From 1c515119b4abf43c6e3645d99f3d9add5333ef41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Sessing=C3=B8?= Date: Fri, 25 Nov 2016 12:51:45 +0100 Subject: [PATCH] Development - Ensure that request-method is always lowercase. - Fixed spaces instead of tabs to comply with PSR-2. --- src/Pecee/Controllers/IRestController.php | 69 +- src/Pecee/CsrfToken.php | 113 +- src/Pecee/Handlers/IExceptionHandler.php | 14 +- src/Pecee/Http/Input/IInputItem.php | 8 +- src/Pecee/Http/Input/Input.php | 357 +++--- src/Pecee/Http/Input/InputFile.php | 310 ++--- src/Pecee/Http/Input/InputItem.php | 112 +- .../Http/Middleware/BaseCsrfVerifier.php | 135 +-- src/Pecee/Http/Middleware/IMiddleware.php | 12 +- src/Pecee/Http/Request.php | 376 +++--- src/Pecee/Http/Response.php | 194 ++-- src/Pecee/SimpleRouter/IRouterBootManager.php | 14 +- .../SimpleRouter/Route/IControllerRoute.php | 52 +- src/Pecee/SimpleRouter/Route/IGroupRoute.php | 92 +- .../SimpleRouter/Route/ILoadableRoute.php | 78 +- src/Pecee/SimpleRouter/Route/IRoute.php | 324 +++--- .../SimpleRouter/Route/LoadableRoute.php | 304 ++--- src/Pecee/SimpleRouter/Route/Route.php | 1024 ++++++++--------- .../SimpleRouter/Route/RouteController.php | 304 ++--- src/Pecee/SimpleRouter/Route/RouteGroup.php | 284 ++--- .../SimpleRouter/Route/RouteResource.php | 310 ++--- src/Pecee/SimpleRouter/Route/RouteUrl.php | 62 +- src/Pecee/SimpleRouter/Router.php | 956 +++++++-------- src/Pecee/SimpleRouter/SimpleRouter.php | 614 +++++----- 24 files changed, 3052 insertions(+), 3066 deletions(-) diff --git a/src/Pecee/Controllers/IRestController.php b/src/Pecee/Controllers/IRestController.php index ca391e0..9fe070b 100644 --- a/src/Pecee/Controllers/IRestController.php +++ b/src/Pecee/Controllers/IRestController.php @@ -1,46 +1,47 @@ getToken() !== null) { - return hash_equals($token, $this->getToken()); - } - return false; - } + return bin2hex(openssl_random_pseudo_bytes(32)); + } - /** - * Set csrf token cookie - * - * @param $token - */ - public function setToken($token) - { - setcookie(static::CSRF_KEY, $token, time() + 60 * 120, '/'); - } + /** + * Validate valid CSRF token + * + * @param string $token + * @return bool + */ + public function validate($token) + { + if ($token !== null && $this->getToken() !== null) { + return hash_equals($token, $this->getToken()); + } - /** - * Get csrf token - * @return string|null - */ - public function getToken() - { - if ($this->hasToken()) { - return $_COOKIE[static::CSRF_KEY]; - } - return null; - } + return false; + } - /** - * Returns whether the csrf token has been defined - * @return bool - */ - public function hasToken() - { - return isset($_COOKIE[static::CSRF_KEY]); - } + /** + * Set csrf token cookie + * + * @param $token + */ + public function setToken($token) + { + setcookie(static::CSRF_KEY, $token, time() + 60 * 120, '/'); + } + + /** + * Get csrf token + * @return string|null + */ + public function getToken() + { + if ($this->hasToken()) { + return $_COOKIE[static::CSRF_KEY]; + } + + return null; + } + + /** + * Returns whether the csrf token has been defined + * @return bool + */ + public function hasToken() + { + return isset($_COOKIE[static::CSRF_KEY]); + } } \ No newline at end of file diff --git a/src/Pecee/Handlers/IExceptionHandler.php b/src/Pecee/Handlers/IExceptionHandler.php index fa2561e..4a3f600 100644 --- a/src/Pecee/Handlers/IExceptionHandler.php +++ b/src/Pecee/Handlers/IExceptionHandler.php @@ -6,12 +6,12 @@ use Pecee\SimpleRouter\Route\ILoadableRoute; interface IExceptionHandler { - /** - * @param Request $request - * @param ILoadableRoute $route - * @param \Exception $error - * @return Request|null - */ - public function handleError(Request $request, ILoadableRoute &$route = null, \Exception $error); + /** + * @param Request $request + * @param ILoadableRoute $route + * @param \Exception $error + * @return Request|null + */ + public function handleError(Request $request, ILoadableRoute &$route = null, \Exception $error); } \ No newline at end of file diff --git a/src/Pecee/Http/Input/IInputItem.php b/src/Pecee/Http/Input/IInputItem.php index 5846788..0857453 100644 --- a/src/Pecee/Http/Input/IInputItem.php +++ b/src/Pecee/Http/Input/IInputItem.php @@ -4,12 +4,12 @@ namespace Pecee\Http\Input; interface IInputItem { - public function getIndex(); + public function getIndex(); - public function getName(); + public function getName(); - public function getValue(); + public function getValue(); - public function __toString(); + public function __toString(); } \ No newline at end of file diff --git a/src/Pecee/Http/Input/Input.php b/src/Pecee/Http/Input/Input.php index f14f2a2..614949c 100644 --- a/src/Pecee/Http/Input/Input.php +++ b/src/Pecee/Http/Input/Input.php @@ -5,247 +5,220 @@ use Pecee\Http\Request; class Input { - /** - * @var array - */ - public $get = []; + /** + * @var array + */ + public $get = []; - /** - * @var array - */ - public $post = []; + /** + * @var array + */ + public $post = []; - /** - * @var array - */ - public $file = []; + /** + * @var array + */ + public $file = []; - /** - * @var Request - */ - protected $request; + /** + * @var Request + */ + protected $request; - protected $invalidContentType = false; + public function __construct(Request $request) + { + $this->request = $request; - protected $invalidContentTypes = [ - 'text/plain', - 'application/x-www-form-urlencoded', - ]; + $this->parseInputs(); + } - public function __construct(Request $request) - { - $this->request = $request; + protected function parseInputs() + { + /* Parse get requests */ + if (count($_GET) > 0) { + $this->get = $this->handleGetPost($_GET); + } - if ($request->getMethod() !== 'get') { + /* Parse post requests */ + $postVars = $_POST; - $requestContentType = $request->getHeader('http-content-type'); + if (in_array($this->request->getMethod(), ['put', 'patch', 'delete']) === true) { + parse_str(file_get_contents('php://input'), $postVars); + } - $max = count($this->invalidContentTypes) - 1; + if (count($postVars) > 0) { + $this->post = $this->handleGetPost($postVars); + } - for ($i = $max; $i >= 0; $i--) { + /* Parse get requests */ - $contentType = $this->invalidContentType[$i]; + if (count($_FILES) > 0) { - if (stripos($requestContentType, $contentType) === 0) { - $this->invalidContentType = true; - break; - } - } - } + $max = count($_FILES) - 1; + $keys = array_keys($_FILES); - if ($this->invalidContentType === false) { - $this->parseInputs(); - } + for ($i = $max; $i >= 0; $i--) { - } + $key = $keys[$i]; + $value = $_FILES[$key]; - protected function parseInputs() - { - /* Parse get requests */ - if (count($_GET) > 0) { - $this->get = $this->handleGetPost($_GET); - } + // Handle array input + if (is_array($value['name']) === false) { + $values['index'] = $key; + $this->file[$key] = InputFile::createFromArray(array_merge($value, $values)); + continue; + } - /* Parse post requests */ - $postVars = $_POST; + $subMax = count($value['name']) - 1; + $keys = array_keys($value['name']); + $output = []; - if (in_array($this->request->getMethod(), ['put', 'patch', 'delete']) === true) { - parse_str(file_get_contents('php://input'), $postVars); - } + for ($i = $subMax; $i >= 0; $i--) { - if (count($postVars) > 0) { - $this->post = $this->handleGetPost($postVars); - } + $output[$keys[$i]] = InputFile::createFromArray([ + 'index' => $key, + 'error' => $value['error'][$keys[$i]], + 'tmp_name' => $value['tmp_name'][$keys[$i]], + 'type' => $value['type'][$keys[$i]], + 'size' => $value['size'][$keys[$i]], + 'name' => $value['name'][$keys[$i]], + ]); - /* Parse get requests */ + } - if (count($_FILES) > 0) { + $this->file[$key] = $output; + } + } + } - $max = count($_FILES) - 1; - $keys = array_keys($_FILES); + protected function handleGetPost($array) + { + $tmp = []; - for ($i = $max; $i >= 0; $i--) { + $max = count($array) - 1; + $keys = array_keys($array); - $key = $keys[$i]; - $value = $_FILES[$key]; + for ($i = $max; $i >= 0; $i--) { - // Handle array input - if (is_array($value['name']) === false) { - $values['index'] = $key; - $this->file[$key] = InputFile::createFromArray(array_merge($value, $values)); - continue; - } + $key = $keys[$i]; + $value = $array[$key]; - $subMax = count($value['name']) - 1; - $keys = array_keys($value['name']); - $output = []; + // Handle array input + if (is_array($value) === false) { + $tmp[$key] = new InputItem($key, $value); + continue; + } - for ($i = $subMax; $i >= 0; $i--) { + $subMax = count($value) - 1; + $keys = array_keys($value); + $output = []; - $output[$keys[$i]] = InputFile::createFromArray([ - 'index' => $key, - 'error' => $value['error'][$keys[$i]], - 'tmp_name' => $value['tmp_name'][$keys[$i]], - 'type' => $value['type'][$keys[$i]], - 'size' => $value['size'][$keys[$i]], - 'name' => $value['name'][$keys[$i]], - ]); + for ($i = $subMax; $i >= 0; $i--) { + $output[$keys[$i]] = new InputItem($key, $value[$keys[$i]]); + } - } + $tmp[$key] = $output; + } - $this->file[$key] = $output; - } - } - } + return $tmp; + } - protected function handleGetPost($array) - { - $tmp = []; + public function findPost($index, $default = null) + { + return isset($this->post[$index]) ? $this->post[$index] : $default; + } - $max = count($array) - 1; - $keys = array_keys($array); + public function findFile($index, $default = null) + { + return isset($this->file[$index]) ? $this->file[$index] : $default; + } - for ($i = $max; $i >= 0; $i--) { + public function findGet($index, $default = null) + { + return isset($this->get[$index]) ? $this->get[$index] : $default; + } - $key = $keys[$i]; - $value = $array[$key]; + public function getObject($index, $default = null, $method = null) + { + $element = null; - // Handle array input - if (is_array($value) === false) { - $tmp[$key] = new InputItem($key, $value); - continue; - } + if ($method === null || strtolower($method) === 'get') { + $element = $this->findGet($index); + } - $subMax = count($value) - 1; - $keys = array_keys($value); - $output = []; + if ($element === null && $method === null || strtolower($method) === 'post') { + $element = $this->findPost($index); + } - for ($i = $subMax; $i >= 0; $i--) { - $output[$keys[$i]] = new InputItem($key, $value[$keys[$i]]); - } + if ($element === null && $method === null || strtolower($method) === 'file') { + $element = $this->findFile($index); + } - $tmp[$key] = $output; - } + return ($element === null) ? $default : $element; + } - return $tmp; - } + /** + * Get input element value matching index + * + * @param string $index + * @param string|null $default + * @param string|null $method + * @return InputItem|string + */ + public function get($index, $default = null, $method = null) + { + $input = $this->getObject($index, $default, $method); - public function findPost($index, $default = null) - { - return isset($this->post[$index]) ? $this->post[$index] : $default; - } + if ($input instanceof InputItem) { + return (trim($input->getValue()) === '') ? $default : $input->getValue(); + } - public function findFile($index, $default = null) - { - return isset($this->file[$index]) ? $this->file[$index] : $default; - } + return $input; + } - public function findGet($index, $default = null) - { - return isset($this->get[$index]) ? $this->get[$index] : $default; - } + public function exists($index) + { + return ($this->getObject($index) !== null); + } - public function getObject($index, $default = null, $method = null) - { - $element = null; + /** + * Get all get/post items + * @param array|null $filter Only take items in filter + * @return array + */ + public function all(array $filter = null) + { + if ($this->invalidContentType === true) { + return []; + } - if ($method === null || strtolower($method) === 'get') { - $element = $this->findGet($index); - } + $output = $_POST; - if ($element === null && $method === null || strtolower($method) === 'post') { - $element = $this->findPost($index); - } + if ($this->request->getMethod() === 'post') { - if ($element === null && $method === null || strtolower($method) === 'file') { - $element = $this->findFile($index); - } + $contents = file_get_contents('php://input'); - return ($element === null) ? $default : $element; - } + if (stripos(trim($contents), '{') === 0) { + $output = json_decode($contents, true); + if ($output === false) { + $output = []; + } + } + } - /** - * Get input element value matching index - * - * @param string $index - * @param string|null $default - * @param string|null $method - * @return InputItem|string - */ - public function get($index, $default = null, $method = null) - { - $input = $this->getObject($index, $default, $method); + $output = array_merge($_GET, $output); - if ($input instanceof InputItem) { - return (trim($input->getValue()) === '') ? $default : $input->getValue(); - } + if ($filter !== null) { + $output = array_filter($output, function ($key) use ($filter) { + if (in_array($key, $filter)) { + return true; + } - return $input; - } + return false; + }, ARRAY_FILTER_USE_KEY); + } - public function exists($index) - { - return ($this->getObject($index) !== null); - } - - /** - * Get all get/post items - * @param array|null $filter Only take items in filter - * @return array - */ - public function all(array $filter = null) - { - if ($this->invalidContentType === true) { - return []; - } - - $output = $_POST; - - if ($this->request->getMethod() === 'post') { - - $contents = file_get_contents('php://input'); - - if (stripos(trim($contents), '{') === 0) { - $output = json_decode($contents, true); - if ($output === false) { - $output = []; - } - } - } - - $output = array_merge($_GET, $output); - - if ($filter !== null) { - $output = array_filter($output, function ($key) use ($filter) { - if (in_array($key, $filter)) { - return true; - } - - return false; - }, ARRAY_FILTER_USE_KEY); - } - - return $output; - } + return $output; + } } \ No newline at end of file diff --git a/src/Pecee/Http/Input/InputFile.php b/src/Pecee/Http/Input/InputFile.php index 8a38794..679b206 100644 --- a/src/Pecee/Http/Input/InputFile.php +++ b/src/Pecee/Http/Input/InputFile.php @@ -3,188 +3,188 @@ namespace Pecee\Http\Input; class InputFile implements IInputItem { - public $index; - public $name; - public $size; - public $type; - public $error; - public $tmpName; + public $index; + public $name; + public $size; + public $type; + public $error; + public $tmpName; - public function __construct($index) - { - $this->index = $index; + public function __construct($index) + { + $this->index = $index; - // Make the name human friendly, by replace _ with space - $this->name = ucfirst(str_replace('_', ' ', $this->index)); - } + // Make the name human friendly, by replace _ with space + $this->name = ucfirst(str_replace('_', ' ', $this->index)); + } - /** - * @return string - */ - public function getIndex() - { - return $this->index; - } + /** + * @return string + */ + public function getIndex() + { + return $this->index; + } - /** - * @return string - */ - public function getName() - { - return $this->name; - } + /** + * @return string + */ + public function getName() + { + return $this->name; + } - /** - * @return string - */ - public function getSize() - { - return $this->size; - } + /** + * @return string + */ + public function getSize() + { + return $this->size; + } - /** - * @return string - */ - public function getType() - { - return $this->type; - } + /** + * @return string + */ + public function getType() + { + return $this->type; + } - /** - * @return string - */ - public function getError() - { - return $this->error; - } + /** + * @return string + */ + public function getError() + { + return $this->error; + } - public function getMime() - { - return $this->getType(); - } + public function getMime() + { + return $this->getType(); + } - /** - * @return string - */ - public function getTmpName() - { - return $this->tmpName; - } + /** + * @return string + */ + public function getTmpName() + { + return $this->tmpName; + } - public function getExtension() - { - return pathinfo($this->getName(), PATHINFO_EXTENSION); - } + public function getExtension() + { + return pathinfo($this->getName(), PATHINFO_EXTENSION); + } - public function move($destination) - { - return move_uploaded_file($this->tmpName, $destination); - } + public function move($destination) + { + return move_uploaded_file($this->tmpName, $destination); + } - public function getContents() - { - return file_get_contents($this->tmpName); - } + public function getContents() + { + return file_get_contents($this->tmpName); + } - public function setName($name) - { - $this->name = $name; + public function setName($name) + { + $this->name = $name; - return $this; - } + return $this; + } - /** - * Set file temp. name - * @param string $name - * @return static $this - */ - public function setTmpName($name) - { - $this->tmpName = $name; + /** + * Set file temp. name + * @param string $name + * @return static $this + */ + public function setTmpName($name) + { + $this->tmpName = $name; - return $this; - } + return $this; + } - /** - * Set file size - * @param int $size - * @return static $this - */ - public function setSize($size) - { - $this->size = $size; + /** + * Set file size + * @param int $size + * @return static $this + */ + public function setSize($size) + { + $this->size = $size; - return $this; - } + return $this; + } - /** - * Set type - * @param string $type - * @return static $this - */ - public function setType($type) - { - $this->type = $type; + /** + * Set type + * @param string $type + * @return static $this + */ + public function setType($type) + { + $this->type = $type; - return $this; - } + return $this; + } - /** - * Set error - * @param int $error - * @return static $this - */ - public function setError($error) - { - $this->error = (int)$error; + /** + * Set error + * @param int $error + * @return static $this + */ + public function setError($error) + { + $this->error = (int)$error; - return $this; - } + return $this; + } - public function getValue() - { - return $this->getTmpName(); - } + public function getValue() + { + return $this->getTmpName(); + } - public function hasError() - { - return ($this->getError() !== 0); - } + public function hasError() + { + return ($this->getError() !== 0); + } - /** - * Create from array - * @param array $values - * @return static - */ - public static function createFromArray(array $values) - { - if (!isset($values['index'])) { - throw new \InvalidArgumentException('Index key is required'); - } + /** + * Create from array + * @param array $values + * @return static + */ + public static function createFromArray(array $values) + { + if (!isset($values['index'])) { + throw new \InvalidArgumentException('Index key is required'); + } - $input = new static($values['index']); - $input->setError(isset($values['error']) ? $values['error'] : null); - $input->setName(isset($values['name']) ? $values['name'] : null); - $input->setSize(isset($values['size']) ? $values['size'] : null); - $input->setType(isset($values['type']) ? $values['type'] : null); - $input->setTmpName(isset($values['tmp_name']) ? $values['tmp_name'] : null); + $input = new static($values['index']); + $input->setError(isset($values['error']) ? $values['error'] : null); + $input->setName(isset($values['name']) ? $values['name'] : null); + $input->setSize(isset($values['size']) ? $values['size'] : null); + $input->setType(isset($values['type']) ? $values['type'] : null); + $input->setTmpName(isset($values['tmp_name']) ? $values['tmp_name'] : null); - return $input; - } + return $input; + } - public function toArray() - { - return [ - 'tmp_name' => $this->tmpName, - 'type' => $this->type, - 'size' => $this->size, - 'name' => $this->name, - 'error' => $this->error, - ]; - } + public function toArray() + { + return [ + 'tmp_name' => $this->tmpName, + 'type' => $this->type, + 'size' => $this->size, + 'name' => $this->name, + 'error' => $this->error, + ]; + } - public function __toString() - { - return $this->getValue(); - } + public function __toString() + { + return $this->getValue(); + } } \ No newline at end of file diff --git a/src/Pecee/Http/Input/InputItem.php b/src/Pecee/Http/Input/InputItem.php index 934477b..32719a9 100644 --- a/src/Pecee/Http/Input/InputItem.php +++ b/src/Pecee/Http/Input/InputItem.php @@ -3,68 +3,70 @@ namespace Pecee\Http\Input; class InputItem implements IInputItem { - public $index; - public $name; - public $value; + public $index; + public $name; + public $value; - public function __construct($index, $value = null) - { - $this->index = $index; - $this->value = $value; + public function __construct($index, $value = null) + { + $this->index = $index; + $this->value = $value; - // Make the name human friendly, by replace _ with space - $this->name = ucfirst(str_replace('_', ' ', $this->index)); - } + // Make the name human friendly, by replace _ with space + $this->name = ucfirst(str_replace('_', ' ', $this->index)); + } - /** - * @return string - */ - public function getIndex() - { - return $this->index; - } + /** + * @return string + */ + public function getIndex() + { + return $this->index; + } - /** - * @return string - */ - public function getName() - { - return $this->name; - } + /** + * @return string + */ + public function getName() + { + return $this->name; + } - /** - * @return string - */ - public function getValue() - { - return $this->value; - } + /** + * @return string + */ + public function getValue() + { + return $this->value; + } - /** - * Set input name - * @param string $name - * @return static $this - */ - public function setName($name) - { - $this->name = $name; - return $this; - } + /** + * Set input name + * @param string $name + * @return static $this + */ + public function setName($name) + { + $this->name = $name; - /** - * Set input value - * @param string $value - * @return static $this - */ - public function setValue($value) - { - $this->value = $value; - return $this; - } + return $this; + } - public function __toString() - { - return (string)$this->value; - } + /** + * Set input value + * @param string $value + * @return static $this + */ + public function setValue($value) + { + $this->value = $value; + + return $this; + } + + public function __toString() + { + return (string)$this->value; + } } \ No newline at end of file diff --git a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php index ba10ff8..d6ea61d 100644 --- a/src/Pecee/Http/Middleware/BaseCsrfVerifier.php +++ b/src/Pecee/Http/Middleware/BaseCsrfVerifier.php @@ -8,92 +8,93 @@ use Pecee\SimpleRouter\Route\ILoadableRoute; class BaseCsrfVerifier implements IMiddleware { - const POST_KEY = 'csrf-token'; - const HEADER_KEY = 'X-CSRF-TOKEN'; + const POST_KEY = 'csrf-token'; + const HEADER_KEY = 'X-CSRF-TOKEN'; - protected $except; - protected $csrfToken; - protected $token; + protected $except; + protected $csrfToken; + protected $token; - public function __construct() - { - $this->csrfToken = new CsrfToken(); + public function __construct() + { + $this->csrfToken = new CsrfToken(); - // Generate or get the CSRF-Token from Cookie. - $this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken(); - } + // Generate or get the CSRF-Token from Cookie. + $this->token = ($this->hasToken() === false) ? $this->generateToken() : $this->csrfToken->getToken(); + } - /** - * Check if the url matches the urls in the except property - * @param Request $request - * @return bool - */ - protected function skip(Request $request) - { - if ($this->except === null || is_array($this->except) === false) { - return false; - } + /** + * Check if the url matches the urls in the except property + * @param Request $request + * @return bool + */ + protected function skip(Request $request) + { + if ($this->except === null || is_array($this->except) === false) { + return false; + } - $max = count($this->except) - 1; + $max = count($this->except) - 1; - for ($i = $max; $i >= 0; $i--) { - $url = $this->except[$i]; + for ($i = $max; $i >= 0; $i--) { + $url = $this->except[$i]; - $url = rtrim($url, '/'); - if ($url[strlen($url) - 1] === '*') { - $url = rtrim($url, '*'); - $skip = (stripos($request->getUri(), $url) === 0); - } else { - $skip = ($url === rtrim($request->getUri(), '/')); - } + $url = rtrim($url, '/'); + if ($url[strlen($url) - 1] === '*') { + $url = rtrim($url, '*'); + $skip = (stripos($request->getUri(), $url) === 0); + } else { + $skip = ($url === rtrim($request->getUri(), '/')); + } - if ($skip === true) { - return true; - } - } + if ($skip === true) { + return true; + } + } - return false; - } + return false; + } - public function handle(Request $request, ILoadableRoute &$route = null) - { + public function handle(Request $request, ILoadableRoute &$route = null) + { - if (in_array($request->getMethod(), ['post', 'put', 'delete']) === true && $this->skip($request) === false) { + if (in_array($request->getMethod(), ['post', 'put', 'delete']) === true && $this->skip($request) === false) { - $token = $request->getInput()->get(static::POST_KEY, null, 'post'); + $token = $request->getInput()->get(static::POST_KEY, null, 'post'); - // If the token is not posted, check headers for valid x-csrf-token - if ($token === null) { - $token = $request->getHeader(static::HEADER_KEY); - } + // If the token is not posted, check headers for valid x-csrf-token + if ($token === null) { + $token = $request->getHeader(static::HEADER_KEY); + } - if ($this->csrfToken->validate($token) === false) { - throw new TokenMismatchException('Invalid csrf-token.'); - } + if ($this->csrfToken->validate($token) === false) { + throw new TokenMismatchException('Invalid csrf-token.'); + } - } + } - } + } - public function generateToken() - { - $token = $this->csrfToken->generateToken(); - $this->csrfToken->setToken($token); - return $token; - } + public function generateToken() + { + $token = $this->csrfToken->generateToken(); + $this->csrfToken->setToken($token); - public function hasToken() - { - if ($this->token != null) { - return true; - } + return $token; + } - return $this->csrfToken->hasToken(); - } + public function hasToken() + { + if ($this->token != null) { + return true; + } - public function getToken() - { - return $this->token; - } + return $this->csrfToken->hasToken(); + } + + public function getToken() + { + return $this->token; + } } \ No newline at end of file diff --git a/src/Pecee/Http/Middleware/IMiddleware.php b/src/Pecee/Http/Middleware/IMiddleware.php index bbd5103..aaee9cf 100644 --- a/src/Pecee/Http/Middleware/IMiddleware.php +++ b/src/Pecee/Http/Middleware/IMiddleware.php @@ -6,11 +6,11 @@ use Pecee\SimpleRouter\Route\ILoadableRoute; interface IMiddleware { - /** - * @param Request $request - * @param ILoadableRoute $route - * @return Request|null - */ - public function handle(Request $request, ILoadableRoute &$route); + /** + * @param Request $request + * @param ILoadableRoute $route + * @return Request|null + */ + public function handle(Request $request, ILoadableRoute &$route); } \ No newline at end of file diff --git a/src/Pecee/Http/Request.php b/src/Pecee/Http/Request.php index 839ec96..8ce9075 100644 --- a/src/Pecee/Http/Request.php +++ b/src/Pecee/Http/Request.php @@ -5,226 +5,226 @@ use Pecee\Http\Input\Input; class Request { - protected $data = []; - protected $headers; - protected $host; - protected $uri; - protected $method; - protected $input; + protected $data = []; + protected $headers; + protected $host; + protected $uri; + protected $method; + protected $input; - public function __construct() - { - $this->parseHeaders(); - $this->host = $this->getHeader('http-host');; - $this->uri = $this->getHeader('request-uri'); - $this->input = new Input($this); - $this->method = $this->input->get('_method', strtolower($this->getHeader('request-method'))); - } + public function __construct() + { + $this->parseHeaders(); + $this->host = $this->getHeader('http-host');; + $this->uri = $this->getHeader('request-uri'); + $this->input = new Input($this); + $this->method = strtolower($this->input->get('_method', $this->getHeader('request-method'))); + } - protected function parseHeaders() - { - $this->headers = []; + protected function parseHeaders() + { + $this->headers = []; - $max = count($_SERVER) - 1; - $keys = array_keys($_SERVER); + $max = count($_SERVER) - 1; + $keys = array_keys($_SERVER); - for($i = $max; $i >= 0; $i--) { - $key = $keys[$i]; - $value = $_SERVER[$key]; + for ($i = $max; $i >= 0; $i--) { + $key = $keys[$i]; + $value = $_SERVER[$key]; - $this->headers[strtolower($key)] = $value; - $this->headers[strtolower(str_replace('_', '-', $key))] = $value; - } + $this->headers[strtolower($key)] = $value; + $this->headers[strtolower(str_replace('_', '-', $key))] = $value; + } - } + } - public function isSecure() - { - if ($this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443) { - return true; - } + public function isSecure() + { + if ($this->getHeader('http-x-forwarded-proto') === 'https' || $this->getHeader('https') !== null || $this->getHeader('server-port') === 443) { + return true; + } - return false; - } + return false; + } - /** - * @return string - */ - public function getUri() - { - return $this->uri; - } + /** + * @return string + */ + public function getUri() + { + return $this->uri; + } - /** - * @return string - */ - public function getHost() - { - return $this->host; - } + /** + * @return string + */ + public function getHost() + { + return $this->host; + } - /** - * @return string - */ - public function getMethod() - { - return $this->method; - } + /** + * @return string + */ + public function getMethod() + { + return $this->method; + } - /** - * Get http basic auth user - * @return string|null - */ - public function getUser() - { - return $this->getHeader('php-auth-user'); - } + /** + * Get http basic auth user + * @return string|null + */ + public function getUser() + { + return $this->getHeader('php-auth-user'); + } - /** - * Get http basic auth password - * @return string|null - */ - public function getPassword() - { - return $this->getHeader('php-auth-pw'); - } + /** + * Get http basic auth password + * @return string|null + */ + public function getPassword() + { + return $this->getHeader('php-auth-pw'); + } - /** - * Get all headers - * @return array - */ - public function getHeaders() - { - return $this->headers; - } + /** + * Get all headers + * @return array + */ + public function getHeaders() + { + return $this->headers; + } - /** - * Get id address - * @return string - */ - public function getIp() - { - if ($this->getHeader('http-cf-connecting-ip') !== null) { - return $this->getHeader('http-cf-connecting-ip'); - } + /** + * Get id address + * @return string + */ + public function getIp() + { + if ($this->getHeader('http-cf-connecting-ip') !== null) { + return $this->getHeader('http-cf-connecting-ip'); + } - if ($this->getHeader('http-x-forwarded-for') !== null && strlen($this->getHeader('http-x-forwarded-for'))) { - return $this->getHeader('http-x-forwarded_for'); - } + if ($this->getHeader('http-x-forwarded-for') !== null && strlen($this->getHeader('http-x-forwarded-for'))) { + return $this->getHeader('http-x-forwarded_for'); + } - return $this->getHeader('remote-addr'); - } + return $this->getHeader('remote-addr'); + } - /** - * Get referer - * @return string - */ - public function getReferer() - { - return $this->getHeader('http-referer'); - } + /** + * Get referer + * @return string + */ + public function getReferer() + { + return $this->getHeader('http-referer'); + } - /** - * Get user agent - * @return string - */ - public function getUserAgent() - { - return $this->getHeader('http-user-agent'); - } + /** + * Get user agent + * @return string + */ + public function getUserAgent() + { + return $this->getHeader('http-user-agent'); + } - /** - * Get header value by name - * - * @param string $name - * @param object|null $defaultValue - * - * @return string|null - */ - public function getHeader($name, $defaultValue = null) - { - if (isset($this->headers[strtolower($name)])) { - return $this->headers[strtolower($name)]; - } + /** + * Get header value by name + * + * @param string $name + * @param object|null $defaultValue + * + * @return string|null + */ + public function getHeader($name, $defaultValue = null) + { + if (isset($this->headers[strtolower($name)])) { + return $this->headers[strtolower($name)]; + } - $max = count($_SERVER) - 1; - $keys = array_keys($_SERVER); + $max = count($_SERVER) - 1; + $keys = array_keys($_SERVER); - for ($i = $max; $i >= 0; $i--) { + for ($i = $max; $i >= 0; $i--) { - $key = $keys[$i]; - $name = $_SERVER[$key]; + $key = $keys[$i]; + $name = $_SERVER[$key]; - if ($key === $name) { - return $name; - } - } + if ($key === $name) { + return $name; + } + } - return $defaultValue; - } + return $defaultValue; + } - /** - * Get input class - * @return Input - */ - public function getInput() - { - return $this->input; - } + /** + * Get input class + * @return Input + */ + public function getInput() + { + return $this->input; + } - /** - * Is format accepted - * - * @param string $format - * - * @return bool - */ - public function isFormatAccepted($format) - { - return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1); - } + /** + * Is format accepted + * + * @param string $format + * + * @return bool + */ + public function isFormatAccepted($format) + { + return ($this->getHeader('http-accept') !== null && stripos($this->getHeader('http-accept'), $format) > -1); + } - /** - * Get accept formats - * @return array - */ - public function getAcceptFormats() - { - return explode(',', $this->getHeader('http-accept')); - } + /** + * Get accept formats + * @return array + */ + public function getAcceptFormats() + { + return explode(',', $this->getHeader('http-accept')); + } - /** - * @param string $uri - */ - public function setUri($uri) - { - $this->uri = $uri; - } + /** + * @param string $uri + */ + public function setUri($uri) + { + $this->uri = $uri; + } - /** - * @param string $host - */ - public function setHost($host) - { - $this->host = $host; - } + /** + * @param string $host + */ + public function setHost($host) + { + $this->host = $host; + } - /** - * @param string $method - */ - public function setMethod($method) - { - $this->method = $method; - } + /** + * @param string $method + */ + public function setMethod($method) + { + $this->method = $method; + } - public function __set($name, $value = null) - { - $this->data[$name] = $value; - } + public function __set($name, $value = null) + { + $this->data[$name] = $value; + } - public function __get($name) - { - return isset($this->data[$name]) ? $this->data[$name] : null; - } + public function __get($name) + { + return isset($this->data[$name]) ? $this->data[$name] : null; + } } \ No newline at end of file diff --git a/src/Pecee/Http/Response.php b/src/Pecee/Http/Response.php index 3fe16bb..a1bba1f 100644 --- a/src/Pecee/Http/Response.php +++ b/src/Pecee/Http/Response.php @@ -3,116 +3,120 @@ namespace Pecee\Http; class Response { - protected $request; + protected $request; - public function __construct(Request $request) - { - $this->request = $request; - } + public function __construct(Request $request) + { + $this->request = $request; + } - /** - * Set the http status code - * - * @param int $code - * @return static - */ - public function httpCode($code) - { - http_response_code($code); - return $this; - } + /** + * Set the http status code + * + * @param int $code + * @return static + */ + public function httpCode($code) + { + http_response_code($code); - /** - * Redirect the response - * - * @param string $url - * @param int $httpCode - */ - public function redirect($url, $httpCode = null) - { - if ($httpCode !== null) { - $this->httpCode($httpCode); - } + return $this; + } - $this->header('location: ' . $url); - die(); - } + /** + * Redirect the response + * + * @param string $url + * @param int $httpCode + */ + public function redirect($url, $httpCode = null) + { + if ($httpCode !== null) { + $this->httpCode($httpCode); + } - public function refresh() - { - $this->redirect($this->request->getUri()); - } + $this->header('location: ' . $url); + die(); + } - /** - * Add http authorisation - * @param string $name - * @return static - */ - public function auth($name = '') - { - $this->headers([ - 'WWW-Authenticate: Basic realm="' . $name . '"', - 'HTTP/1.0 401 Unauthorized' - ]); - return $this; - } + public function refresh() + { + $this->redirect($this->request->getUri()); + } - public function cache($eTag, $lastModified = 2592000) - { + /** + * Add http authorisation + * @param string $name + * @return static + */ + public function auth($name = '') + { + $this->headers([ + 'WWW-Authenticate: Basic realm="' . $name . '"', + 'HTTP/1.0 401 Unauthorized', + ]); - $this->headers([ - 'Cache-Control: public', - 'Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT', - 'Etag: ' . $eTag - ]); + return $this; + } - $httpModified = $this->request->getHeader('http-if-modified-since'); - $httpIfNoneMatch = $this->request->getHeader('http-if-none-match'); + public function cache($eTag, $lastModified = 2592000) + { - if ($httpModified !== null && strtotime($httpModified) == $lastModified || $httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) { + $this->headers([ + 'Cache-Control: public', + 'Last-Modified: ' . gmdate("D, d M Y H:i:s", $lastModified) . ' GMT', + 'Etag: ' . $eTag, + ]); - $this->header('HTTP/1.1 304 Not Modified'); + $httpModified = $this->request->getHeader('http-if-modified-since'); + $httpIfNoneMatch = $this->request->getHeader('http-if-none-match'); - exit(); - } + if ($httpModified !== null && strtotime($httpModified) == $lastModified || $httpIfNoneMatch !== null && $httpIfNoneMatch === $eTag) { - return $this; - } + $this->header('HTTP/1.1 304 Not Modified'); - /** - * Json encode array - * @param array $value - */ - public function json(array $value) - { - $this->header('Content-Type: application/json'); - echo json_encode($value); - die(); - } + exit(); + } - /** - * Add header to response - * @param string $value - * @return static - */ - public function header($value) - { - header($value); - return $this; - } + return $this; + } - /** - * Add multiple headers to response - * @param array $headers - * @return static - */ - public function headers(array $headers) - { - $max = count($headers); - for($i = 0; $i < $max; $i++) { - $this->header($headers[$i]); - } - return $this; - } + /** + * Json encode array + * @param array $value + */ + public function json(array $value) + { + $this->header('Content-Type: application/json'); + echo json_encode($value); + die(); + } + + /** + * Add header to response + * @param string $value + * @return static + */ + public function header($value) + { + header($value); + + return $this; + } + + /** + * Add multiple headers to response + * @param array $headers + * @return static + */ + public function headers(array $headers) + { + $max = count($headers); + for ($i = 0; $i < $max; $i++) { + $this->header($headers[$i]); + } + + return $this; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/IRouterBootManager.php b/src/Pecee/SimpleRouter/IRouterBootManager.php index 6fa7efc..08090ed 100644 --- a/src/Pecee/SimpleRouter/IRouterBootManager.php +++ b/src/Pecee/SimpleRouter/IRouterBootManager.php @@ -5,11 +5,11 @@ use Pecee\Http\Request; interface IRouterBootManager { - /** - * Called when router loads it's routes - * - * @param Request $request - * @return Request - */ - public function boot(Request $request); + /** + * Called when router loads it's routes + * + * @param Request $request + * @return Request + */ + public function boot(Request $request); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/IControllerRoute.php b/src/Pecee/SimpleRouter/Route/IControllerRoute.php index 3df2b65..9b1e79b 100644 --- a/src/Pecee/SimpleRouter/Route/IControllerRoute.php +++ b/src/Pecee/SimpleRouter/Route/IControllerRoute.php @@ -3,34 +3,34 @@ namespace Pecee\SimpleRouter\Route; interface IControllerRoute extends IRoute { - /** - * Get controller class-name - * - * @return string - */ - public function getController(); + /** + * Get controller class-name + * + * @return string + */ + public function getController(); - /** - * Set controller class-name - * - * @param string $controller - * @return static - */ - public function setController($controller); + /** + * Set controller class-name + * + * @param string $controller + * @return static + */ + public function setController($controller); - /** - * Return active method - * - * @return string - */ - public function getMethod(); + /** + * Return active method + * + * @return string + */ + public function getMethod(); - /** - * Set active method - * - * @param string $method - * @return static - */ - public function setMethod($method); + /** + * Set active method + * + * @param string $method + * @return static + */ + public function setMethod($method); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/IGroupRoute.php b/src/Pecee/SimpleRouter/Route/IGroupRoute.php index f596bed..6892379 100644 --- a/src/Pecee/SimpleRouter/Route/IGroupRoute.php +++ b/src/Pecee/SimpleRouter/Route/IGroupRoute.php @@ -5,56 +5,56 @@ use Pecee\Http\Request; interface IGroupRoute extends IRoute { - /** - * Method called to check if a domain matches - * - * @param Request $request - * @return bool - */ - public function matchDomain(Request $request); + /** + * Method called to check if a domain matches + * + * @param Request $request + * @return bool + */ + public function matchDomain(Request $request); - /** - * Set exception-handlers for group - * - * @param array $handlers - * @return static $this - */ - public function setExceptionHandlers(array $handlers); + /** + * Set exception-handlers for group + * + * @param array $handlers + * @return static $this + */ + public function setExceptionHandlers(array $handlers); - /** - * Get exception-handlers for group - * - * @return array - */ - public function getExceptionHandlers(); + /** + * Get exception-handlers for group + * + * @return array + */ + public function getExceptionHandlers(); - /** - * Get domains for domain. - * - * @return array - */ - public function getDomains(); + /** + * Get domains for domain. + * + * @return array + */ + public function getDomains(); - /** - * Set allowed domains for group. - * - * @param array $domains - * @return $this - */ - public function setDomains(array $domains); + /** + * Set allowed domains for group. + * + * @param array $domains + * @return $this + */ + public function setDomains(array $domains); - /** - * Set prefix that child-routes will inherit. - * - * @param string $prefix - * @return string - */ - public function setPrefix($prefix); + /** + * Set prefix that child-routes will inherit. + * + * @param string $prefix + * @return string + */ + public function setPrefix($prefix); - /** - * Get prefix. - * - * @return string - */ - public function getPrefix(); + /** + * Get prefix. + * + * @return string + */ + public function getPrefix(); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/ILoadableRoute.php b/src/Pecee/SimpleRouter/Route/ILoadableRoute.php index 638438c..bebe009 100644 --- a/src/Pecee/SimpleRouter/Route/ILoadableRoute.php +++ b/src/Pecee/SimpleRouter/Route/ILoadableRoute.php @@ -5,50 +5,50 @@ use Pecee\Http\Request; interface ILoadableRoute extends IRoute { - /** - * Find url that matches method, parameters or name. - * Used when calling the url() helper. - * - * @param string|null $method - * @param array|null $parameters - * @param string|null $name - * @return string - */ - public function findUrl($method = null, $parameters = null, $name = null); + /** + * Find url that matches method, parameters or name. + * Used when calling the url() helper. + * + * @param string|null $method + * @param array|null $parameters + * @param string|null $name + * @return string + */ + public function findUrl($method = null, $parameters = null, $name = null); - /** - * Loads and renders middlewares-classes - * - * @param Request $request - * @param ILoadableRoute $route - */ - public function loadMiddleware(Request $request, ILoadableRoute &$route); + /** + * Loads and renders middlewares-classes + * + * @param Request $request + * @param ILoadableRoute $route + */ + public function loadMiddleware(Request $request, ILoadableRoute &$route); - public function getUrl(); + public function getUrl(); - public function setUrl($url); + public function setUrl($url); - /** - * Returns the provided name for the router. - * - * @return string - */ - public function getName(); + /** + * Returns the provided name for the router. + * + * @return string + */ + public function getName(); - /** - * Check if route has given name. - * - * @param string $name - * @return bool - */ - public function hasName($name); + /** + * Check if route has given name. + * + * @param string $name + * @return bool + */ + public function hasName($name); - /** - * Sets the router name, which makes it easier to obtain the url or router at a later point. - * - * @param string $name - * @return static $this - */ - public function setName($name); + /** + * Sets the router name, which makes it easier to obtain the url or router at a later point. + * + * @param string $name + * @return static $this + */ + public function setName($name); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/IRoute.php b/src/Pecee/SimpleRouter/Route/IRoute.php index 86b2dc5..63c5cf1 100644 --- a/src/Pecee/SimpleRouter/Route/IRoute.php +++ b/src/Pecee/SimpleRouter/Route/IRoute.php @@ -5,195 +5,195 @@ use Pecee\Http\Request; interface IRoute { - /** - * Method called to check if a domain matches - * - * @param Request $request - * @return bool - */ - public function matchRoute(Request $request); + /** + * Method called to check if a domain matches + * + * @param Request $request + * @return bool + */ + public function matchRoute(Request $request); - /** - * Called when route is matched. - * Returns class to be rendered. - * - * @param Request $request - * @return object - */ - public function renderRoute(Request $request); + /** + * Called when route is matched. + * Returns class to be rendered. + * + * @param Request $request + * @return object + */ + public function renderRoute(Request $request); - /** - * 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 - * when using translations etc. - * - * @return string - */ - public function getIdentifier(); + /** + * 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 + * when using translations etc. + * + * @return string + */ + public function getIdentifier(); - /** - * Set allowed request methods - * - * @param array $methods - * @return static $this - */ - public function setRequestMethods(array $methods); + /** + * Set allowed request methods + * + * @param array $methods + * @return static $this + */ + public function setRequestMethods(array $methods); - /** - * Get allowed request methods - * - * @return array - */ - public function getRequestMethods(); + /** + * Get allowed request methods + * + * @return array + */ + public function getRequestMethods(); - /** - * @return IRoute|null - */ - public function getParent(); + /** + * @return IRoute|null + */ + public function getParent(); - /** - * Get the group for the route. - * - * @return IGroupRoute|null - */ - public function getGroup(); + /** + * Get the group for the route. + * + * @return IGroupRoute|null + */ + public function getGroup(); - /** - * Set group - * - * @param IGroupRoute $group - * @return static $this - */ - public function setGroup(IGroupRoute $group); + /** + * Set group + * + * @param IGroupRoute $group + * @return static $this + */ + public function setGroup(IGroupRoute $group); - /** - * Set parent route - * - * @param IRoute $parent - * @return static $this - */ - public function setParent(IRoute $parent); + /** + * Set parent route + * + * @param IRoute $parent + * @return static $this + */ + public function setParent(IRoute $parent); - /** - * Set callback - * - * @param string $callback - * @return static - */ - public function setCallback($callback); + /** + * Set callback + * + * @param string $callback + * @return static + */ + public function setCallback($callback); - /** - * @return string - */ - public function getCallback(); + /** + * @return string + */ + public function getCallback(); - public function getMethod(); + public function getMethod(); - public function getClass(); + public function getClass(); - public function setMethod($method); + public function setMethod($method); - /** - * @param string $namespace - * @return static $this - */ - public function setNamespace($namespace); + /** + * @param string $namespace + * @return static $this + */ + public function setNamespace($namespace); - /** - * @return string - */ - public function getNamespace(); + /** + * @return string + */ + public function getNamespace(); - /** - * @param string $namespace - * @return static $this - */ - public function setDefaultNamespace($namespace); + /** + * @param string $namespace + * @return static $this + */ + public function setDefaultNamespace($namespace); - public function getDefaultNamespace(); + public function getDefaultNamespace(); - /** - * Get regular expression match used for matching route (if defined). - * - * @return string - */ - public function getMatch(); + /** + * Get regular expression match used for matching route (if defined). + * + * @return string + */ + public function getMatch(); - /** - * Add regular expression match for the entire route. - * - * @param string $regex - * @return static - */ - public function setMatch($regex); + /** + * Add regular expression match for the entire route. + * + * @param string $regex + * @return static + */ + public function setMatch($regex); - /** - * Get parameter names. - * - * @return array - */ - public function getWhere(); + /** + * Get parameter names. + * + * @return array + */ + public function getWhere(); - /** - * Set parameter names. - * - * @param array $options - * @return static - */ - public function setWhere(array $options); + /** + * Set parameter names. + * + * @param array $options + * @return static + */ + public function setWhere(array $options); - /** - * Get parameters - * - * @return array - */ - public function getParameters(); + /** + * Get parameters + * + * @return array + */ + public function getParameters(); - /** - * Get parameters - * - * @param array $parameters - * @return static $this - */ - public function setParameters(array $parameters); + /** + * Get parameters + * + * @param array $parameters + * @return static $this + */ + public function setParameters(array $parameters); - /** - * Merge with information from another route. - * - * @param array $settings - * @param bool $merge - * @return static $this - */ - public function setSettings(array $settings, $merge = false); + /** + * Merge with information from another route. + * + * @param array $settings + * @param bool $merge + * @return static $this + */ + public function setSettings(array $settings, $merge = false); - /** - * Export route settings to array so they can be merged with another route. - * - * @return array - */ - public function toArray(); + /** + * Export route settings to array so they can be merged with another route. + * + * @return array + */ + public function toArray(); - /** - * Get middlewares array - * - * @return array - */ - public function getMiddlewares(); + /** + * Get middlewares array + * + * @return array + */ + public function getMiddlewares(); - /** - * Set middleware class-name - * - * @param string $middleware - * @return static - */ - public function setMiddleware($middleware); + /** + * Set middleware class-name + * + * @param string $middleware + * @return static + */ + public function setMiddleware($middleware); - /** - * Set middlewares array - * - * @param array $middlewares - * @return $this - */ - public function setMiddlewares(array $middlewares); + /** + * Set middlewares array + * + * @param array $middlewares + * @return $this + */ + public function setMiddlewares(array $middlewares); } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/LoadableRoute.php b/src/Pecee/SimpleRouter/Route/LoadableRoute.php index b9dae4a..d4d93ff 100644 --- a/src/Pecee/SimpleRouter/Route/LoadableRoute.php +++ b/src/Pecee/SimpleRouter/Route/LoadableRoute.php @@ -7,198 +7,198 @@ use Pecee\SimpleRouter\Exceptions\HttpException; abstract class LoadableRoute extends Route implements ILoadableRoute { - const PARAMETERS_REGEX_MATCH = '%s([\w\-\_]*?)\%s{0,1}%s'; + const PARAMETERS_REGEX_MATCH = '%s([\w\-\_]*?)\%s{0,1}%s'; - protected $url; - protected $name; + protected $url; + protected $name; - /** - * Loads and renders middlewares-classes - * - * @param Request $request - * @param ILoadableRoute $route - * @throws HttpException - */ - public function loadMiddleware(Request $request, ILoadableRoute &$route) - { - if (count($this->getMiddlewares()) > 0) { + /** + * Loads and renders middlewares-classes + * + * @param Request $request + * @param ILoadableRoute $route + * @throws HttpException + */ + public function loadMiddleware(Request $request, ILoadableRoute &$route) + { + if (count($this->getMiddlewares()) > 0) { - $max = count($this->getMiddlewares()); + $max = count($this->getMiddlewares()); - for ($i = 0; $i < $max; $i++) { + for ($i = 0; $i < $max; $i++) { - $middleware = $this->getMiddlewares()[$i]; + $middleware = $this->getMiddlewares()[$i]; - $middleware = $this->loadClass($middleware); - if (!($middleware instanceof IMiddleware)) { - throw new HttpException($middleware . ' must be instance of Middleware'); - } + $middleware = $this->loadClass($middleware); + if (!($middleware instanceof IMiddleware)) { + throw new HttpException($middleware . ' must be instance of Middleware'); + } - $middleware->handle($request, $route); - } - } - } + $middleware->handle($request, $route); + } + } + } - /** - * Set url - * - * @param string $url - * @return static - */ - public function setUrl($url) - { - $this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/'; + /** + * Set url + * + * @param string $url + * @return static + */ + public function setUrl($url) + { + $this->url = ($url === '/') ? '/' : '/' . trim($url, '/') . '/'; - if(strpos($this->url, $this->paramModifiers[0]) !== false) { + if (strpos($this->url, $this->paramModifiers[0]) !== false) { - $regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]); + $regex = sprintf(static::PARAMETERS_REGEX_MATCH, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]); - if (preg_match_all('/' . $regex . '/is', $this->url, $matches)) { + if (preg_match_all('/' . $regex . '/is', $this->url, $matches)) { - $max = count($matches[1]); + $max = count($matches[1]); - for ($i = 0; $i < $max; $i++) { - $this->parameters[$matches[1][$i]] = null; - } + for ($i = 0; $i < $max; $i++) { + $this->parameters[$matches[1][$i]] = null; + } - } + } - } + } - return $this; - } + return $this; + } - public function getUrl() - { - return $this->url; - } + public function getUrl() + { + return $this->url; + } - /** - * Find url that matches method, parameters or name. - * Used when calling the url() helper. - * - * @param string|null $method - * @param array|null $parameters - * @param string|null $name - * @return string - */ - public function findUrl($method = null, $parameters = null, $name = null) - { - $url = ''; + /** + * Find url that matches method, parameters or name. + * Used when calling the url() helper. + * + * @param string|null $method + * @param array|null $parameters + * @param string|null $name + * @return string + */ + public function findUrl($method = null, $parameters = null, $name = null) + { + $url = ''; - $parameters = (array)$parameters; + $parameters = (array)$parameters; - if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) { - $url .= '//' . $this->getGroup()->getDomains()[0]; - } + if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) { + $url .= '//' . $this->getGroup()->getDomains()[0]; + } - $url .= $this->getUrl(); + $url .= $this->getUrl(); - $params = array_merge($this->getParameters(), $parameters); + $params = array_merge($this->getParameters(), $parameters); - /* Url that contains parameters that aren't recognized */ - $unknownParams = []; + /* Url that contains parameters that aren't recognized */ + $unknownParams = []; - /* Create the param string - {} */ - $param1 = $this->paramModifiers[0] . '%s' . $this->paramModifiers[1]; + /* Create the param string - {} */ + $param1 = $this->paramModifiers[0] . '%s' . $this->paramModifiers[1]; - /* Create the param string with the optional symbol - {?} */ - $param2 = $this->paramModifiers[0] . '%s' . $this->paramOptionalSymbol . $this->paramModifiers[1]; + /* Create the param string with the optional symbol - {?} */ + $param2 = $this->paramModifiers[0] . '%s' . $this->paramOptionalSymbol . $this->paramModifiers[1]; - /* Let's parse the values of any {} parameter in the url */ + /* Let's parse the values of any {} parameter in the url */ - $max = count($params) - 1; - $keys = array_keys($params); + $max = count($params) - 1; + $keys = array_keys($params); - for ($i = $max; $i >= 0; $i--) { - $param = $keys[$i]; - $value = $params[$param]; + for ($i = $max; $i >= 0; $i--) { + $param = $keys[$i]; + $value = $params[$param]; - $value = (isset($parameters[$param])) ? $parameters[$param] : $value; + $value = (isset($parameters[$param])) ? $parameters[$param] : $value; - if (stripos($url, $param1) !== false || stripos($url, $param) !== false) { - $url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], $value, $url); - } else { - $unknownParams[$param] = $value; - } - } + if (stripos($url, $param1) !== false || stripos($url, $param) !== false) { + $url = str_ireplace([sprintf($param1, $param), sprintf($param2, $param)], $value, $url); + } else { + $unknownParams[$param] = $value; + } + } - $url .= join('/', $unknownParams); + $url .= join('/', $unknownParams); - return rtrim($url, '/') . '/'; - } + return rtrim($url, '/') . '/'; + } - /** - * Returns the provided name for the router. - * - * @return string - */ - public function getName() - { - return $this->name; - } + /** + * Returns the provided name for the router. + * + * @return string + */ + public function getName() + { + return $this->name; + } - /** - * Check if route has given name. - * - * @param string $name - * @return bool - */ - public function hasName($name) - { - return (strtolower($this->name) === strtolower($name)); - } + /** + * Check if route has given name. + * + * @param string $name + * @return bool + */ + public function hasName($name) + { + return (strtolower($this->name) === strtolower($name)); + } - /** - * Sets the router name, which makes it easier to obtain the url or router at a later point. - * Alias for LoadableRoute::setName(). - * - * @see LoadableRoute::setName() - * @param string|array $name - * @return static - */ - public function name($name) - { - return $this->setName($name); - } + /** + * Sets the router name, which makes it easier to obtain the url or router at a later point. + * Alias for LoadableRoute::setName(). + * + * @see LoadableRoute::setName() + * @param string|array $name + * @return static + */ + public function name($name) + { + return $this->setName($name); + } - /** - * Sets the router name, which makes it easier to obtain the url or router at a later point. - * - * @param string $name - * @return static $this - */ - public function setName($name) - { - $this->name = $name; + /** + * Sets the router name, which makes it easier to obtain the url or router at a later point. + * + * @param string $name + * @return static $this + */ + public function setName($name) + { + $this->name = $name; - return $this; - } + return $this; + } - /** - * Merge with information from another route. - * - * @param array $values - * @param bool $merge - * @return static - */ - public function setSettings(array $values, $merge = false) - { - if (isset($values['as'])) { - if ($this->name !== null && $merge !== false) { - $this->setName($values['as'] . '.' . $this->name); - } else { - $this->setName($values['as']); - } - } + /** + * Merge with information from another route. + * + * @param array $values + * @param bool $merge + * @return static + */ + public function setSettings(array $values, $merge = false) + { + if (isset($values['as'])) { + if ($this->name !== null && $merge !== false) { + $this->setName($values['as'] . '.' . $this->name); + } else { + $this->setName($values['as']); + } + } - if (isset($values['prefix'])) { - $this->setUrl($values['prefix'] . $this->getUrl()); - } + if (isset($values['prefix'])) { + $this->setUrl($values['prefix'] . $this->getUrl()); + } - parent::setSettings($values, $merge); + parent::setSettings($values, $merge); - return $this; - } + return $this; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/Route.php b/src/Pecee/SimpleRouter/Route/Route.php index d953ba1..1878b88 100644 --- a/src/Pecee/SimpleRouter/Route/Route.php +++ b/src/Pecee/SimpleRouter/Route/Route.php @@ -7,517 +7,517 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; abstract class Route implements IRoute { - const REQUEST_TYPE_GET = 'get'; - const REQUEST_TYPE_POST = 'post'; - const REQUEST_TYPE_PUT = 'put'; - const REQUEST_TYPE_PATCH = 'patch'; - const REQUEST_TYPE_OPTIONS = 'options'; - const REQUEST_TYPE_DELETE = 'delete'; - - public static $requestTypes = [ - self::REQUEST_TYPE_GET, - self::REQUEST_TYPE_POST, - self::REQUEST_TYPE_PUT, - self::REQUEST_TYPE_PATCH, - self::REQUEST_TYPE_OPTIONS, - self::REQUEST_TYPE_DELETE, - ]; - - protected $paramModifiers = '{}'; - protected $paramOptionalSymbol = '?'; - protected $group; - protected $parent; - protected $callback; - protected $defaultNamespace; - - /* Default options */ - protected $namespace; - protected $regex; - protected $requestMethods = []; - protected $where = []; - protected $parameters = []; - protected $middlewares = []; - - public function renderRoute(Request $request) - { - if ($this->getCallback() !== null && is_callable($this->getCallback())) { - - /* When the callback is a function */ - call_user_func_array($this->getCallback(), $this->getParameters()); - - } else { - - /* When the callback is a method */ - $controller = explode('@', $this->getCallback()); - $className = $this->getNamespace() . '\\' . $controller[0]; - - $class = $this->loadClass($className); - $method = $controller[1]; - - if (!method_exists($class, $method)) { - throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); - } - - $parameters = array_filter($this->getParameters(), function ($var) { - return ($var !== null); - }); - - call_user_func_array([$class, $method], $parameters); - - return $class; - } - - return null; - } - - protected function parseParameters($route, $url, $parameterRegex = '[\w]+') - { - $parameterNames = []; - $regex = ''; - $lastCharacter = ''; - $isParameter = false; - $parameter = ''; - $routeLength = strlen($route) - 1; - - for ($i = $routeLength; $i >= 0; $i--) { - - $character = strrev($route)[$i]; - - if ($character === '{') { - /* Remove "/" and "\" from regex */ - if (substr($regex, strlen($regex) - 1) === '/') { - $regex = substr($regex, 0, strlen($regex) - 2); - } - - $isParameter = true; - } elseif ($isParameter && $character === '}') { - $required = true; - - /* Check for optional parameter and use custom parameter regex if it exists */ - if (is_array($this->where) === true && isset($this->where[$parameter])) { - $parameterRegex = $this->where[$parameter]; - } - - if ($lastCharacter === '?') { - $parameter = substr($parameter, 0, strlen($parameter) - 1); - $regex .= '(?:\/?(?P<' . $parameter . '>' . $parameterRegex . ')[^\/]?)?'; - $required = false; - } else { - $regex .= '\/?(?P<' . $parameter . '>' . $parameterRegex . ')[^\/]?'; - } - - $parameterNames[] = [ - 'name' => $parameter, - 'required' => $required, - ]; - - $parameter = ''; - $isParameter = false; - } elseif ($isParameter) { - $parameter .= $character; - } elseif ($character === '/') { - $regex .= '\\' . $character; - } else { - $regex .= str_replace('.', '\\.', $character); - } - - $lastCharacter = $character; - } - - $parameterValues = []; - - if (preg_match('/^' . $regex . '\/?$/is', $url, $parameterValues)) { - - $parameters = []; - - $max = count($parameterNames) - 1; - - for ($i = $max; $i >= 0; $i--) { - - $name = $parameterNames[$i]; - - $parameterValue = isset($parameterValues[$name['name']]) ? $parameterValues[$name['name']] : null; - - if ($name['required'] && $parameterValue === null) { - throw new HttpException('Missing required parameter ' . $name['name'], 404); - } - - if ($name['required'] === false && $parameterValue === null) { - continue; - } - - $parameters[$name['name']] = $parameterValue; - } - - return $parameters; - } - - return null; - } - - protected function loadClass($name) - { - if (!class_exists($name)) { - throw new NotFoundHttpException(sprintf('Class %s does not exist', $name), 404); - } - - return new $name(); - } - - /** - * 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 - * when using translations etc. - * - * @return string - */ - public function getIdentifier() - { - if (strpos($this->callback, '@') !== false) { - return $this->callback; - } - - return 'function_' . md5($this->callback); - } - - /** - * Set allowed request methods - * - * @param array $methods - * @return static $this - */ - public function setRequestMethods(array $methods) - { - $this->requestMethods = $methods; - - return $this; - } - - /** - * Get allowed request methods - * - * @return array - */ - public function getRequestMethods() - { - return $this->requestMethods; - } - - /** - * @return IRoute|null - */ - public function getParent() - { - return $this->parent; - } - - /** - * Get the group for the route. - * - * @return IGroupRoute|null - */ - public function getGroup() - { - return $this->group; - } - - /** - * Set group - * - * @param IGroupRoute $group - * @return static $this - */ - public function setGroup(IGroupRoute $group) - { - $this->group = $group; - - return $this; - } - - /** - * Set parent route - * - * @param IRoute $parent - * @return static $this - */ - public function setParent(IRoute $parent) - { - $this->parent = $parent; - - return $this; - } - - /** - * Set callback - * - * @param string $callback - * @return static - */ - public function setCallback($callback) - { - $this->callback = $callback; - - return $this; - } - - /** - * @return string - */ - public function getCallback() - { - 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; - } - - public function setMethod($method) - { - $this->callback = sprintf('%s@%s', $this->getClass(), $method); - - return $this; - } - - public function setClass($class) - { - $this->callback = sprintf('%s@%s', $class, $this->getMethod()); - - return $this; - } - - /** - * @param string $namespace - * @return static $this - */ - public function setNamespace($namespace) - { - $this->namespace = $namespace; - - return $this; - } - - /** - * @param string $namespace - * @return static $this - */ - public function setDefaultNamespace($namespace) - { - $this->defaultNamespace = $namespace; - - return $this; - } - - public function getDefaultNamespace() - { - return $this->defaultNamespace; - } - - /** - * @return string - */ - public function getNamespace() - { - return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace; - } - - /** - * Add regular expression match for the entire route. - * - * @param string $regex - * @return static - */ - public function setMatch($regex) - { - $this->regex = $regex; - - return $this; - } - - /** - * Get regular expression match used for matching route (if defined). - * - * @return string - */ - public function getMatch() - { - return $this->regex; - } - - /** - * Export route settings to array so they can be merged with another route. - * - * @return array - */ - public function toArray() - { - $values = []; - - if ($this->namespace !== null) { - $values['namespace'] = $this->namespace; - } - - if (count($this->requestMethods) > 0) { - $values['method'] = $this->requestMethods; - } - - if (count($this->where) > 0) { - $values['where'] = $this->where; - } - - if (count($this->parameters) > 0) { - $values['parameters'] = $this->parameters; - } - - if (count($this->middlewares) > 0) { - $values['middleware'] = $this->middlewares; - } - - return $values; - } - - /** - * Merge with information from another route. - * - * @param array $values - * @param bool $merge - * @return static $this - */ - public function setSettings(array $values, $merge = false) - { - if (isset($values['namespace']) && $this->namespace === null) { - $this->setNamespace($values['namespace']); - } - - if (isset($values['method'])) { - $this->setRequestMethods(array_merge($this->requestMethods, (array)$values['method'])); - } - - if (isset($values['where'])) { - $this->setWhere(array_merge($this->where, (array)$values['where'])); - } - - if (isset($values['parameters'])) { - $this->setParameters(array_merge($this->parameters, (array)$values['parameters'])); - } - - // Push middleware if multiple - if (isset($values['middleware'])) { - $this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares)); - } - - return $this; - } - - /** - * Get parameter names. - * - * @return array - */ - public function getWhere() - { - return $this->where; - } - - /** - * Set parameter names. - * - * @param array $options - * @return static - */ - public function setWhere(array $options) - { - $this->where = $options; - - return $this; - } - - /** - * Add regular expression parameter match. - * Alias for LoadableRoute::where() - * - * @see LoadableRoute::where() - * @param array $options - * @return static - */ - public function where(array $options) - { - return $this->where($options); - } - - /** - * Get parameters - * - * @return array - */ - public function getParameters() - { - return $this->parameters; - } - - /** - * Get parameters - * - * @param array $parameters - * @return static $this - */ - public function setParameters(array $parameters) - { - $this->parameters = $parameters; - - return $this; - } - - /** - * Set middleware class-name - * - * @param string $middleware - * @return static - */ - public function setMiddleware($middleware) - { - $this->middlewares[] = $middleware; - - return $this; - } - - /** - * Set middlewares array - * - * @param array $middlewares - * @return $this - */ - public function setMiddlewares(array $middlewares) - { - $this->middlewares = $middlewares; - - return $this; - } - - /** - * @return string|array - */ - public function getMiddlewares() - { - return $this->middlewares; - } + const REQUEST_TYPE_GET = 'get'; + const REQUEST_TYPE_POST = 'post'; + const REQUEST_TYPE_PUT = 'put'; + const REQUEST_TYPE_PATCH = 'patch'; + const REQUEST_TYPE_OPTIONS = 'options'; + const REQUEST_TYPE_DELETE = 'delete'; + + public static $requestTypes = [ + self::REQUEST_TYPE_GET, + self::REQUEST_TYPE_POST, + self::REQUEST_TYPE_PUT, + self::REQUEST_TYPE_PATCH, + self::REQUEST_TYPE_OPTIONS, + self::REQUEST_TYPE_DELETE, + ]; + + protected $paramModifiers = '{}'; + protected $paramOptionalSymbol = '?'; + protected $group; + protected $parent; + protected $callback; + protected $defaultNamespace; + + /* Default options */ + protected $namespace; + protected $regex; + protected $requestMethods = []; + protected $where = []; + protected $parameters = []; + protected $middlewares = []; + + public function renderRoute(Request $request) + { + if ($this->getCallback() !== null && is_callable($this->getCallback())) { + + /* When the callback is a function */ + call_user_func_array($this->getCallback(), $this->getParameters()); + + } else { + + /* When the callback is a method */ + $controller = explode('@', $this->getCallback()); + $className = $this->getNamespace() . '\\' . $controller[0]; + + $class = $this->loadClass($className); + $method = $controller[1]; + + if (!method_exists($class, $method)) { + throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); + } + + $parameters = array_filter($this->getParameters(), function ($var) { + return ($var !== null); + }); + + call_user_func_array([$class, $method], $parameters); + + return $class; + } + + return null; + } + + protected function parseParameters($route, $url, $parameterRegex = '[\w]+') + { + $parameterNames = []; + $regex = ''; + $lastCharacter = ''; + $isParameter = false; + $parameter = ''; + $routeLength = strlen($route) - 1; + + for ($i = $routeLength; $i >= 0; $i--) { + + $character = strrev($route)[$i]; + + if ($character === '{') { + /* Remove "/" and "\" from regex */ + if (substr($regex, strlen($regex) - 1) === '/') { + $regex = substr($regex, 0, strlen($regex) - 2); + } + + $isParameter = true; + } elseif ($isParameter && $character === '}') { + $required = true; + + /* Check for optional parameter and use custom parameter regex if it exists */ + if (is_array($this->where) === true && isset($this->where[$parameter])) { + $parameterRegex = $this->where[$parameter]; + } + + if ($lastCharacter === '?') { + $parameter = substr($parameter, 0, strlen($parameter) - 1); + $regex .= '(?:\/?(?P<' . $parameter . '>' . $parameterRegex . ')[^\/]?)?'; + $required = false; + } else { + $regex .= '\/?(?P<' . $parameter . '>' . $parameterRegex . ')[^\/]?'; + } + + $parameterNames[] = [ + 'name' => $parameter, + 'required' => $required, + ]; + + $parameter = ''; + $isParameter = false; + } elseif ($isParameter) { + $parameter .= $character; + } elseif ($character === '/') { + $regex .= '\\' . $character; + } else { + $regex .= str_replace('.', '\\.', $character); + } + + $lastCharacter = $character; + } + + $parameterValues = []; + + if (preg_match('/^' . $regex . '\/?$/is', $url, $parameterValues)) { + + $parameters = []; + + $max = count($parameterNames) - 1; + + for ($i = $max; $i >= 0; $i--) { + + $name = $parameterNames[$i]; + + $parameterValue = isset($parameterValues[$name['name']]) ? $parameterValues[$name['name']] : null; + + if ($name['required'] && $parameterValue === null) { + throw new HttpException('Missing required parameter ' . $name['name'], 404); + } + + if ($name['required'] === false && $parameterValue === null) { + continue; + } + + $parameters[$name['name']] = $parameterValue; + } + + return $parameters; + } + + return null; + } + + protected function loadClass($name) + { + if (!class_exists($name)) { + throw new NotFoundHttpException(sprintf('Class %s does not exist', $name), 404); + } + + return new $name(); + } + + /** + * 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 + * when using translations etc. + * + * @return string + */ + public function getIdentifier() + { + if (strpos($this->callback, '@') !== false) { + return $this->callback; + } + + return 'function_' . md5($this->callback); + } + + /** + * Set allowed request methods + * + * @param array $methods + * @return static $this + */ + public function setRequestMethods(array $methods) + { + $this->requestMethods = $methods; + + return $this; + } + + /** + * Get allowed request methods + * + * @return array + */ + public function getRequestMethods() + { + return $this->requestMethods; + } + + /** + * @return IRoute|null + */ + public function getParent() + { + return $this->parent; + } + + /** + * Get the group for the route. + * + * @return IGroupRoute|null + */ + public function getGroup() + { + return $this->group; + } + + /** + * Set group + * + * @param IGroupRoute $group + * @return static $this + */ + public function setGroup(IGroupRoute $group) + { + $this->group = $group; + + return $this; + } + + /** + * Set parent route + * + * @param IRoute $parent + * @return static $this + */ + public function setParent(IRoute $parent) + { + $this->parent = $parent; + + return $this; + } + + /** + * Set callback + * + * @param string $callback + * @return static + */ + public function setCallback($callback) + { + $this->callback = $callback; + + return $this; + } + + /** + * @return string + */ + public function getCallback() + { + 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; + } + + public function setMethod($method) + { + $this->callback = sprintf('%s@%s', $this->getClass(), $method); + + return $this; + } + + public function setClass($class) + { + $this->callback = sprintf('%s@%s', $class, $this->getMethod()); + + return $this; + } + + /** + * @param string $namespace + * @return static $this + */ + public function setNamespace($namespace) + { + $this->namespace = $namespace; + + return $this; + } + + /** + * @param string $namespace + * @return static $this + */ + public function setDefaultNamespace($namespace) + { + $this->defaultNamespace = $namespace; + + return $this; + } + + public function getDefaultNamespace() + { + return $this->defaultNamespace; + } + + /** + * @return string + */ + public function getNamespace() + { + return ($this->namespace === null) ? $this->defaultNamespace : $this->namespace; + } + + /** + * Add regular expression match for the entire route. + * + * @param string $regex + * @return static + */ + public function setMatch($regex) + { + $this->regex = $regex; + + return $this; + } + + /** + * Get regular expression match used for matching route (if defined). + * + * @return string + */ + public function getMatch() + { + return $this->regex; + } + + /** + * Export route settings to array so they can be merged with another route. + * + * @return array + */ + public function toArray() + { + $values = []; + + if ($this->namespace !== null) { + $values['namespace'] = $this->namespace; + } + + if (count($this->requestMethods) > 0) { + $values['method'] = $this->requestMethods; + } + + if (count($this->where) > 0) { + $values['where'] = $this->where; + } + + if (count($this->parameters) > 0) { + $values['parameters'] = $this->parameters; + } + + if (count($this->middlewares) > 0) { + $values['middleware'] = $this->middlewares; + } + + return $values; + } + + /** + * Merge with information from another route. + * + * @param array $values + * @param bool $merge + * @return static $this + */ + public function setSettings(array $values, $merge = false) + { + if (isset($values['namespace']) && $this->namespace === null) { + $this->setNamespace($values['namespace']); + } + + if (isset($values['method'])) { + $this->setRequestMethods(array_merge($this->requestMethods, (array)$values['method'])); + } + + if (isset($values['where'])) { + $this->setWhere(array_merge($this->where, (array)$values['where'])); + } + + if (isset($values['parameters'])) { + $this->setParameters(array_merge($this->parameters, (array)$values['parameters'])); + } + + // Push middleware if multiple + if (isset($values['middleware'])) { + $this->setMiddlewares(array_merge((array)$values['middleware'], $this->middlewares)); + } + + return $this; + } + + /** + * Get parameter names. + * + * @return array + */ + public function getWhere() + { + return $this->where; + } + + /** + * Set parameter names. + * + * @param array $options + * @return static + */ + public function setWhere(array $options) + { + $this->where = $options; + + return $this; + } + + /** + * Add regular expression parameter match. + * Alias for LoadableRoute::where() + * + * @see LoadableRoute::where() + * @param array $options + * @return static + */ + public function where(array $options) + { + return $this->where($options); + } + + /** + * Get parameters + * + * @return array + */ + public function getParameters() + { + return $this->parameters; + } + + /** + * Get parameters + * + * @param array $parameters + * @return static $this + */ + public function setParameters(array $parameters) + { + $this->parameters = $parameters; + + return $this; + } + + /** + * Set middleware class-name + * + * @param string $middleware + * @return static + */ + public function setMiddleware($middleware) + { + $this->middlewares[] = $middleware; + + return $this; + } + + /** + * Set middlewares array + * + * @param array $middlewares + * @return $this + */ + public function setMiddlewares(array $middlewares) + { + $this->middlewares = $middlewares; + + return $this; + } + + /** + * @return string|array + */ + public function getMiddlewares() + { + return $this->middlewares; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/RouteController.php b/src/Pecee/SimpleRouter/Route/RouteController.php index 441e6c7..6f96f50 100644 --- a/src/Pecee/SimpleRouter/Route/RouteController.php +++ b/src/Pecee/SimpleRouter/Route/RouteController.php @@ -6,201 +6,201 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; class RouteController extends LoadableRoute implements IControllerRoute { - protected $defaultMethod = 'index'; - protected $controller; - protected $method; - protected $names = []; + protected $defaultMethod = 'index'; + protected $controller; + protected $method; + protected $names = []; - public function __construct($url, $controller) - { - $this->setUrl($url); - $this->setName(trim(str_replace('/', '.', $url), '/')); - $this->controller = $controller; - } + public function __construct($url, $controller) + { + $this->setUrl($url); + $this->setName(trim(str_replace('/', '.', $url), '/')); + $this->controller = $controller; + } - /** - * Check if route has given name. - * - * @param string $name - * @return bool - */ - public function hasName($name) - { - if ($this->name === null) { - return false; - } + /** + * Check if route has given name. + * + * @param string $name + * @return bool + */ + public function hasName($name) + { + if ($this->name === null) { + return false; + } - /* Remove method/type */ - if (stripos($name, '.') !== false) { - $method = substr($name, strrpos($name, '.') + 1); - $newName = substr($name, 0, strrpos($name, '.')); + /* Remove method/type */ + if (stripos($name, '.') !== false) { + $method = substr($name, strrpos($name, '.') + 1); + $newName = substr($name, 0, strrpos($name, '.')); - if (strtolower($this->name) === strtolower($newName) && in_array($method, $this->names)) { - return true; - } - } + if (strtolower($this->name) === strtolower($newName) && in_array($method, $this->names)) { + return true; + } + } - return parent::hasName($name); - } + return parent::hasName($name); + } - public function findUrl($method = null, $parameters = null, $name = null) - { + public function findUrl($method = null, $parameters = null, $name = null) + { - if (stripos($name, '.') !== false) { - $found = array_search(substr($name, strrpos($name, '.') + 1), $this->names); - if ($found !== false) { - $method = $found; - } - } + if (stripos($name, '.') !== false) { + $found = array_search(substr($name, strrpos($name, '.') + 1), $this->names); + if ($found !== false) { + $method = $found; + } + } - $url = ''; + $url = ''; - $parameters = (array)$parameters; + $parameters = (array)$parameters; - /* Remove requestType from method-name, if it exists */ - if ($method !== null) { + /* Remove requestType from method-name, if it exists */ + if ($method !== null) { - $max = count(static::$requestTypes); + $max = count(static::$requestTypes); - for ($i = 0; $i < $max; $i++) { + for ($i = 0; $i < $max; $i++) { - $requestType = static::$requestTypes[$i]; + $requestType = static::$requestTypes[$i]; - if (stripos($method, $requestType) === 0) { - $method = substr($method, strlen($requestType)); - break; - } - } + if (stripos($method, $requestType) === 0) { + $method = substr($method, strlen($requestType)); + break; + } + } - $method .= '/'; - } + $method .= '/'; + } - if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) { - $url .= '//' . $this->getGroup()->getDomains()[0]; - } + if ($this->getGroup() !== null && count($this->getGroup()->getDomains()) > 0) { + $url .= '//' . $this->getGroup()->getDomains()[0]; + } - $url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters); + $url .= '/' . trim($this->getUrl(), '/') . '/' . strtolower($method) . join('/', $parameters); - return '/' . trim($url, '/') . '/'; - } + return '/' . trim($url, '/') . '/'; + } - public function renderRoute(Request $request) - { - if ($this->getCallback() !== null && is_callable($this->getCallback())) { + public function renderRoute(Request $request) + { + if ($this->getCallback() !== null && is_callable($this->getCallback())) { - // When the callback is a function - call_user_func_array($this->getCallback(), $this->getParameters()); - } else { - // When the callback is a method - $controller = explode('@', $this->getCallback()); - $className = $this->getNamespace() . '\\' . $controller[0]; + // When the callback is a function + call_user_func_array($this->getCallback(), $this->getParameters()); + } else { + // When the callback is a method + $controller = explode('@', $this->getCallback()); + $className = $this->getNamespace() . '\\' . $controller[0]; - $class = $this->loadClass($className); - $method = $request->getMethod() . ucfirst($controller[1]); + $class = $this->loadClass($className); + $method = $request->getMethod() . ucfirst($controller[1]); - if (!method_exists($class, $method)) { - throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); - } + if (!method_exists($class, $method)) { + throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); + } - call_user_func_array([$class, $method], $this->getParameters()); + call_user_func_array([$class, $method], $this->getParameters()); - return $class; - } + return $class; + } - return null; - } + return null; + } - public function matchRoute(Request $request) - { - $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); - $url = rtrim($url, '/') . '/'; + public function matchRoute(Request $request) + { + $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); + $url = rtrim($url, '/') . '/'; - if (strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { + if (strtolower($url) == strtolower($this->url) || stripos($url, $this->url) === 0) { - $strippedUrl = trim(str_ireplace($this->url, '/', $url), '/'); + $strippedUrl = trim(str_ireplace($this->url, '/', $url), '/'); - $path = explode('/', $strippedUrl); + $path = explode('/', $strippedUrl); - if (count($path) > 0) { + if (count($path) > 0) { - $method = (!isset($path[0]) || trim($path[0]) === '') ? $this->defaultMethod : $path[0]; - $this->method = $method; + $method = (!isset($path[0]) || trim($path[0]) === '') ? $this->defaultMethod : $path[0]; + $this->method = $method; - array_shift($path); - $this->parameters = $path; + array_shift($path); + $this->parameters = $path; - // Set callback - $this->setCallback($this->controller . '@' . $this->method); + // Set callback + $this->setCallback($this->controller . '@' . $this->method); - return true; - } - } + return true; + } + } - return null; - } + return null; + } - /** - * Get controller class-name. - * - * @return string - */ - public function getController() - { - return $this->controller; - } + /** + * Get controller class-name. + * + * @return string + */ + public function getController() + { + return $this->controller; + } - /** - * Get controller class-name. - * - * @param string $controller - * @return static - */ - public function setController($controller) - { - $this->controller = $controller; + /** + * Get controller class-name. + * + * @param string $controller + * @return static + */ + public function setController($controller) + { + $this->controller = $controller; - return $this; - } + return $this; + } - /** - * Return active method - * - * @return string - */ - public function getMethod() - { - return $this->method; - } + /** + * Return active method + * + * @return string + */ + public function getMethod() + { + return $this->method; + } - /** - * Set active method - * - * @param string $method - * @return static - */ - public function setMethod($method) - { - $this->method = $method; + /** + * Set active method + * + * @param string $method + * @return static + */ + public function setMethod($method) + { + $this->method = $method; - return $this; - } + return $this; + } - /** - * Merge with information from another route. - * - * @param array $values - * @param bool $merge - * @return static - */ - public function setSettings(array $values, $merge = false) - { - if (isset($values['names'])) { - $this->names = $values['names']; - } + /** + * Merge with information from another route. + * + * @param array $values + * @param bool $merge + * @return static + */ + public function setSettings(array $values, $merge = false) + { + if (isset($values['names'])) { + $this->names = $values['names']; + } - parent::setSettings($values, $merge); + parent::setSettings($values, $merge); - return $this; - } + return $this; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/RouteGroup.php b/src/Pecee/SimpleRouter/Route/RouteGroup.php index a314d54..2c04556 100644 --- a/src/Pecee/SimpleRouter/Route/RouteGroup.php +++ b/src/Pecee/SimpleRouter/Route/RouteGroup.php @@ -5,177 +5,177 @@ use Pecee\Http\Request; class RouteGroup extends Route implements IGroupRoute { - protected $prefix; - protected $name; - protected $domains = []; - protected $exceptionHandlers = []; + protected $prefix; + protected $name; + protected $domains = []; + protected $exceptionHandlers = []; - /** - * Method called to check if a domain matches - * - * @param Request $request - * @return bool - */ - public function matchDomain(Request $request) - { - if (count($this->domains) > 0) { + /** + * Method called to check if a domain matches + * + * @param Request $request + * @return bool + */ + public function matchDomain(Request $request) + { + if (count($this->domains) > 0) { - $max = count($this->domains) - 1; + $max = count($this->domains) - 1; - for ($i = $max; $i >= 0; $i--) { + for ($i = $max; $i >= 0; $i--) { - $domain = $this->domains[$i]; - $parameters = $this->parseParameters($domain, $request->getHost(), '.*'); + $domain = $this->domains[$i]; + $parameters = $this->parseParameters($domain, $request->getHost(), '.*'); - if ($parameters !== null) { - $this->parameters = $parameters; + if ($parameters !== null) { + $this->parameters = $parameters; - return true; - } - } + return true; + } + } - return false; - } + return false; + } - return true; - } + return true; + } - /** - * Method called to check if route matches - * - * @param Request $request - * @return bool - */ - public function matchRoute(Request $request) - { - // Skip if prefix doesn't match - if ($this->prefix !== null && stripos($request->getUri(), $this->prefix) === false) { - return false; - } + /** + * Method called to check if route matches + * + * @param Request $request + * @return bool + */ + public function matchRoute(Request $request) + { + // Skip if prefix doesn't match + if ($this->prefix !== null && stripos($request->getUri(), $this->prefix) === false) { + return false; + } - return $this->matchDomain($request); - } + return $this->matchDomain($request); + } - /** - * Set exception-handlers for group - * - * @param array $handlers - * @return static $this - */ - public function setExceptionHandlers(array $handlers) - { - $this->exceptionHandlers = $handlers; + /** + * Set exception-handlers for group + * + * @param array $handlers + * @return static $this + */ + public function setExceptionHandlers(array $handlers) + { + $this->exceptionHandlers = $handlers; - return $this; - } + return $this; + } - /** - * Get exception-handlers for group - * - * @return array - */ - public function getExceptionHandlers() - { - return $this->exceptionHandlers; - } + /** + * Get exception-handlers for group + * + * @return array + */ + public function getExceptionHandlers() + { + return $this->exceptionHandlers; + } - /** - * Get allowed domains for domain. - * - * @return array - */ - public function getDomains() - { - return $this->domains; - } + /** + * Get allowed domains for domain. + * + * @return array + */ + public function getDomains() + { + return $this->domains; + } - /** - * Set allowed domains for group. - * - * @param array $domains - * @return $this - */ - public function setDomains(array $domains) - { - $this->domains = $domains; + /** + * Set allowed domains for group. + * + * @param array $domains + * @return $this + */ + public function setDomains(array $domains) + { + $this->domains = $domains; - return $this; - } + return $this; + } - /** - * @param string $prefix - * @return static - */ - public function setPrefix($prefix) - { - $this->prefix = '/' . trim($prefix, '/'); + /** + * @param string $prefix + * @return static + */ + public function setPrefix($prefix) + { + $this->prefix = '/' . trim($prefix, '/'); - return $this; - } + return $this; + } - /** - * Set prefix that child-routes will inherit. - * - * @return string - */ - public function getPrefix() - { - return $this->prefix; - } + /** + * Set prefix that child-routes will inherit. + * + * @return string + */ + public function getPrefix() + { + return $this->prefix; + } - /** - * Merge with information from another route. - * - * @param array $values - * @param bool $merge - * @return static - */ - public function setSettings(array $values, $merge = false) - { + /** + * Merge with information from another route. + * + * @param array $values + * @param bool $merge + * @return static + */ + public function setSettings(array $values, $merge = false) + { - if (isset($values['prefix'])) { - $this->setPrefix($values['prefix'] . $this->prefix); - } + if (isset($values['prefix'])) { + $this->setPrefix($values['prefix'] . $this->prefix); + } - if (isset($values['exceptionHandler'])) { - $this->setExceptionHandlers((array)$values['exceptionHandler']); - } + if (isset($values['exceptionHandler'])) { + $this->setExceptionHandlers((array)$values['exceptionHandler']); + } - if (isset($values['domain'])) { - $this->setDomains((array)$values['domain']); - } + if (isset($values['domain'])) { + $this->setDomains((array)$values['domain']); + } - if (isset($values['as'])) { - if ($this->name !== null && $merge !== false) { - $this->name = $values['as'] . '.' . $this->name; - } else { - $this->name = $values['as']; - } - } + if (isset($values['as'])) { + if ($this->name !== null && $merge !== false) { + $this->name = $values['as'] . '.' . $this->name; + } else { + $this->name = $values['as']; + } + } - parent::setSettings($values, $merge); + parent::setSettings($values, $merge); - return $this; - } + return $this; + } - /** - * Export route settings to array so they can be merged with another route. - * - * @return array - */ - public function toArray() - { - $values = []; + /** + * Export route settings to array so they can be merged with another route. + * + * @return array + */ + public function toArray() + { + $values = []; - if ($this->prefix !== null) { - $values['prefix'] = $this->getPrefix(); - } + if ($this->prefix !== null) { + $values['prefix'] = $this->getPrefix(); + } - if ($this->name !== null) { - $values['as'] = $this->name; - } + if ($this->name !== null) { + $values['as'] = $this->name; + } - return array_merge($values, parent::toArray()); - } + return array_merge($values, parent::toArray()); + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/RouteResource.php b/src/Pecee/SimpleRouter/Route/RouteResource.php index f395a6e..b877e29 100644 --- a/src/Pecee/SimpleRouter/Route/RouteResource.php +++ b/src/Pecee/SimpleRouter/Route/RouteResource.php @@ -6,198 +6,198 @@ use Pecee\SimpleRouter\Exceptions\NotFoundHttpException; class RouteResource extends LoadableRoute implements IControllerRoute { - protected $urls = [ - 'index' => '', - 'create' => 'create', - 'store' => '', - 'show' => '', - 'edit' => 'edit', - 'update' => '', - 'destroy' => '', - ]; - protected $names = []; - protected $controller; + protected $urls = [ + 'index' => '', + 'create' => 'create', + 'store' => '', + 'show' => '', + 'edit' => 'edit', + 'update' => '', + 'destroy' => '', + ]; + protected $names = []; + protected $controller; - public function __construct($url, $controller) - { - $this->setUrl($url); - $this->controller = $controller; - $this->setName(trim(str_replace('/', '.', $url), '/')); - } + public function __construct($url, $controller) + { + $this->setUrl($url); + $this->controller = $controller; + $this->setName(trim(str_replace('/', '.', $url), '/')); + } - /** - * Check if route has given name. - * - * @param string $name - * @return bool - */ - public function hasName($name) - { - if ($this->name === null) { - return false; - } + /** + * Check if route has given name. + * + * @param string $name + * @return bool + */ + public function hasName($name) + { + if ($this->name === null) { + return false; + } - if (strtolower($this->name) === strtolower($name)) { - return true; - } + if (strtolower($this->name) === strtolower($name)) { + return true; + } - /* Remove method/type */ - if (stripos($name, '.') !== false) { - $name = substr($name, 0, strrpos($name, '.')); - } + /* Remove method/type */ + if (stripos($name, '.') !== false) { + $name = substr($name, 0, strrpos($name, '.')); + } - return (strtolower($this->name) === strtolower($name)); - } + return (strtolower($this->name) === strtolower($name)); + } - public function findUrl($method = null, $parameters = null, $name = null) - { - $method = array_search($name, $this->names); - if ($method !== false) { - return rtrim($this->url . $this->urls[$method], '/') . '/'; - } + public function findUrl($method = null, $parameters = null, $name = null) + { + $method = array_search($name, $this->names); + if ($method !== false) { + return rtrim($this->url . $this->urls[$method], '/') . '/'; + } - return $this->url; - } + return $this->url; + } - public function renderRoute(Request $request) - { - if ($this->getCallback() !== null && is_callable($this->getCallback())) { - // When the callback is a function - call_user_func_array($this->getCallback(), $this->getParameters()); - } else { - // When the callback is a method - $controller = explode('@', $this->getCallback()); - $className = $this->getNamespace() . '\\' . $controller[0]; - $class = $this->loadClass($className); - $method = strtolower($controller[1]); + public function renderRoute(Request $request) + { + if ($this->getCallback() !== null && is_callable($this->getCallback())) { + // When the callback is a function + call_user_func_array($this->getCallback(), $this->getParameters()); + } else { + // When the callback is a method + $controller = explode('@', $this->getCallback()); + $className = $this->getNamespace() . '\\' . $controller[0]; + $class = $this->loadClass($className); + $method = strtolower($controller[1]); - if (!method_exists($class, $method)) { - throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); - } + if (!method_exists($class, $method)) { + throw new NotFoundHttpException(sprintf('Method %s does not exist in class %s', $method, $className), 404); + } - call_user_func_array([$class, $method], $this->getParameters()); + call_user_func_array([$class, $method], $this->getParameters()); - return $class; - } + return $class; + } - return null; - } + return null; + } - protected function call($method, $parameters) - { - $this->setCallback($this->controller . '@' . $method); - $this->parameters = $parameters; + protected function call($method, $parameters) + { + $this->setCallback($this->controller . '@' . $method); + $this->parameters = $parameters; - return true; - } + return true; + } - public function matchRoute(Request $request) - { - $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); - $url = rtrim($url, '/') . '/'; + public function matchRoute(Request $request) + { + $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); + $url = rtrim($url, '/') . '/'; - $route = rtrim($this->url, '/') . '/{id?}/{action?}'; + $route = rtrim($this->url, '/') . '/{id?}/{action?}'; - $parameters = $this->parseParameters($route, $url); + $parameters = $this->parseParameters($route, $url); - if ($parameters !== null) { + if ($parameters !== null) { - $parameters = array_merge($this->parameters, (array)$parameters); + $parameters = array_merge($this->parameters, (array)$parameters); - $action = isset($parameters['action']) ? $parameters['action'] : null; - unset($parameters['action']); + $action = isset($parameters['action']) ? $parameters['action'] : null; + unset($parameters['action']); - $method = $request->getMethod(); + $method = $request->getMethod(); - // Delete - if (isset($parameters['id']) && $method === static::REQUEST_TYPE_DELETE) { - return $this->call('destroy', $parameters); - } + // Delete + if (isset($parameters['id']) && $method === static::REQUEST_TYPE_DELETE) { + return $this->call('destroy', $parameters); + } - // Update - if (isset($parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT])) { - return $this->call('update', $parameters); - } + // Update + if (isset($parameters['id']) && in_array($method, [static::REQUEST_TYPE_PATCH, static::REQUEST_TYPE_PUT])) { + return $this->call('update', $parameters); + } - // Edit - if (isset($parameters['id']) && strtolower($action) === 'edit' && $method === static::REQUEST_TYPE_GET) { - return $this->call('edit', $parameters); - } + // Edit + if (isset($parameters['id']) && strtolower($action) === 'edit' && $method === static::REQUEST_TYPE_GET) { + return $this->call('edit', $parameters); + } - // Create - if (strtolower($action) === 'create' && $method === static::REQUEST_TYPE_GET) { - return $this->call('create', $parameters); - } + // Create + if (strtolower($action) === 'create' && $method === static::REQUEST_TYPE_GET) { + return $this->call('create', $parameters); + } - // Save - if ($method === static::REQUEST_TYPE_POST) { - return $this->call('store', $parameters); - } + // Save + if ($method === static::REQUEST_TYPE_POST) { + return $this->call('store', $parameters); + } - // Show - if (isset($parameters['id']) && $method === static::REQUEST_TYPE_GET) { - return $this->call('show', $parameters); - } + // Show + if (isset($parameters['id']) && $method === static::REQUEST_TYPE_GET) { + return $this->call('show', $parameters); + } - // Index - return $this->call('index', $parameters); - } + // Index + return $this->call('index', $parameters); + } - return null; - } + return null; + } - /** - * @return string - */ - public function getController() - { - return $this->controller; - } + /** + * @return string + */ + public function getController() + { + return $this->controller; + } - /** - * @param string $controller - * @return static - */ - public function setController($controller) - { - $this->controller = $controller; + /** + * @param string $controller + * @return static + */ + public function setController($controller) + { + $this->controller = $controller; - return $this; - } + return $this; + } - public function setName($name) - { - $this->name = $name; + public function setName($name) + { + $this->name = $name; - $this->names = [ - 'index' => $this->name . '.index', - 'create' => $this->name . '.create', - 'store' => $this->name . '.store', - 'show' => $this->name . '.show', - 'edit' => $this->name . '.edit', - 'update' => $this->name . '.update', - 'destroy' => $this->name . '.destroy', - ]; + $this->names = [ + 'index' => $this->name . '.index', + 'create' => $this->name . '.create', + 'store' => $this->name . '.store', + 'show' => $this->name . '.show', + 'edit' => $this->name . '.edit', + 'update' => $this->name . '.update', + 'destroy' => $this->name . '.destroy', + ]; - return $this; - } + return $this; + } - /** - * Merge with information from another route. - * - * @param array $values - * @param bool $merge - * @return static - */ - public function setSettings(array $values, $merge = false) - { - if (isset($values['names'])) { - $this->names = $values['names']; - } + /** + * Merge with information from another route. + * + * @param array $values + * @param bool $merge + * @return static + */ + public function setSettings(array $values, $merge = false) + { + if (isset($values['names'])) { + $this->names = $values['names']; + } - parent::setSettings($values, $merge); + parent::setSettings($values, $merge); - return $this; - } + return $this; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Route/RouteUrl.php b/src/Pecee/SimpleRouter/Route/RouteUrl.php index 23f47cf..baa2329 100644 --- a/src/Pecee/SimpleRouter/Route/RouteUrl.php +++ b/src/Pecee/SimpleRouter/Route/RouteUrl.php @@ -5,45 +5,45 @@ use Pecee\Http\Request; class RouteUrl extends LoadableRoute { - public function __construct($url, $callback) - { - $this->setUrl($url); - $this->setCallback($callback); - } + public function __construct($url, $callback) + { + $this->setUrl($url); + $this->setCallback($callback); + } - public function matchRoute(Request $request) - { - $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); - $url = rtrim($url, '/') . '/'; + public function matchRoute(Request $request) + { + $url = parse_url(urldecode($request->getUri()), PHP_URL_PATH); + $url = rtrim($url, '/') . '/'; - // Match on custom defined regular expression - if ($this->regex !== null) { - $parameters = []; - if (preg_match($this->regex, $request->getHost() . $url, $parameters)) { - /* Remove global match */ - if(count($parameters) > 1) { - array_shift($parameters); - $this->parameters = $parameters; - } + // Match on custom defined regular expression + if ($this->regex !== null) { + $parameters = []; + if (preg_match($this->regex, $request->getHost() . $url, $parameters)) { + /* Remove global match */ + if (count($parameters) > 1) { + array_shift($parameters); + $this->parameters = $parameters; + } - return true; - } + return true; + } - return null; - } + return null; + } - // Make regular expression based on route - $route = rtrim($this->url, '/') . '/'; + // Make regular expression based on route + $route = rtrim($this->url, '/') . '/'; - $parameters = $this->parseParameters($route, $url); + $parameters = $this->parseParameters($route, $url); - if ($parameters !== null) { - $this->parameters = array_merge($this->parameters, $parameters); + if ($parameters !== null) { + $this->parameters = array_merge($this->parameters, $parameters); - return true; - } + return true; + } - return null; - } + return null; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/Router.php b/src/Pecee/SimpleRouter/Router.php index 071918a..62c22d2 100644 --- a/src/Pecee/SimpleRouter/Router.php +++ b/src/Pecee/SimpleRouter/Router.php @@ -14,534 +14,536 @@ use Pecee\SimpleRouter\Route\IRoute; class Router { - /** - * The instance of this class - * @var static - */ - protected static $instance; - - /** - * Current request - * @var Request - */ - protected $request; - - /** - * Defines if a route is currently being processed. - * @var bool - */ - protected $processingRoute; - - /** - * All added routes - * @var array - */ - protected $routes; - - /** - * List of processed routes - * @var array - */ - protected $processedRoutes; - - /** - * Stack of routes used to keep track of sub-routes added - * when a route is being processed. - * @var array - */ - protected $routeStack; - - /** - * List of added bootmanagers - * @var array - */ - protected $bootManagers; - - /** - * Csrf verifier class - * @var BaseCsrfVerifier - */ - protected $csrfVerifier; - - /** - * Get exception handlers - * @var array - */ - protected $exceptionHandlers; - - /** - * The current loaded route - * @var ILoadableRoute|null - */ - protected $loadedRoute; - - /** - * List over route changes (to avoid endless-looping) - * @var array - */ - protected $routeRewrites = []; - - /** - * If the route has been rewritten/changed this property will contain the original url. - * @var string - */ - protected $originalUrl; - - /** - * Get current router instance - * @return static - */ - public static function getInstance() - { - if (static::$instance === null) { - static::$instance = new static(); - } - - return static::$instance; - } - - public function __construct() - { - $this->reset(); - } - - public function reset() - { - $this->processingRoute = false; - $this->request = new Request(); - $this->routes = []; - $this->bootManagers = []; - $this->routeStack = []; - $this->processedRoutes = []; - $this->exceptionHandlers = []; - } - - /** - * Add route - * @param IRoute $route - * @return IRoute - */ - public function addRoute(IRoute $route) - { - /* - * If a route is currently being processed, that means that the - * route being added are rendered from the parent routes callback, - * so we add them to the stack instead. - */ - if ($this->processingRoute === true) { - $this->routeStack[] = $route; - } else { - $this->routes[] = $route; - } - - return $route; - } - - protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null) - { - // Loop through each route-request - $max = count($routes) - 1; - - /* @var $route IRoute */ - for ($i = $max; $i >= 0; $i--) { - - $route = $routes[$i]; + /** + * The instance of this class + * @var static + */ + protected static $instance; + + /** + * Current request + * @var Request + */ + protected $request; + + /** + * Defines if a route is currently being processed. + * @var bool + */ + protected $processingRoute; + + /** + * All added routes + * @var array + */ + protected $routes; + + /** + * List of processed routes + * @var array + */ + protected $processedRoutes; + + /** + * Stack of routes used to keep track of sub-routes added + * when a route is being processed. + * @var array + */ + protected $routeStack; + + /** + * List of added bootmanagers + * @var array + */ + protected $bootManagers; + + /** + * Csrf verifier class + * @var BaseCsrfVerifier + */ + protected $csrfVerifier; + + /** + * Get exception handlers + * @var array + */ + protected $exceptionHandlers; + + /** + * The current loaded route + * @var ILoadableRoute|null + */ + protected $loadedRoute; + + /** + * List over route changes (to avoid endless-looping) + * @var array + */ + protected $routeRewrites = []; + + /** + * If the route has been rewritten/changed this property will contain the original url. + * @var string + */ + protected $originalUrl; + + /** + * Get current router instance + * @return static + */ + public static function getInstance() + { + if (static::$instance === null) { + static::$instance = new static(); + } + + return static::$instance; + } + + public function __construct() + { + $this->reset(); + } + + public function reset() + { + $this->processingRoute = false; + $this->request = new Request(); + $this->routes = []; + $this->bootManagers = []; + $this->routeStack = []; + $this->processedRoutes = []; + $this->exceptionHandlers = []; + } + + /** + * Add route + * @param IRoute $route + * @return IRoute + */ + public function addRoute(IRoute $route) + { + /* + * If a route is currently being processed, that means that the + * route being added are rendered from the parent routes callback, + * so we add them to the stack instead. + */ + if ($this->processingRoute === true) { + $this->routeStack[] = $route; + } else { + $this->routes[] = $route; + } + + return $route; + } + + protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null) + { + // Loop through each route-request + $max = count($routes) - 1; + + /* @var $route IRoute */ + for ($i = $max; $i >= 0; $i--) { + + $route = $routes[$i]; - if ($route instanceof IGroupRoute) { + if ($route instanceof IGroupRoute) { - $group = $route; + $group = $route; - if ($route->getCallback() !== null && is_callable($route->getCallback())) { + if ($route->getCallback() !== null && is_callable($route->getCallback())) { - $this->processingRoute = true; - $route->renderRoute($this->request); - $this->processingRoute = false; + $this->processingRoute = true; + $route->renderRoute($this->request); + $this->processingRoute = false; - if ($route->matchRoute($this->request)) { + if ($route->matchRoute($this->request)) { - /* Add exceptionhandlers */ - if (count($route->getExceptionHandlers()) > 0) { - $this->exceptionHandlers = array_merge($route->getExceptionHandlers(), $this->exceptionHandlers); - } + /* Add exceptionhandlers */ + if (count($route->getExceptionHandlers()) > 0) { + $this->exceptionHandlers = array_merge($route->getExceptionHandlers(), $this->exceptionHandlers); + } - } - } - } + } + } + } - if ($group !== null) { + if ($group !== null) { - /* Add the parent group */ - $route->setGroup($group); + /* Add the parent group */ + $route->setGroup($group); - } + } - if ($parent !== null) { + if ($parent !== null) { - /* Add the parent route */ - $route->setParent($parent); + /* Add the parent route */ + $route->setParent($parent); - /* Add/merge parent settings with child */ - $route->setSettings($parent->toArray(), true); + /* Add/merge parent settings with child */ + $route->setSettings($parent->toArray(), true); - } + } - if ($route instanceof ILoadableRoute) { + if ($route instanceof ILoadableRoute) { - /* Add the route to the map, so we can find the active one when all routes has been loaded */ - $this->processedRoutes[] = $route; - } + /* Add the route to the map, so we can find the active one when all routes has been loaded */ + $this->processedRoutes[] = $route; + } - if (count($this->routeStack) > 0) { + if (count($this->routeStack) > 0) { - /* Pop and grap the routes added when executing group callback earlier */ - $stack = $this->routeStack; - $this->routeStack = []; + /* Pop and grap the routes added when executing group callback earlier */ + $stack = $this->routeStack; + $this->routeStack = []; - /* Route any routes added to the stack */ - $this->processRoutes($stack, $route, $group); - } - } - } + /* Route any routes added to the stack */ + $this->processRoutes($stack, $route, $group); + } + } + } - public function routeRequest($rewrite = false) - { - $this->loadedRoute = null; - $routeNotAllowed = false; + public function routeRequest($rewrite = false) + { + $this->loadedRoute = null; + $routeNotAllowed = false; - try { + try { - /* Initialize boot-managers */ - if (count($this->bootManagers) > 0) { + /* Initialize boot-managers */ + if (count($this->bootManagers) > 0) { - $max = count($this->bootManagers) - 1; + $max = count($this->bootManagers) - 1; - /* @var $manager IRouterBootManager */ - for ($i = $max; $i >= 0; $i--) { + /* @var $manager IRouterBootManager */ + for ($i = $max; $i >= 0; $i--) { - $manager = $this->bootManagers[$i]; + $manager = $this->bootManagers[$i]; - $this->request = $manager->boot($this->request); + $this->request = $manager->boot($this->request); - if (!($this->request instanceof Request)) { - throw new HttpException('Bootmanager "' . get_class($manager) . '" must return instance of ' . Request::class, 500); - } - } - } + if (!($this->request instanceof Request)) { + throw new HttpException('Bootmanager "' . get_class($manager) . '" must return instance of ' . Request::class, 500); + } + } + } - if ($rewrite === false) { + if ($rewrite === false) { - /* Loop through each route-request */ - $this->processRoutes($this->routes); + /* Loop through each route-request */ + $this->processRoutes($this->routes); - if ($this->csrfVerifier !== null) { + if ($this->csrfVerifier !== null) { - // Verify csrf token for request - $this->csrfVerifier->handle($this->request); - } + // Verify csrf token for request + $this->csrfVerifier->handle($this->request); + } - $this->originalUrl = $this->request->getUri(); - } + $this->originalUrl = $this->request->getUri(); + } - $max = count($this->processedRoutes) - 1; + $max = count($this->processedRoutes) - 1; - /* @var $route IRoute */ - for ($i = $max; $i >= 0; $i--) { + /* @var $route IRoute */ + for ($i = $max; $i >= 0; $i--) { - $route = $this->processedRoutes[$i]; + $route = $this->processedRoutes[$i]; - /* If the route matches */ - if ($route->matchRoute($this->request)) { + /* If the route matches */ + if ($route->matchRoute($this->request)) { - /* Check if request method matches */ - if (count($route->getRequestMethods()) > 0 && !in_array($this->request->getMethod(), $route->getRequestMethods())) { - $routeNotAllowed = true; - continue; - } + /* Check if request method matches */ + if (count($route->getRequestMethods()) > 0 && !in_array($this->request->getMethod(), $route->getRequestMethods())) { + $routeNotAllowed = true; + continue; + } - $this->loadedRoute = $route; - $this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute); + $this->loadedRoute = $route; + $this->loadedRoute->loadMiddleware($this->request, $this->loadedRoute); - /* If the request has changed, we reinitialize the router */ - if ($this->request->getUri() !== $this->originalUrl && !in_array($this->request->getUri(), $this->routeRewrites)) { - $this->routeRewrites[] = $this->request->getUri(); - $this->routeRequest(true); + /* If the request has changed, we reinitialize the router */ + if ($this->request->getUri() !== $this->originalUrl && !in_array($this->request->getUri(), $this->routeRewrites)) { + $this->routeRewrites[] = $this->request->getUri(); + $this->routeRequest(true); - return; - } + return; + } - /* Render route */ - $routeNotAllowed = false; - $this->request->setUri($this->originalUrl); - $this->loadedRoute->renderRoute($this->request); + /* Render route */ + $routeNotAllowed = false; + $this->request->setUri($this->originalUrl); + $this->loadedRoute->renderRoute($this->request); - break; - } - } + break; + } + } - } catch (\Exception $e) { - $this->handleException($e); - } + } catch (\Exception $e) { + $this->handleException($e); + } - if ($routeNotAllowed === true) { - $this->handleException(new HttpException('Route or method not allowed', 403)); - } + if ($routeNotAllowed === true) { + $this->handleException(new HttpException('Route or method not allowed', 403)); + } - if ($this->loadedRoute === null) { - $this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404)); - } - } + if ($this->loadedRoute === null) { + $this->handleException(new NotFoundHttpException('Route not found: ' . $this->request->getUri(), 404)); + } + } - protected function handleException(\Exception $e) - { - $max = count($this->exceptionHandlers); + protected function handleException(\Exception $e) + { + $max = count($this->exceptionHandlers); - /* @var $handler IExceptionHandler */ - for ($i = 0; $i < $max; $i++) { + /* @var $handler IExceptionHandler */ + for ($i = 0; $i < $max; $i++) { - $handler = $this->exceptionHandlers[$i]; + $handler = $this->exceptionHandlers[$i]; - $handler = new $handler(); + $handler = new $handler(); - if (!($handler instanceof IExceptionHandler)) { - throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500); - } + if (!($handler instanceof IExceptionHandler)) { + throw new HttpException('Exception handler must implement the IExceptionHandler interface.', 500); + } - $request = $handler->handleError($this->request, $this->loadedRoute, $e); + $request = $handler->handleError($this->request, $this->loadedRoute, $e); - /* If the request has changed */ - if ($request !== null && $this->request->getUri() !== $this->originalUrl && !in_array($request->getUri(), $this->routeRewrites)) { - $this->request = $request; - $this->routeRewrites[] = $request->getUri(); - $this->routeRequest(true); - - return; - } - } - - throw $e; - } - - public function arrayToParams(array $getParams = [], $includeEmpty = true) - { - if (count($getParams) > 0) { - - if ($includeEmpty === false) { - $getParams = array_filter($getParams, function ($item) { - return (!empty($item)); - }); - } - - return '?' . http_build_query($getParams); - } - - return ''; - } - - /** - * Find route by alias, class, callback or method. - * - * @param string $name - * @return ILoadableRoute|null - */ - public function findRoute($name) - { - $max = count($this->processedRoutes) - 1; - - /* @var $route ILoadableRoute */ - for ($i = $max; $i >= 0; $i--) { - - $route = $this->processedRoutes[$i]; - - /* Check if the name matches with a name on the route. Should match either router alias or controller alias. */ - if ($route->hasName($name)) { - return $route; - } - - /* Direct match to controller */ - if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) { - return $route; - } - - /* Using @ is most definitely a controller@method or alias@method */ - if (strpos($name, '@') !== false) { - list($controller, $method) = array_map('strtolower', explode('@', $name)); - - if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) { - return $route; - } - } - - /* Check if callback matches (if it's not a function) */ - if (strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) { - - /* Check if the entire callback is matching */ - if (strtolower($route->getCallback()) === strtolower($name) || strpos($route->getCallback(), $name) === 0) { - return $route; - } - - /* Check if the class part of the callback matches (class@method) */ - if (strtolower($name) === strtolower($route->getClass())) { - return $route; - } - } - } - - return null; - } - - /** - * Get url for a route by using either name/alias, class or method name. - * - * The name parameter supports the following values: - * - Route name - * - Controller/resource name (with or without method) - * - Controller class name - * - * When searching for controller/resource by name, you can use this syntax "route.name@method". - * You can also use the same syntax when searching for a specific controller-class "MyController@home". - * If no arguments is specified, it will return the url for the current loaded route. - * - * @param string|null $name - * @param string|array|null $parameters - * @param array|null $getParams - * @return string - */ - public function getUrl($name = null, $parameters = null, $getParams = null) - { - if ($getParams !== null && is_array($getParams) === false) { - throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null'); - } - - /* Only merge $_GET when all parameters are null */ - if ($name === null && $parameters === null && $getParams === null) { - $getParams = $_GET; - } else { - $getParams = (array)$getParams; - } - - /* Return current route if no options has been specified */ - if ($name === null && $parameters === null) { - $url = rtrim(parse_url($this->request->getUri(), PHP_URL_PATH), '/'); - return (($url === '') ? '/' : $url . '/') . $this->arrayToParams($getParams); - } - - /* If nothing is defined and a route is loaded we use that */ - if ($name === null && $this->loadedRoute !== null) { - return $this->loadedRoute->findUrl($this->loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams); - } - - /* We try to find a match on the given name */ - $route = $this->findRoute($name); - - if ($route !== null) { - return $route->findUrl($route->getMethod(), $parameters, $name) . $this->arrayToParams($getParams); - } - - /* Using @ is most definitely a controller@method or alias@method */ - if (stripos($name, '@') !== false) { - list($controller, $method) = explode('@', $name); - - /* Loop through all the routes to see if we can find a match */ - - $max = count($this->processedRoutes) - 1; - - /* @var $route ILoadableRoute */ - for ($i = $max; $i >= 0; $i--) { - - $route = $this->processedRoutes[$i]; - - /* Check if the route contains the name/alias */ - if ($route->hasName($controller)) { - return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams); - } - - /* Check if the route controller is equal to the name */ - if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($controller)) { - return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams); - } - - } - } - - /* No result so we assume that someone is using a hardcoded url and join everything together. */ - $url = trim(join('/', array_merge((array)$name, (array)$parameters)), '/'); - return (($url === '') ? '/' : '/' . $url . '/') . $this->arrayToParams($getParams); - } - - /** - * Get bootmanagers - * @return array - */ - public function getBootManagers() - { - return $this->bootManagers; - } - - /** - * Set bootmanagers - * @param array $bootManagers - */ - public function setBootManagers(array $bootManagers) - { - $this->bootManagers = $bootManagers; - } - - /** - * Add bootmanager - * @param IRouterBootManager $bootManager - */ - public function addBootManager(IRouterBootManager $bootManager) - { - $this->bootManagers[] = $bootManager; - } - - /** - * @return array - */ - public function getRoutes() - { - return $this->routes; - } - - /** - * Get current request - * - * @return Request - */ - public function getRequest() - { - return $this->request; - } - - /** - * Get csrf verifier class - * @return BaseCsrfVerifier - */ - public function getCsrfVerifier() - { - return $this->csrfVerifier; - } - - /** - * Set csrf verifier class - * - * @param BaseCsrfVerifier $csrfVerifier - * @return static - */ - public function setCsrfVerifier(BaseCsrfVerifier $csrfVerifier) - { - $this->csrfVerifier = $csrfVerifier; - - return $this; - } - - /** - * Get loaded route - * @return ILoadableRoute|null - */ - public function getLoadedRoute() - { - return $this->loadedRoute; - } + /* If the request has changed */ + if ($request !== null && $this->request->getUri() !== $this->originalUrl && !in_array($request->getUri(), $this->routeRewrites)) { + $this->request = $request; + $this->routeRewrites[] = $request->getUri(); + $this->routeRequest(true); + + return; + } + } + + throw $e; + } + + public function arrayToParams(array $getParams = [], $includeEmpty = true) + { + if (count($getParams) > 0) { + + if ($includeEmpty === false) { + $getParams = array_filter($getParams, function ($item) { + return (!empty($item)); + }); + } + + return '?' . http_build_query($getParams); + } + + return ''; + } + + /** + * Find route by alias, class, callback or method. + * + * @param string $name + * @return ILoadableRoute|null + */ + public function findRoute($name) + { + $max = count($this->processedRoutes) - 1; + + /* @var $route ILoadableRoute */ + for ($i = $max; $i >= 0; $i--) { + + $route = $this->processedRoutes[$i]; + + /* Check if the name matches with a name on the route. Should match either router alias or controller alias. */ + if ($route->hasName($name)) { + return $route; + } + + /* Direct match to controller */ + if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($name)) { + return $route; + } + + /* Using @ is most definitely a controller@method or alias@method */ + if (strpos($name, '@') !== false) { + list($controller, $method) = array_map('strtolower', explode('@', $name)); + + if ($controller === strtolower($route->getClass()) && $method === strtolower($route->getMethod())) { + return $route; + } + } + + /* Check if callback matches (if it's not a function) */ + if (strpos($name, '@') !== false && strpos($route->getCallback(), '@') !== false && !is_callable($route->getCallback())) { + + /* Check if the entire callback is matching */ + if (strtolower($route->getCallback()) === strtolower($name) || strpos($route->getCallback(), $name) === 0) { + return $route; + } + + /* Check if the class part of the callback matches (class@method) */ + if (strtolower($name) === strtolower($route->getClass())) { + return $route; + } + } + } + + return null; + } + + /** + * Get url for a route by using either name/alias, class or method name. + * + * The name parameter supports the following values: + * - Route name + * - Controller/resource name (with or without method) + * - Controller class name + * + * When searching for controller/resource by name, you can use this syntax "route.name@method". + * You can also use the same syntax when searching for a specific controller-class "MyController@home". + * If no arguments is specified, it will return the url for the current loaded route. + * + * @param string|null $name + * @param string|array|null $parameters + * @param array|null $getParams + * @return string + */ + public function getUrl($name = null, $parameters = null, $getParams = null) + { + if ($getParams !== null && is_array($getParams) === false) { + throw new \InvalidArgumentException('Invalid type for getParams. Must be array or null'); + } + + /* Only merge $_GET when all parameters are null */ + if ($name === null && $parameters === null && $getParams === null) { + $getParams = $_GET; + } else { + $getParams = (array)$getParams; + } + + /* Return current route if no options has been specified */ + if ($name === null && $parameters === null) { + $url = rtrim(parse_url($this->request->getUri(), PHP_URL_PATH), '/'); + + return (($url === '') ? '/' : $url . '/') . $this->arrayToParams($getParams); + } + + /* If nothing is defined and a route is loaded we use that */ + if ($name === null && $this->loadedRoute !== null) { + return $this->loadedRoute->findUrl($this->loadedRoute->getMethod(), $parameters, $name) . $this->arrayToParams($getParams); + } + + /* We try to find a match on the given name */ + $route = $this->findRoute($name); + + if ($route !== null) { + return $route->findUrl($route->getMethod(), $parameters, $name) . $this->arrayToParams($getParams); + } + + /* Using @ is most definitely a controller@method or alias@method */ + if (stripos($name, '@') !== false) { + list($controller, $method) = explode('@', $name); + + /* Loop through all the routes to see if we can find a match */ + + $max = count($this->processedRoutes) - 1; + + /* @var $route ILoadableRoute */ + for ($i = $max; $i >= 0; $i--) { + + $route = $this->processedRoutes[$i]; + + /* Check if the route contains the name/alias */ + if ($route->hasName($controller)) { + return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams); + } + + /* Check if the route controller is equal to the name */ + if ($route instanceof IControllerRoute && strtolower($route->getController()) === strtolower($controller)) { + return $route->findUrl($method, $parameters, $name) . $this->arrayToParams($getParams); + } + + } + } + + /* No result so we assume that someone is using a hardcoded url and join everything together. */ + $url = trim(join('/', array_merge((array)$name, (array)$parameters)), '/'); + + return (($url === '') ? '/' : '/' . $url . '/') . $this->arrayToParams($getParams); + } + + /** + * Get bootmanagers + * @return array + */ + public function getBootManagers() + { + return $this->bootManagers; + } + + /** + * Set bootmanagers + * @param array $bootManagers + */ + public function setBootManagers(array $bootManagers) + { + $this->bootManagers = $bootManagers; + } + + /** + * Add bootmanager + * @param IRouterBootManager $bootManager + */ + public function addBootManager(IRouterBootManager $bootManager) + { + $this->bootManagers[] = $bootManager; + } + + /** + * @return array + */ + public function getRoutes() + { + return $this->routes; + } + + /** + * Get current request + * + * @return Request + */ + public function getRequest() + { + return $this->request; + } + + /** + * Get csrf verifier class + * @return BaseCsrfVerifier + */ + public function getCsrfVerifier() + { + return $this->csrfVerifier; + } + + /** + * Set csrf verifier class + * + * @param BaseCsrfVerifier $csrfVerifier + * @return static + */ + public function setCsrfVerifier(BaseCsrfVerifier $csrfVerifier) + { + $this->csrfVerifier = $csrfVerifier; + + return $this; + } + + /** + * Get loaded route + * @return ILoadableRoute|null + */ + public function getLoadedRoute() + { + return $this->loadedRoute; + } } \ No newline at end of file diff --git a/src/Pecee/SimpleRouter/SimpleRouter.php b/src/Pecee/SimpleRouter/SimpleRouter.php index cb9503e..5c1722d 100644 --- a/src/Pecee/SimpleRouter/SimpleRouter.php +++ b/src/Pecee/SimpleRouter/SimpleRouter.php @@ -21,354 +21,354 @@ use Pecee\SimpleRouter\Route\RouteUrl; class SimpleRouter { - /** - * Default namespace added to all routes - * @var string - */ - protected static $defaultNamespace; + /** + * Default namespace added to all routes + * @var string + */ + protected static $defaultNamespace; - /** - * The response object - * @var Response - */ - protected static $response; + /** + * The response object + * @var Response + */ + protected static $response; - /** - * Start/route request - * - * @throws HttpException - * @throws NotFoundHttpException - */ - public static function start() - { - static::router()->routeRequest(); - } + /** + * Start/route request + * + * @throws HttpException + * @throws NotFoundHttpException + */ + public static function start() + { + static::router()->routeRequest(); + } - /** - * Set default namespace which will be prepended to all routes. - * - * @param string $defaultNamespace - */ - public static function setDefaultNamespace($defaultNamespace) - { - static::$defaultNamespace = $defaultNamespace; - } + /** + * Set default namespace which will be prepended to all routes. + * + * @param string $defaultNamespace + */ + public static function setDefaultNamespace($defaultNamespace) + { + static::$defaultNamespace = $defaultNamespace; + } - /** - * Base CSRF verifier - * - * @param BaseCsrfVerifier $baseCsrfVerifier - */ - public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) - { - static::router()->setCsrfVerifier($baseCsrfVerifier); - } + /** + * Base CSRF verifier + * + * @param BaseCsrfVerifier $baseCsrfVerifier + */ + public static function csrfVerifier(BaseCsrfVerifier $baseCsrfVerifier) + { + static::router()->setCsrfVerifier($baseCsrfVerifier); + } - /** - * Boot managers allows you to alter the routes before the routing occurs. - * Perfect if you want to load pretty-urls from a file or database. - * - * @param IRouterBootManager $bootManager - */ - public static function addBootManager(IRouterBootManager $bootManager) - { - static::router()->addBootManager($bootManager); - } + /** + * Boot managers allows you to alter the routes before the routing occurs. + * Perfect if you want to load pretty-urls from a file or database. + * + * @param IRouterBootManager $bootManager + */ + public static function addBootManager(IRouterBootManager $bootManager) + { + static::router()->addBootManager($bootManager); + } - /** - * Route the given url to your callback on GET request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function get($url, $callback, array $settings = null) - { - return static::match(['get'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on GET request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function get($url, $callback, array $settings = null) + { + return static::match(['get'], $url, $callback, $settings); + } - /** - * Route the given url to your callback on POST request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function post($url, $callback, array $settings = null) - { - return static::match(['post'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on POST request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function post($url, $callback, array $settings = null) + { + return static::match(['post'], $url, $callback, $settings); + } - /** - * Route the given url to your callback on PUT request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function put($url, $callback, array $settings = null) - { - return static::match(['put'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on PUT request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function put($url, $callback, array $settings = null) + { + return static::match(['put'], $url, $callback, $settings); + } - /** - * Route the given url to your callback on PATCH request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function patch($url, $callback, array $settings = null) - { - return static::match(['patch'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on PATCH request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function patch($url, $callback, array $settings = null) + { + return static::match(['patch'], $url, $callback, $settings); + } - /** - * Route the given url to your callback on OPTIONS request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function options($url, $callback, array $settings = null) - { - return static::match(['options'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on OPTIONS request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function options($url, $callback, array $settings = null) + { + return static::match(['options'], $url, $callback, $settings); + } - /** - * Route the given url to your callback on DELETE request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function delete($url, $callback, array $settings = null) - { - return static::match(['delete'], $url, $callback, $settings); - } + /** + * Route the given url to your callback on DELETE request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function delete($url, $callback, array $settings = null) + { + return static::match(['delete'], $url, $callback, $settings); + } - /** - * Groups allows for encapsulating routes with special settings. - * - * @param array $settings - * @param \Closure $callback - * @throws \InvalidArgumentException - * @return RouteGroup - */ - public static function group(array $settings = [], \Closure $callback) - { - $group = new RouteGroup(); - $group->setCallback($callback); - $group->setSettings($settings); + /** + * Groups allows for encapsulating routes with special settings. + * + * @param array $settings + * @param \Closure $callback + * @throws \InvalidArgumentException + * @return RouteGroup + */ + public static function group(array $settings = [], \Closure $callback) + { + $group = new RouteGroup(); + $group->setCallback($callback); + $group->setSettings($settings); - if (is_callable($callback) === false) { - throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); - } + if (is_callable($callback) === false) { + throw new \InvalidArgumentException('Invalid callback provided. Only functions or methods supported'); + } - static::router()->addRoute($group); + static::router()->addRoute($group); - return $group; - } + return $group; + } - /** - * Alias for the form method - * - * @param string $url - * @param callable $callback - * @param array|null $settings - * @see SimpleRouter::form - * @return RouteUrl - */ - public static function basic($url, $callback, array $settings = null) - { - return static::match(['get', 'post'], $url, $callback, $settings); - } + /** + * Alias for the form method + * + * @param string $url + * @param callable $callback + * @param array|null $settings + * @see SimpleRouter::form + * @return RouteUrl + */ + public static function basic($url, $callback, array $settings = null) + { + return static::match(['get', 'post'], $url, $callback, $settings); + } - /** - * This type will route the given url to your callback on the provided request methods. - * Route the given url to your callback on POST and GET request method. - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @see SimpleRouter::form - * @return RouteUrl - */ - public static function form($url, $callback, array $settings = null) - { - return static::match(['get', 'post'], $url, $callback, $settings); - } + /** + * This type will route the given url to your callback on the provided request methods. + * Route the given url to your callback on POST and GET request method. + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @see SimpleRouter::form + * @return RouteUrl + */ + public static function form($url, $callback, array $settings = null) + { + return static::match(['get', 'post'], $url, $callback, $settings); + } - /** - * This type will route the given url to your callback on the provided request methods. - * - * @param array $requestMethods - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function match(array $requestMethods, $url, $callback, array $settings = null) - { - $route = new RouteUrl($url, $callback); - $route->setRequestMethods($requestMethods); - $route = static::addDefaultNamespace($route); + /** + * This type will route the given url to your callback on the provided request methods. + * + * @param array $requestMethods + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function match(array $requestMethods, $url, $callback, array $settings = null) + { + $route = new RouteUrl($url, $callback); + $route->setRequestMethods($requestMethods); + $route = static::addDefaultNamespace($route); - if ($settings !== null) { - $route->setSettings($settings); - } + if ($settings !== null) { + $route->setSettings($settings); + } - static::router()->addRoute($route); + static::router()->addRoute($route); - return $route; - } + return $route; + } - /** - * This type will route the given url to your callback and allow any type of request method - * - * @param string $url - * @param string|\Closure $callback - * @param array|null $settings - * @return RouteUrl - */ - public static function all($url, $callback, array $settings = null) - { - $route = new RouteUrl($url, $callback); - $route = static::addDefaultNamespace($route); + /** + * This type will route the given url to your callback and allow any type of request method + * + * @param string $url + * @param string|\Closure $callback + * @param array|null $settings + * @return RouteUrl + */ + public static function all($url, $callback, array $settings = null) + { + $route = new RouteUrl($url, $callback); + $route = static::addDefaultNamespace($route); - if ($settings !== null) { - $route->setSettings($settings); - } + if ($settings !== null) { + $route->setSettings($settings); + } - static::router()->addRoute($route); + static::router()->addRoute($route); - return $route; - } + return $route; + } - /** - * This route will route request from the given url to the controller. - * - * @param string $url - * @param string $controller - * @param array|null $settings - * @return RouteController - */ - public static function controller($url, $controller, array $settings = null) - { - $route = new RouteController($url, $controller); - $route = static::addDefaultNamespace($route); + /** + * This route will route request from the given url to the controller. + * + * @param string $url + * @param string $controller + * @param array|null $settings + * @return RouteController + */ + public static function controller($url, $controller, array $settings = null) + { + $route = new RouteController($url, $controller); + $route = static::addDefaultNamespace($route); - if ($settings !== null) { - $route->setSettings($settings); - } + if ($settings !== null) { + $route->setSettings($settings); + } - static::router()->addRoute($route); + static::router()->addRoute($route); - return $route; - } + return $route; + } - /** - * This type will route all REST-supported requests to different methods in the provided controller. - * - * @param string $url - * @param string $controller - * @param array|null $settings - * @return RouteResource - */ - public static function resource($url, $controller, array $settings = null) - { - $route = new RouteResource($url, $controller); + /** + * This type will route all REST-supported requests to different methods in the provided controller. + * + * @param string $url + * @param string $controller + * @param array|null $settings + * @return RouteResource + */ + public static function resource($url, $controller, array $settings = null) + { + $route = new RouteResource($url, $controller); - if ($settings !== null) { - $route->setSettings($settings); - } + if ($settings !== null) { + $route->setSettings($settings); + } - static::router()->addRoute($route); + static::router()->addRoute($route); - return $route; - } + return $route; + } - /** - * Get url for a route by using either name/alias, class or method name. - * - * The name parameter supports the following values: - * - Route name - * - Controller/resource name (with or without method) - * - Controller class name - * - * When searching for controller/resource by name, you can use this syntax "route.name@method". - * You can also use the same syntax when searching for a specific controller-class "MyController@home". - * If no arguments is specified, it will return the url for the current loaded route. - * - * @param string|null $name - * @param string|array|null $parameters - * @param array|null $getParams - * @return string - */ - public static function getUrl($name = null, $parameters = null, $getParams = null) - { - return static::router()->getUrl($name, $parameters, $getParams); - } + /** + * Get url for a route by using either name/alias, class or method name. + * + * The name parameter supports the following values: + * - Route name + * - Controller/resource name (with or without method) + * - Controller class name + * + * When searching for controller/resource by name, you can use this syntax "route.name@method". + * You can also use the same syntax when searching for a specific controller-class "MyController@home". + * If no arguments is specified, it will return the url for the current loaded route. + * + * @param string|null $name + * @param string|array|null $parameters + * @param array|null $getParams + * @return string + */ + public static function getUrl($name = null, $parameters = null, $getParams = null) + { + return static::router()->getUrl($name, $parameters, $getParams); + } - /** - * Get the request - * - * @return \Pecee\Http\Request - */ - public static function request() - { - return static::router()->getRequest(); - } + /** + * Get the request + * + * @return \Pecee\Http\Request + */ + public static function request() + { + return static::router()->getRequest(); + } - /** - * Get the response object - * - * @return Response - */ - public static function response() - { - if (static::$response === null) { - static::$response = new Response(static::request()); - } + /** + * Get the response object + * + * @return Response + */ + public static function response() + { + if (static::$response === null) { + static::$response = new Response(static::request()); + } - return static::$response; - } + return static::$response; + } - /** - * Returns the router instance - * - * @return Router - */ - public static function router() - { - return Router::getInstance(); - } + /** + * Returns the router instance + * + * @return Router + */ + public static function router() + { + return Router::getInstance(); + } - /** - * Prepends the default namespace to all new routes added. - * - * @param IRoute $route - * @return IRoute - */ - protected static function addDefaultNamespace(IRoute $route) - { - if (static::$defaultNamespace !== null) { - $namespace = static::$defaultNamespace; + /** + * Prepends the default namespace to all new routes added. + * + * @param IRoute $route + * @return IRoute + */ + protected static function addDefaultNamespace(IRoute $route) + { + if (static::$defaultNamespace !== null) { + $namespace = static::$defaultNamespace; - if ($route->getNamespace() !== null) { - $namespace .= '\\' . $route->getNamespace(); - } + if ($route->getNamespace() !== null) { + $namespace .= '\\' . $route->getNamespace(); + } - $route->setDefaultNamespace($namespace); - } + $route->setDefaultNamespace($namespace); + } - return $route; - } + return $route; + } } \ No newline at end of file