[BUGFIX] Improvements

- Fixed errors with getRoute method.
- Added Response and Request classes.
- Added CSRF stuff.
- Cleanup and bugfixes.
This commit is contained in:
Simon Sessingø
2015-10-18 17:36:06 +02:00
parent 0650e5ba93
commit b3b362a9e6
11 changed files with 272 additions and 90 deletions
+74
View File
@@ -0,0 +1,74 @@
<?php
namespace Pecee;
class CsrfToken {
const CSRF_KEY = 'csrf_token';
protected static $instance;
protected $lastToken;
protected $currentToken;
public static function getInstance() {
if(self::$instance === null) {
self::$instance = new static();
}
return self::$instance;
}
public function __construct() {
$this->lastToken = isset($_SESSION[self::CSRF_KEY]) ? $_SESSION[self::CSRF_KEY] : null;
$this->currentToken = $this->generate();
// Initialise session, if it hasn't been initialised.
if(!isset($_SESSION)) {
session_start();
}
$_SESSION['csrf_token'] = $this->currentToken;
}
/**
* Generate random identifier for CSRF token
* @return string
*/
public static function generate() {
if (function_exists('mcrypt_create_iv')) {
return bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
}
return bin2hex(openssl_random_pseudo_bytes(32));
}
/**
* Validate valid CSRF token
*
* @param string $token
* @return bool
*/
public function validate($token) {
return hash_equals($token, $_SESSION[self::CSRF_KEY]);
}
/**
* @return string|null
*/
public function getLastToken(){
return $this->lastToken;
}
/**
* @param string|null $lastToken
*/
public function setLastToken($lastToken){
$this->lastToken = $lastToken;
}
/**
* @return string|null
*/
public function getCurrentToken(){
return $this->currentToken;
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace Pecee\Http\Middleware;
use Pecee\Http\Request;
use Pecee\SimpleRouter\RouterEntry;
abstract class Middleware
{
public function handle(Request $request) {
return true;
}
}
@@ -0,0 +1,9 @@
<?php
namespace Pecee\Http\Middleware;
class VerifyCsrfToken extends Middleware {
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace Pecee\Http;
class Request {
protected $uri;
protected $host;
protected $method;
public function __construct() {
$this->host = $_SERVER['HTTP_HOST'];
$this->uri = rtrim($_SERVER['REQUEST_URI'], '/') . '/';
$this->method = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
}
/**
* @return string
*/
public function getUri() {
return $this->uri;
}
/**
* @return string
*/
public function getHost() {
return $this->host;
}
/**
* @return string
*/
public function getMethod() {
return $this->method;
}
/**
* Get http basic auth user
* @return string|null
*/
public function getUser() {
$data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST']);
return (isset($data['username'])) ? $data['username'] : null;
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Pecee\Http;
class Response {
/**
* Set the http status code
*
* @param int $code
* @return self $this
*/
public function httpCode($code) {
http_response_code($code);
return $this;
}
/**
* Redirect the response
*
* @param string $url
*/
public function redirect($url) {
header('location: ' . $url);
}
}
+24 -38
View File
@@ -1,19 +1,19 @@
<?php <?php
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
use Pecee\Url; use Pecee\Url;
class RouterBase { class RouterBase {
protected static $instance; protected static $instance;
protected $request;
protected $currentRoute; protected $currentRoute;
protected $routes; protected $routes;
protected $processedRoutes; protected $processedRoutes;
protected $controllerUrlMap; protected $controllerUrlMap;
protected $backstack; protected $backstack;
protected $requestUri;
protected $requestMethod;
protected $loadedRoute; protected $loadedRoute;
protected $defaultNamespace; protected $defaultNamespace;
@@ -24,8 +24,7 @@ class RouterBase {
$this->routes = array(); $this->routes = array();
$this->backstack = array(); $this->backstack = array();
$this->controllerUrlMap = array(); $this->controllerUrlMap = array();
$this->requestUri = $_SERVER['REQUEST_URI']; $this->request = new Request();
$this->requestMethod = (isset($_POST['_method'])) ? strtolower($_POST['_method']) : strtolower($_SERVER['REQUEST_METHOD']);
} }
public function addRoute(RouterEntry $route) { public function addRoute(RouterEntry $route) {
@@ -42,9 +41,8 @@ class RouterBase {
/* @var $route RouterEntry */ /* @var $route RouterEntry */
foreach($routes as $route) { foreach($routes as $route) {
if($this->defaultNamespace) { if($this->defaultNamespace && !$route->getNamespace()) {
$namespace = null; $namespace = null;
if ($route->getNamespace()) { if ($route->getNamespace()) {
$namespace = $this->defaultNamespace . '\\' . $route->getNamespace(); $namespace = $this->defaultNamespace . '\\' . $route->getNamespace();
} else { } else {
@@ -71,7 +69,7 @@ class RouterBase {
$this->currentRoute = $route; $this->currentRoute = $route;
if($route instanceof RouterGroup && is_callable($route->getCallback())) { if($route instanceof RouterGroup && is_callable($route->getCallback())) {
$route->renderRoute($this->requestMethod); $route->renderRoute($this->request);
} }
$this->currentRoute = null; $this->currentRoute = null;
@@ -96,17 +94,17 @@ class RouterBase {
}); });
foreach($this->controllerUrlMap as $route) { foreach($this->controllerUrlMap as $route) {
$routeMatch = $route->matchRoute($this->requestMethod, rtrim($this->requestUri, '/') . '/'); $routeMatch = $route->matchRoute($this->request);
if($routeMatch && !($routeMatch instanceof RouterGroup)) { if($routeMatch && !($routeMatch instanceof RouterGroup)) {
$this->loadedRoute = $routeMatch; $this->loadedRoute = $routeMatch;
$routeMatch->renderRoute($this->requestMethod); $routeMatch->renderRoute($this->request);
break; break;
} }
} }
if(!$this->loadedRoute) { if(!$this->loadedRoute) {
throw new RouterException(sprintf('Route not found: %s', $this->requestUri), 404); throw new RouterException(sprintf('Route not found: %s', $this->request->getUri()), 404);
} }
} }
@@ -134,20 +132,6 @@ class RouterBase {
return null; return null;
} }
/**
* @return string
*/
public function getRequestMethod() {
return $this->requestMethod;
}
/**
* @return string
*/
public function getRequestUri() {
return $this->requestUri;
}
/** /**
* @return array * @return array
*/ */
@@ -169,10 +153,20 @@ class RouterBase {
return $this->routes; return $this->routes;
} }
/**
* Get current request
*
* @return Request
*/
public function getRequest() {
return $this->request;
}
protected function processUrl($route, $method = null, $parameters = null, $getParams = null) { protected function processUrl($route, $method = null, $parameters = null, $getParams = null) {
$url = rtrim($route->getUrl(), '/') . '/'; $url = rtrim($route->getUrl(), '/') . '/';
if($method !== null) { if(($route instanceof RouterController || $route instanceof RouterRessource) && $method !== null) {
$url .= $method . '/'; $url .= $method . '/';
} }
@@ -226,24 +220,16 @@ class RouterBase {
} }
if($c === $controller || strpos($c, $controller) === 0) { if($c === $controller || strpos($c, $controller) === 0) {
if(stripos($c, '@') !== false) { return $this->processUrl($route, $route->getMethod(), $parameters, $getParams);
$tmp = explode('@', $route->getCallback());
$method = strtolower($tmp[1]);
}
return $this->processUrl($route, $method, $parameters, $getParams);
} }
} }
$c = '';
// No match has yet been found, let's try to guess what url that should be returned // No match has yet been found, let's try to guess what url that should be returned
foreach($this->controllerUrlMap as $route) { foreach($this->controllerUrlMap as $route) {
if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) { if($route instanceof RouterRoute && !is_callable($route->getCallback()) && stripos($route->getCallback(), '@') !== false) {
$c = $route->getCallback(); $c = $route->getClass();
if(stripos($controller, '@') !== false) {
$tmp = explode('@', $controller);
$c = $tmp[0];
}
} else if($route instanceof RouterController || $route instanceof RouterRessource) { } else if($route instanceof RouterController || $route instanceof RouterRessource) {
$c = $route->getController(); $c = $route->getController();
} }
@@ -254,7 +240,7 @@ class RouterBase {
$method = $tmp[1]; $method = $tmp[1];
} }
if($controller == $c) { if($controller === $c) {
return $this->processUrl($route, $method, $parameters, $getParams); return $this->processUrl($route, $method, $parameters, $getParams);
} }
} }
+4 -2
View File
@@ -1,6 +1,8 @@
<?php <?php
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
class RouterController extends RouterEntry { class RouterController extends RouterEntry {
const DEFAULT_METHOD = 'index'; const DEFAULT_METHOD = 'index';
@@ -15,8 +17,8 @@ class RouterController extends RouterEntry {
$this->controller = $controller; $this->controller = $controller;
} }
public function matchRoute($requestMethod, $url) { public function matchRoute(Request $request) {
$url = parse_url($url); $url = parse_url($request->getUri());
$url = rtrim($url['path'], '/') . '/'; $url = rtrim($url['path'], '/') . '/';
if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) {
+45 -15
View File
@@ -2,6 +2,9 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Middleware\Middleware;
use Pecee\Http\Request;
abstract class RouterEntry { abstract class RouterEntry {
const REQUEST_TYPE_POST = 'post'; const REQUEST_TYPE_POST = 'post';
@@ -27,14 +30,6 @@ abstract class RouterEntry {
$this->parametersRegex = array(); $this->parametersRegex = array();
} }
protected function loadClass($name) {
if(!class_exists($name)) {
throw new RouterException(sprintf('Class %s does not exist', $name));
}
return new $name();
}
/** /**
* Returns callback name/identifier for the current route based on the callback. * Returns callback name/identifier for the current route based on the callback.
* Useful if you need to get a unique identifier for the loaded route, for instance * Useful if you need to get a unique identifier for the loaded route, for instance
@@ -65,6 +60,22 @@ abstract class RouterEntry {
return $this->callback; return $this->callback;
} }
public function getMethod() {
if(strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[1];
}
return null;
}
public function getClass() {
if(strpos($this->callback, '@') !== false) {
$tmp = explode('@', $this->callback);
return $tmp[0];
}
return null;
}
/** /**
* @param string $prefix * @param string $prefix
* @return self * @return self
@@ -171,7 +182,7 @@ abstract class RouterEntry {
* @return self * @return self
*/ */
public function addSettings(array $settings) { public function addSettings(array $settings) {
array_merge($this->settings, $settings); $this->settings = array_merge($this->settings, $settings);
return $this; return $this;
} }
@@ -209,12 +220,30 @@ abstract class RouterEntry {
$this->settings[$name] = $value; $this->settings[$name] = $value;
} }
public function renderRoute($requestMethod) { protected function loadClass($name) {
// Load middleware if(!class_exists($name)) {
if($this->getMiddleware()) { throw new RouterException(sprintf('Class %s does not exist', $name));
$this->loadClass($this->getMiddleware());
} }
return new $name();
}
protected function loadMiddleware(Request $request) {
if($this->getMiddleware()) {
if (!($this->getMiddleware() instanceof Middleware)) {
throw new RouterException($this->getMiddleware() . ' must be instance of Middleware');
}
/* @var $class Middleware */
$class = $this->loadClass($this->getMiddleware());
$class->handle($request);
}
}
public function renderRoute(Request $request) {
// Load middleware
$this->loadMiddleware($request);
if(is_object($this->getCallback()) && is_callable($this->getCallback())) { if(is_object($this->getCallback()) && is_callable($this->getCallback())) {
// When the callback is a function // When the callback is a function
@@ -223,8 +252,9 @@ abstract class RouterEntry {
// When the callback is a method // When the callback is a method
$controller = explode('@', $this->getCallback()); $controller = explode('@', $this->getCallback());
$className = $this->getNamespace() . '\\' . $controller[0]; $className = $this->getNamespace() . '\\' . $controller[0];
$class = $this->loadClass($className); $class = $this->loadClass($className);
$method = $requestMethod . ucfirst($controller[1]); $method = $request->getMethod() . ucfirst($controller[1]);
if (!method_exists($class, $method)) { if (!method_exists($class, $method)) {
throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404); throw new RouterException(sprintf('Method %s does not exist in class %s', $method, $className), 404);
@@ -238,6 +268,6 @@ abstract class RouterEntry {
return null; return null;
} }
abstract function matchRoute($requestMethod, $url); abstract function matchRoute(Request $request);
} }
+6 -4
View File
@@ -2,24 +2,26 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
class RouterGroup extends RouterEntry { class RouterGroup extends RouterEntry {
public function __construct() { public function __construct() {
parent::__construct(); parent::__construct();
} }
public function matchRoute($requestMethod, $url) { public function matchRoute(Request $request) {
// Check if request method is allowed // Check if request method is allowed
if(strtolower($url) == strtolower($this->prefix) || stripos($url, $this->prefix) === 0) { if(strtolower($request->getUri()) == strtolower($this->prefix) || stripos($request->getUri(), $this->prefix) === 0) {
$hasAccess = (!$this->method); $hasAccess = (!$this->method);
if($this->method) { if($this->method) {
if(is_array($this->method)) { if(is_array($this->method)) {
$hasAccess = (in_array($requestMethod, $this->method)); $hasAccess = (in_array($request->getMethod(), $this->method));
} else { } else {
$hasAccess = strtolower($this->method) == strtolower($requestMethod); $hasAccess = strtolower($this->method) == strtolower($request->getMethod());
} }
} }
+9 -9
View File
@@ -1,6 +1,8 @@
<?php <?php
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Http\Request;
class RouterRessource extends RouterEntry { class RouterRessource extends RouterEntry {
const DEFAULT_METHOD = 'index'; const DEFAULT_METHOD = 'index';
@@ -17,11 +19,9 @@ class RouterRessource extends RouterEntry {
$this->postMethod = strtolower(($_SERVER['REQUEST_METHOD'] != 'GET') ? 'post' : 'get'); $this->postMethod = strtolower(($_SERVER['REQUEST_METHOD'] != 'GET') ? 'post' : 'get');
} }
public function renderRoute($requestMethod) { public function renderRoute(Request $request) {
// Load middleware // Load middleware
if($this->getMiddleware()) { $this->loadMiddleware($request);
$this->loadClass($this->getMiddleware());
}
if(is_object($this->getCallback()) && is_callable($this->getCallback())) { if(is_object($this->getCallback()) && is_callable($this->getCallback())) {
// When the callback is a function // When the callback is a function
@@ -51,8 +51,8 @@ class RouterRessource extends RouterEntry {
return $this; return $this;
} }
public function matchRoute($requestMethod, $url) { public function matchRoute(Request $request) {
$url = parse_url($url); $url = parse_url($request->getUri());
$url = rtrim($url['path'], '/') . '/'; $url = rtrim($url['path'], '/') . '/';
if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { if(strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) {
@@ -72,12 +72,12 @@ class RouterRessource extends RouterEntry {
if (count($path)) { if (count($path)) {
// Delete // Delete
if($requestMethod === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) { if($request->getMethod() === self::REQUEST_TYPE_DELETE && $this->postMethod === self::REQUEST_TYPE_POST) {
return $this->call('destroy', $args); return $this->call('destroy', $args);
} }
// Update // Update
if(in_array($requestMethod, array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) { if(in_array($request->getMethod(), array('put', 'patch')) && $this->postMethod === self::REQUEST_TYPE_POST) {
return $this->call('update', array_merge(array($action), $args)); return $this->call('update', array_merge(array($action), $args));
} }
@@ -87,7 +87,7 @@ class RouterRessource extends RouterEntry {
} }
// Create // Create
if(strtolower($action) === 'create' && $requestMethod === self::REQUEST_TYPE_GET) { if(strtolower($action) === 'create' && $request->getMethod() === self::REQUEST_TYPE_GET) {
return $this->call('create', $args); return $this->call('create', $args);
} }
+14 -21
View File
@@ -2,8 +2,7 @@
namespace Pecee\SimpleRouter; namespace Pecee\SimpleRouter;
use Pecee\Registry; use Pecee\Http\Request;
use Pecee\Router;
class RouterRoute extends RouterEntry { class RouterRoute extends RouterEntry {
@@ -19,10 +18,14 @@ class RouterRoute extends RouterEntry {
$this->requestTypes = array(); $this->requestTypes = array();
} }
protected function parseParameters($url) { protected function parseParameters($url, $multiple = false) {
$parameters = array(); $parameters = array();
if($multiple) {
preg_match_all('/{([A-Za-z\-\_]*?)}/is', $url, $parameters); preg_match_all('/{([A-Za-z\-\_]*?)}/is', $url, $parameters);
} else {
preg_match('/{([A-Za-z\-\_]*?)}/is', $url, $parameters);
}
if(isset($parameters[1]) && count($parameters[1]) > 0) { if(isset($parameters[1]) && count($parameters[1]) > 0) {
return $parameters[1]; return $parameters[1];
@@ -31,24 +34,12 @@ class RouterRoute extends RouterEntry {
return null; return null;
} }
protected function parseParameter($path) { public function matchRoute(Request $request) {
$parameters = array();
preg_match('/{([A-Za-z\-\_]*?)}/is', $path, $parameters);
if(isset($parameters[1]) && count($parameters[1]) > 0) {
return $parameters[1];
}
return null;
}
public function matchRoute($requestMethod, $url) {
// Check if request method is allowed // Check if request method is allowed
if(count($this->requestTypes) === 0 || in_array($requestMethod, $this->requestTypes)) { if(count($this->requestTypes) === 0 || in_array($request->getMethod(), $this->requestTypes)) {
$url = parse_url($url); $url = parse_url($request->getUri());
$url = $url['path']; $url = $url['path'];
$url = explode('/', trim($url, '/')); $url = explode('/', trim($url, '/'));
@@ -63,7 +54,7 @@ class RouterRoute extends RouterEntry {
// Check if url matches // Check if url matches
foreach($route as $i => $path) { foreach($route as $i => $path) {
$parameter = $this->parseParameter($path); $parameter = $this->parseParameters($path);
// Check if parameter of path matches, otherwise quit.. // Check if parameter of path matches, otherwise quit..
if(is_null($parameter) && strtolower($path) != strtolower($url[$i])) { if(is_null($parameter) && strtolower($path) != strtolower($url[$i])) {
@@ -116,7 +107,7 @@ class RouterRoute extends RouterEntry {
*/ */
public function setUrl($url) { public function setUrl($url) {
$parameters = $this->parseParameters($url); $parameters = $this->parseParameters($url, true);
if($parameters !== null) { if($parameters !== null) {
foreach($parameters as $param) { foreach($parameters as $param) {
@@ -144,7 +135,9 @@ class RouterRoute extends RouterEntry {
* @return self * @return self
*/ */
public function addAlias($alias) { public function addAlias($alias) {
$this->aliases[] = $alias; $arr = $this->aliases;
$arr[] = $alias;
$this->aliases = $arr;
return $this; return $this;
} }