Skip to content

Instantly share code, notes, and snippets.

@tuttarealstep
Created May 25, 2016 19:08
Show Gist options
  • Save tuttarealstep/92bc10636745050abc0b7cd5948d78bc to your computer and use it in GitHub Desktop.
Save tuttarealstep/92bc10636745050abc0b7cd5948d78bc to your computer and use it in GitHub Desktop.
An RESTfulAPI system
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ ./index.php [L]
</IfModule>
{
"name": "tuttarealstep/phpRest",
"description": "An RESTfulAPI system",
"minimum-stability": "dev",
"license": "GPL-3.0+",
"authors": [
{
"name": "Stefano Valenzano",
"email": "valenzano.stefano99@gmail.com"
}
],
"require": {
"php": ">=7.0.0",
"monolog/monolog": "^1.18"
},
"autoload": {
"psr-4": {
"phpRest\\": "src/"
}
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 19.37
*/
$Application = require_once __DIR__ . '/src/Bootstrap.php';
if ($Application)
{
$Application->run();
}
<?php
namespace phpRest\App\API\defaultAPI\API_news;
class test
{
private $Application;
private $Request;
function __construct($Application)
{
$this->Application = $Application;
$this->Request = new \phpRest\App\Http\Request();
}
function api_function($data = null)
{
$this->Request->setResponseContentType("text/html");
$data = unserialize($data);
print_r($data);
print_r($this->Request->getRequest());
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 19.32
*/
/*
* Database Settings
*/
$config['database']['host'] = "localhost";
$config['database']['user'] = "root";
$config['database']['password'] = "";
$config['database']['name'] = "";
/*
* Locale Settings
*/
$config['locale']['timezone'] = "Europe/Rome";
/*
* Security
*/
$config['ShowFullError'] = true; //Warning if true this can return private information like database password or others things! || ---
$config['debugMODE'] = true; //true = on / false = off || ----
$config['enable_testAPI'] = true;
/*
* EXPERT MODE
*/
$config['project_namespace'] = 'phpRest';
$config['default_api_url'] = 'api';
$config['json_request'] = true;
<?php
/**
* User: tuttarealstep
* Date: 20/05/16
* Time: 12.07
*/
namespace phpRest\App\Http;
class Request
{
private $Method;
private $Request;
private $Server;
private $ContentType;
private $ResponseCode;
function __construct()
{
$this->initialize();
}
private function initialize()
{
$this->setMethod();
$this->setRequest();
$this->setResponseContentType();
$this->setResponseCode();
$this->setServer();
}
private function setMethod()
{
$this->Method = $_SERVER['REQUEST_METHOD'];
}
private function setRequest(bool $json_decode = true)
{
if($json_decode)
{
$this->Request = json_decode(file_get_contents('php://input'), true);
} else {
$this->Request = file_get_contents('php://input');
}
}
public function setResponseContentType(string $ContentType = '')
{
if(!empty($ContentType))
{
$this->ContentType = $ContentType;
} else {
$this->ContentType = 'application/json';
}
}
public function setResponseCode(int $ResponseCode = 200)
{
if($ResponseCode != 200)
{
$this->ResponseCode = $ResponseCode;
} else {
$this->ResponseCode = 200;
}
}
public function sendResponse()
{
http_response_code($this->ResponseCode);
header('Content-Type: ' . $this->ContentType);
}
public function isGET()
{
if($this->Method === "GET")
{
return true;
}
return false;
}
public function isPOST()
{
if($this->Method === "POST")
{
return true;
}
return false;
}
public function isPUT()
{
if($this->Method === "PUT")
{
return true;
}
return false;
}
public function isDELETE()
{
if($this->Method === "DELETE")
{
return true;
}
return false;
}
function isAjax()
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest")
{
return true;
}
return false;
}
private function setServer()
{
$this->Server = $_SERVER;
}
function getServer(string $variable = '')
{
if(!empty($variable))
{
return $this->Server[$variable];
} else {
return $this->Server;
}
}
public function getMethod()
{
return $this->Method;
}
public function getRequest()
{
return $this->Request;
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 21.15
*/
namespace phpRest\App\Utils;
use \phpRest\Application;
class Api
{
private $Application;
private $ApiPath = 'API', $ApiType = '';
private $Request = [], $RequestData = [];
function __construct(Application $Application)
{
$this->Application = $Application;
}
public function manageRequest()
{
$this->getRequest();
$this->loadRequest();
$this->sendRequest();
}
private function getRequest()
{
$router_url = $this->Application->getRouter()->getURL();
//print_r($router_url);
if(count($router_url) > 1) {
if ($router_url[0] == 'test') {
$this->ApiType = 'testAPI';
} elseif($router_url[0] == $this->Application->getConfiguration('settings')['default_api_url'])
{
$this->ApiType = 'defaultAPI';
}
if(!empty($this->ApiType))
{
unset($router_url[0]);
$router_url[1] = 'API_'.$router_url[1];
$this->Request = $router_url;
}
}
//print_r($router_url);
//print_r($this->API_type);
}
private function loadRequest()
{
if($this->ApiType == 'defaultAPI'):
$this->Load( 'App/API/defaultAPI/' , $this->Request);
elseif($this->ApiType == 'testAPI'):
if($this->Application->getConfiguration('settings')['enable_testAPI'])
{
$this->Load( 'App/API/testAPI/' , $this->Request);
}
endif;
}
function Load($path = 'App/API/defaultAPI/', $request_array = [])
{
$array_count = count($request_array);
$find_path = $path;
$array = [];
for($i = 1; $i <= $array_count; $i++) {
if (is_dir(R_PATH_S . $find_path . $request_array[$i])) {
$find_path = $find_path . $request_array[$i] . '/';
} else {
if (is_file(R_PATH_S . $find_path . $request_array[$i] . '.php')) {
if ($i < $array_count) {
for ($i_a = $i; $i_a <= $array_count; $i_a++){
array_push($array, $request_array[$i_a]);
}
unset($array[0]);
$this->Request_Param = serialize($array);
}
$this->Request_Data = '\\' . $this->Application->getConfiguration('settings')['project_namespace'] . '\\' . str_replace('/', '\\', $find_path . $request_array[$i]);
break;
}
}
}
}
private function sendRequest($return = false)
{
try {
if (!empty($this->Request_Data)):
$sendResponse = new $this->Request_Data($this->Application);
if(!empty($this->Request_Param)){
if($return)
return $sendResponse->api_function($this->Request_Param);
else
echo $sendResponse->api_function($this->Request_Param);
} else {
if($return)
return $sendResponse->api_function();
else
echo $sendResponse->api_function();
}
endif;
} catch (\Exception $e) {
//todo logger
}
return false;
}
function __destruct()
{
$this->Request = null;
$this->RequestData = null;
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 20.53
*/
namespace phpRest\App\Utils;
use \phpRest\Application;
class Router
{
private $Application;
private $urlFound;
function __construct(Application $Application)
{
$this->Application = $Application;
$this->urlFound = $this->getURL();
}
/**
* Return the url of the visited page in an array
*
* @return array
*/
public function getURL(){
header('Cache-Control: no-cache');
header('Pragma: no-cache');
header("Access-Control-Allow-Origin: *");
$url_complete = explode('/', $_SERVER['REQUEST_URI']);
$script_complete = explode('/', $_SERVER['SCRIPT_NAME']);
for($i = 0; $i < count($script_complete);){
if (@$url_complete[$i] == @$script_complete[$i]){
unset($url_complete[$i]);
}
$i++;
}
@$url_value = array_values($url_complete);
for($i_count = 1; $i_count <= count($url_value) - 1; $i_count++){
if(strpos($url_value[ $i_count ], "?") !== false ) {
@$url_get_value = explode("?", $url_value[ $i_count ]);
$url_value[ $i_count ] = $url_get_value[0];
unset($url_get_value[0]);
array_splice( $url_value, $i_count + 1, 0, $url_get_value );
// @$url_value[] = implode("&", $url_get_value);
}
/*if(strpos($url_value[ count($url_value) - 1 ], "?") !== false ){
//Found ( "?" )
@$url_get_value = explode("?", $url_value[ count($url_value) - 1 ]);
$url_value[ count($url_value) - 1 ] = $url_get_value[0];
unset($url_get_value[0]);
@$url_value[] = implode("&", $url_get_value);
}*/
}
return $url_value;
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 19.29
*/
namespace phpRest;
use \Monolog\Handler\StreamHandler;
use \Monolog\Logger;
use \phpRest\App\Http\Request;
use \phpRest\App\Utils\Router;
use \phpRest\App\Utils\Api;
class Application
{
private $configuration;
private $logger;
private $router;
private $request;
private $api;
function __construct(Array $configuration)
{
$this->configuration = $configuration;
$this->configuration['phpRest_version'] = '1.0';
/* Initialize */
$this->initialize();
}
private function initialize()
{
if($this->getConfiguration('settings')['debugMODE'] === false)
{
error_reporting(E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING);
} else {
error_reporting(E_ALL);
ini_set('display_errors', '1');
}
/* Initialize Logger */
$this->init_logger();
/* Set locale (default_time_zone ...) */
$this->init_locale();
/* Initialize Database */
$this->init_database();
/* Initialize Router */
$this->init_router();
/**
* Initialize restAPI
* For load useful functions
*/
$this->init_restAPI();
/**
* Initialize Api
* For load api file
*/
$this->init_api();
}
private function init_logger()
{
$this->logger = function()
{
$logger = new Logger('phpRest');
$file_handler = new StreamHandler("src/App/Storage/Logs/application.log");
$logger->pushHandler($file_handler);
return $logger;
};
}
private function init_locale()
{
date_default_timezone_set($this->getConfiguration('settings')['locale']['timezone'] ?: ini_get('date.timezone') ?: 'UTC');
}
private function init_database()
{
}
private function init_router()
{
$this->router = new Router($this);
}
private function init_restAPI()
{
$this->request = new Request();
}
private function init_api()
{
$this->api = new Api($this);
}
public function run()
{
$this->api->manageRequest();
$this->request->sendResponse();
}
/**
* Return configuration array with all configurations
* @return array
*/
public function getConfiguration(string $configuration_layer_name = null)
{
if(!empty($configuration_layer_name))
{
return $this->configuration[$configuration_layer_name];
} else {
return $this->configuration;
}
}
public function getLogger()
{
return $this->logger;
}
public function getRouter()
{
return $this->router;
}
public function getRequest()
{
return $this->request;
}
public function getApi()
{
return $this->api;
}
}
<?php
/**
* User: tuttarealstep
* Date: 19/05/16
* Time: 19.29
*/
namespace phpRest;
define( 'R_PATH_S', __DIR__ . '/' );
return call_user_func(
function()
{
mb_internal_encoding('UTF-8');
mb_http_output('UTF-8');
$_R_PATH = realpath(__DIR__ . '/..');
require $_R_PATH . '/vendor/autoload.php';
/* Load configuration file */
if ( file_exists( $_R_PATH . '/src/App/Configuration/Config.php') ) {
$config = [];
require_once($_R_PATH . '/src/App/Configuration/Config.php');
} else {
$config = null;
}
$Application = new Application(["settings" => $config]);
return $Application;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment