Compare commits

...

14 Commits

Author SHA1 Message Date
Simon Sessingø c5c63671ef Merge pull request #383 from skipperbent/v3-development
Development
2018-03-03 23:44:20 +01:00
Simon Sessingo d279d5598d Development
- Fixed issue with subdomains on groups.
- Fixed issue with loadble routes sometimes mistakenly inheriting wrong group.
- Routes will now check if group matches before matching any custom regex.
- Added setValue method to IInputItem class to streamline the InputFile and InputItem classes.
- Other minor optimisations.
- Documentation: fixed broken links and cleaned it up.
2018-03-03 23:37:14 +01:00
Simon Sessingø 6e247f811f Merge pull request #381 from skipperbent/v3-development
Throw correct exception-types.
2018-02-27 09:04:57 +01:00
Simon Sessingo be39010be3 Throw correct exception-types. 2018-02-27 08:58:57 +01:00
Simon Sessingø 8111de48fd Merge pull request #378 from skipperbent/v3-development
Fixed issue with PDO exception not returning correct type for error-code.
2018-02-27 08:36:43 +01:00
Simon Sessingo 79c82c90cc Fixed issue with PDO exception not returning correct type for error-code. 2018-02-27 08:20:25 +01:00
Simon Sessingø 0dbc4e6ba2 Merge pull request #376 from skipperbent/v3-development
Optimisations
2018-02-27 00:20:12 +01:00
Simon Sessingo 6d7d07669b Optimisations 2018-02-27 00:19:44 +01:00
Simon Sessingø a4dfa59a66 Merge pull request #374 from skipperbent/v3-development
Stop router from processing routes if no valid route is found.
2018-02-27 00:14:24 +01:00
Simon Sessingo 98bf95bfc9 Added back getPath. 2018-02-27 00:14:01 +01:00
Simon Sessingo b051bcf02b Stop router from processing routes if no valid route is found. 2018-02-27 00:12:45 +01:00
Simon Sessingo b8d5106f4e Removed getPath from url. 2018-02-27 00:00:54 +01:00
Simon Sessingø 2c9d996437 Merge pull request #372 from skipperbent/v3-development
Fixed setUrl issue.
2018-02-26 23:48:45 +01:00
Simon Sessingo cfc9ac138a Fixed setUrl issue. 2018-02-26 23:48:09 +01:00
15 changed files with 136 additions and 97 deletions
+42 -40
View File
@@ -1,45 +1,18 @@
# Simple PHP router
Simple, fast and yet powerful PHP router that is easy to get integrated and in any project. Heavily inspired by the way Laravel handles routing, with both simplicity and expandability in mind.
**Note: this documentation is currently work-in-progress. Feel free to contribute.**
### Notes
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
### Feedback and development
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.
###### Issues guidelines
- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.
- We love to hear out any ideas or feedback to the library.
[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)
###### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
**Please note that this documentation is currently work-in-progress. Feel free to contribute.**
---
## Table of Contents
- [Getting started](#getting-started)
- [Requirements](#requirements)
- [Notes](#notes-1)
- [Requirements](#requirements)
- [Feedback and development](#feedback-and-development)
- [Issues guidelines](#issues-guidelines)
- [Contribution development guidelines](#contribution-development-guidelines)
- [Features](#features)
- [Installation](#installation)
- [Setting up Apache](#setting-up-apache)
@@ -47,7 +20,6 @@ For example when pushing changes to version 3, the pull request should use the `
- [Setting up IIS](#setting-up-iis)
- [Configuration](#configuration)
- [Helper functions](#helper-functions)
- [Routes](#routes)
- [Basic routing](#basic-routing)
- [Available methods](#available-methods)
@@ -99,8 +71,7 @@ For example when pushing changes to version 3, the pull request should use the `
- [Advanced](#advanced)
- [Url rewriting](#url-rewriting)
- [Rewrite using callback](#rewrite-using-callback)
- [Rewrite using url](#rewrite-using-url)
- [Changing current route](#changing-current-route)
- [Bootmanager: loading routes dynamically](#bootmanager-loading-routes-dynamically)
- [Adding routes manually](#adding-routes-manually)
- [Parameters](#parameters)
@@ -119,12 +90,10 @@ Add the latest version of Simple PHP Router running this command.
composer require pecee/simple-router
```
## Requirements
- PHP 5.5 or greater
## Notes
The goal of this project is to create a router that is more or less 100% compatible with the Laravel documentation, while remaining as simple as possible, and as easy to integrate and change without compromising either speed or complexity. Being lightweight is the #1 priority.
We've included a simple demo project for the router which can be found in the `demo-project` folder. This project should give you a basic understanding of how to setup and use simple-php-router project.
Please note that the demo-project only covers how to integrate the `simple-php-router` in a project without an existing framework. If you are using a framework in your project, the implementation might vary.
@@ -143,6 +112,36 @@ You can find the demo-project here: [https://github.com/skipperbent/simple-route
- How to get ExceptionHandlers, Middlewares and Controllers working.
- How to setup your webservers.
## Requirements
- PHP 5.5 or greater
### Feedback and development
If you are missing a feature, experience problems or have ideas or feedback that you want us to hear, please feel free to create an issue.
###### Issues guidelines
- Please be as detailed as possible in the description when creating a new issue. This will help others to more easily understand- and solve your issue.
For example: if you are experiencing issues, you should provide the necessary steps to reproduce the error within your description.
- We love to hear out any ideas or feedback to the library.
[Create a new issue here](https://github.com/skipperbent/simple-php-router/issues/new)
###### Contribution development guidelines
- Please try to follow the PSR-2 codestyle guidelines.
- Please create your pull requests to the development base that matches the version number you want to change.
For example when pushing changes to version 3, the pull request should use the `v3-development` base/branch.
- Create detailed descriptions for your commits, as these will be used in the changelog for new releases.
- When changing existing functionality, please ensure that the unit-tests working.
- When adding new stuff, please remember to add new unit-tests for the functionality.
## Features
- Basic routing (`GET`, `POST`, `PUT`, `PATCH`, `UPDATE`, `DELETE`) with support for custom multiple verbs.
@@ -598,7 +597,7 @@ SimpleRouter::group(['namespace' => 'Admin'], function () {
});
```
### Sub domain-routing
### Subdomain-routing
Route groups may also be used to handle sub-domain routing. Sub-domains may be assigned route parameters just like route urls, allowing you to capture a portion of the sub-domain for usage in your route or controller. The sub-domain may be specified using the `domain` key on the group attribute array:
@@ -1135,6 +1134,9 @@ $siteId = input('site_id', 2, ['post', 'get']);
# Advanced
## Url rewriting
### Changing current route
Sometimes it can be useful to manipulate the route about to be loaded.
simple-php-router allows you to easily manipulate and change the routes which are about to be rendered.
All information about the current route is stored in the `\Pecee\SimpleRouter\Router` instance's `loadedRoute` property.
+3
View File
@@ -1,4 +1,5 @@
<?php
namespace Pecee\Http\Input;
interface IInputItem
@@ -14,6 +15,8 @@ interface IInputItem
public function getValue();
public function setValue($value);
public function __toString();
}
+11
View File
@@ -266,6 +266,17 @@ class InputFile implements IInputItem
return $this->getFilename();
}
/**
* @param string $value
* @return static
*/
public function setValue($value)
{
$this->filename = $value;
return $this;
}
public function toArray()
{
return [
+1
View File
@@ -1,4 +1,5 @@
<?php
namespace Pecee\Http\Input;
class InputItem implements IInputItem
+1 -1
View File
@@ -217,7 +217,7 @@ class Request
*/
public function setUrl($url)
{
$this->url = is_string($url) ? new Url($url) : $url;
$this->url = ($url instanceof Url) ? $url : new Url($url);
}
/**
@@ -36,7 +36,7 @@ class CookieTokenProvider implements ITokenProvider
try {
return bin2hex(random_bytes(32));
} catch(\Exception $e) {
throw new SecurityException($e->getMessage(), $e->getCode(), $e->getPrevious());
throw new SecurityException($e->getMessage(), (int)$e->getCode(), $e->getPrevious());
}
}
@@ -50,7 +50,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
return null;
}
return (preg_match($this->regex, $request->getHost() . $url) > 0);
return ((bool)preg_match($this->regex, $request->getHost() . $url) !== false);
}
/**
@@ -67,7 +67,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
$regex = sprintf(static::PARAMETERS_REGEX_FORMAT, $this->paramModifiers[0], $this->paramOptionalSymbol, $this->paramModifiers[1]);
if (preg_match_all('/' . $regex . '/u', $this->url, $matches) > 0) {
if ((bool)preg_match_all('/' . $regex . '/u', $this->url, $matches) !== false) {
$this->parameters = array_fill_keys($matches[1], null);
}
}
@@ -111,11 +111,8 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
/* Replace any {parameter} in the url with the correct value */
$params = $this->getParameters();
$max = count($params) - 1;
$keys = array_keys($params);
for ($i = $max; $i >= 0; $i--) {
$param = $keys[$i];
foreach (array_keys($params) as $param) {
if ($parameters === '' || (is_array($parameters) === true && count($parameters) === 0)) {
$value = '';
@@ -137,8 +134,7 @@ abstract class LoadableRoute extends Route implements ILoadableRoute
}
}
$url = '/' . ltrim($url, '/');
$url .= implode('/', $unknownParams);
$url = '/' . ltrim($url, '/') . implode('/', $unknownParams);
return rtrim($url, '/') . '/';
}
+7 -5
View File
@@ -128,7 +128,9 @@ abstract class Route implements IRoute
// Ensures that hostnames/domains will work with parameters
$url = '/' . ltrim($url, '/');
if (preg_match_all('/' . $regex . '/u', $route, $parameters) !== 0) {
if ((bool)preg_match_all('/' . $regex . '/u', $route, $parameters) === false) {
$urlRegex = preg_quote($route, '/');
} else {
$urlParts = preg_split('/((\-?\/?)\{[^}]+\})/', $route);
@@ -154,7 +156,6 @@ abstract class Route implements IRoute
}
$regex = sprintf('(?:\/|\-)%1$s(?P<%2$s>%3$s)%1$s', $parameters[2][$key], $name, $regex);
}
$urlParts[$key] = preg_quote($t, '/') . $regex;
@@ -162,11 +163,9 @@ abstract class Route implements IRoute
$urlRegex = implode('', $urlParts);
} else {
$urlRegex = preg_quote($route, '/');
}
if (preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === 0) {
if ((bool)preg_match(sprintf($this->urlRegex, $urlRegex), $url, $matches) === false) {
return null;
}
@@ -250,6 +249,9 @@ abstract class Route implements IRoute
{
$this->group = $group;
/* Add/merge parent settings with child */
$this->setSettings($group->toArray(), true);
return $this;
}
@@ -88,6 +88,10 @@ class RouteController extends LoadableRoute implements IControllerRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -48,6 +48,10 @@ class RouteGroup extends Route implements IGroupRoute
*/
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Skip if prefix doesn't match */
if ($this->prefix !== null && stripos($url, $this->prefix) === false) {
return false;
@@ -17,6 +17,10 @@ class RoutePartialGroup extends RouteGroup implements IPartialGroupRoute
*/
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
if ($this->prefix !== null) {
/* Parse parameters from current route */
$parameters = $this->parseParameters($this->prefix, $url);
@@ -79,6 +79,10 @@ class RouteResource extends LoadableRoute implements IControllerRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
@@ -14,6 +14,10 @@ class RouteUrl extends LoadableRoute
public function matchRoute($url, Request $request)
{
if($this->getGroup() !== null && $this->getGroup()->matchRoute($url, $request) === false) {
return false;
}
/* Match global regular-expression for route */
$regexMatch = $this->matchRegex($request, $url);
+45 -42
View File
@@ -97,49 +97,64 @@ class Router
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 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;
}
$this->routes[] = $route;
return $route;
}
/**
* Render and process any new routes added.
*
* @param IRoute $route
* @throws NotFoundHttpException
*/
protected function renderAndProcess(IRoute $route) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
if (count($this->routeStack) !== 0) {
/* Pop and grab the routes added when executing group callback earlier */
$stack = $this->routeStack;
$this->routeStack = [];
/* Route any routes added to the stack */
$this->processRoutes($stack, $route);
}
}
/**
* Process added routes.
*
* @param array $routes
* @param IGroupRoute|null $group
* @param IRoute|null $parent
* @throws NotFoundHttpException
*/
protected function processRoutes(array $routes, IGroupRoute $group = null, IRoute $parent = null)
protected function processRoutes(array $routes, IGroupRoute $group = null)
{
// Loop through each route-request
$exceptionHandlers = [];
// Stop processing routes if no valid route is found.
if($this->request->getRewriteRoute() === null && $this->request->getUrl() === null) {
return;
}
$url = ($this->request->getRewriteUrl() !== null) ? $this->request->getRewriteUrl() : $this->request->getUrl()->getPath();
/* @var $route IRoute */
foreach ($routes as $route) {
if ($parent !== null) {
/* Add the parent route */
$route->setParent($parent);
/* Add/merge parent settings with child */
$route->setSettings($parent->toArray(), true);
}
if ($group !== null) {
/* Add the parent group */
$route->setGroup($group);
}
@@ -147,8 +162,6 @@ class Router
/* @var $route IGroupRoute */
if ($route instanceof IGroupRoute) {
$group = $route;
if ($route->matchRoute($url, $this->request) === true) {
/* Add exception handlers */
@@ -158,36 +171,24 @@ class Router
}
/* Only render partial group if it matches */
if ($route instanceof IPartialGroupRoute) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
if ($route instanceof IPartialGroupRoute === true) {
$this->renderAndProcess($route);
}
}
if (($route instanceof IPartialGroupRoute) === false) {
$this->processingRoute = true;
$route->renderRoute($this->request);
$this->processingRoute = false;
if ($route instanceof IPartialGroupRoute === false) {
$this->renderAndProcess($route);
}
continue;
}
if ($route instanceof ILoadableRoute) {
if ($route instanceof ILoadableRoute === true) {
/* 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) {
/* Pop and grab 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);
}
}
$this->exceptionHandlers = array_merge($exceptionHandlers, $this->exceptionHandlers);
@@ -216,6 +217,7 @@ class Router
* @param bool $rewrite
* @return string|mixed
* @throws HttpException
* @throws \Exception
*/
public function routeRequest($rewrite = false)
{
@@ -329,6 +331,7 @@ class Router
/**
* @param \Exception $e
* @throws HttpException
* @throws \Exception
* @return string
*/
protected function handleException(\Exception $e)
@@ -360,7 +363,7 @@ class Router
}
}
throw new HttpException($e->getMessage(), $e->getCode(), $e->getPrevious());
throw $e;
}
public function arrayToParams(array $getParams = [], $includeEmpty = true)
@@ -599,4 +602,4 @@ class Router
return $this;
}
}
}
+1
View File
@@ -45,6 +45,7 @@ class SimpleRouter
/**
* @throws \Pecee\Http\Exceptions\MalformedUrlException
* @throws HttpException
* @throws \Exception
*/
public static function start()
{