Skip to content
This repository has been archived by the owner on Jun 9, 2022. It is now read-only.

Commit

Permalink
Added a whole load of PHPDOC documentation to main classes
Browse files Browse the repository at this point in the history
  • Loading branch information
Nik Barham committed May 18, 2017
1 parent 68bb6d9 commit d6917ac
Show file tree
Hide file tree
Showing 2 changed files with 120 additions and 15 deletions.
33 changes: 25 additions & 8 deletions src/HandlerContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,23 @@

class HandlerContainer implements Delegate
{
/** @var Middleware|null[] */
/** @var Middleware|null[] Stack of middleware to call for this route */
public $middlewareStack = [null];

/** @var string */
/** @var string The Controller class for this route */
public $controllerClass;

/** @var string */
/** @var string The method to call on the Controller for this route*/
public $controllerMethod;

/** @var Circuit\Router */
/** @var Circuit\Router The router responsible for this route - this gets assigned when a route is executed */
protected $router;

/**
* Store a handler against a list of middleware
*
* @param mixed $handler
* @param Middleware[] $middleware
* @param Middleware[] $stack
*/
public function __construct($handler, array $stack = [])
{
Expand All @@ -41,15 +41,23 @@ public function __construct($handler, array $stack = [])
/**
* Add middleware to an existing handler stack
*
* @param Middleware[] $middleware
* @param Middleware[] $stack
* @return self
*/
public function addMiddleware(array $stack)
{
$this->middlewareStack = array_merge($this->middlewareStack, $stack);
return $this;
}

/**
* Set the router about to call this handler
* Start processing this route, by calling middleware in order, and then calling the specified Controller
* This call stores various information (args, controller info) on the Request
*
* @param Router $router The router calling this handler
* @param Request $request The request for the current route
* @param array $args The matched arguments from the route
* @return Response
*/
public function startProcessing(Router $router, Request $request, $args) : Response
{
Expand All @@ -61,6 +69,12 @@ public function startProcessing(Router $router, Request $request, $args) : Respo
return $this->process($request);
}

/**
* Call middleware in order, and then call the specified Controller, using a modified PSR15 Middleware pattern
*
* @param Request $request The request for the current route
* @return Response
*/
public function process(Request $request) : Response
{
$next = next($this->middlewareStack);
Expand All @@ -85,7 +99,10 @@ public function process(Request $request) : Response
);
}
}


/**
* Remove $this->router when serialising this object
*/
public function __sleep()
{
return ['controllerClass', 'middlewareStack', 'controllerMethod'];
Expand Down
102 changes: 95 additions & 7 deletions src/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,39 @@

class Router implements Delegate
{
const CACHE_KEY = 'routes_v1';
const CACHE_KEY = 'routes_v2';

protected $options = [];
protected $routeCollection;
protected $dispatcher;

/** @var Psr\SimpleCache\CacheInterface|Psr\Cache\CacheItemPoolInterface
PSR6/16 compatible cache item
*/
protected $cache;

/** @var bool Did we pull results from cache i.e. do we need to call the RouteCollector callback */
protected $cached = false;

/** @var ExceptionHandler[] */
/** @var ExceptionHandler[] List of exception handlers for particular HTTP codes */
public $exceptionHandlers = [];

/** @var mixed[] */
/** @var mixed[] List of arguments passed to Controller constructor */
public $controllerArguments = [];

/** @var Middleware[] */
/** @var Middleware[] List of registered middlewares on this router */
protected $middleware = [];

/** @var mixed[] */
/** @var mixed[] List of middlewares to run before matching routes */
protected $preRouteMiddlewareStack = [null];

/**
* Create a new Router
* See https://github.com/nikic/FastRoute for more details
*
* @param array $options Option overrides
* @param Psr\SimpleCache\CacheInterface|Psr\Cache\CacheItemPoolInterface $cache A PSR-6 or PSR-16 compatible Cache object
*/
public function __construct(array $options = [], $cache = null)
{
$this->options = $options + [
Expand Down Expand Up @@ -68,6 +82,13 @@ public function __construct(array $options = [], $cache = null)
}
}

/**
* Define routes using a routerCollector
* See https://github.com/nikic/FastRoute for more details
*
* @param callable $routeDefinitionCallback Callback that will define the routes
* @return self
*/
public function defineRoutes(callable $routeDefinitionCallback)
{
if (!$this->cached) {
Expand All @@ -87,8 +108,15 @@ public function defineRoutes(callable $routeDefinitionCallback)
}

$this->dispatcher = new $this->options['dispatcher']($this->routeCollection->getData());
return $this;
}

/**
* Internal function to retrieve a cached value from PSR-6/16 cache object
*
* @param string $key Cache key to retrieve from cache
* @return self
*/
protected function getCachedValue($key)
{
if (!$this->cache) {
Expand All @@ -108,13 +136,25 @@ protected function getCachedValue($key)
}
}

/**
* Execute a route
*
* @param Request $request Request object for current process
*/
public function run(Request $request)
{
$response = $this->process($request);
$response->prepare($request);
$response->send();
}

/**
* Process a route
* Will call pre-route middleware, then match route and execute that route (more middleware + controller)
*
* @param Request $request Request object for current process
* @return Response Response to http request ready for dispatch
*/
public function process(Request $request) : Response
{
try {
Expand Down Expand Up @@ -150,7 +190,17 @@ public function process(Request $request) : Response
}
}

public function handleException(\Throwable $e, Request $request, $currentContext = null) : Response
/**
* Handle an exception during processing of route.
* Will try and determine context (Controller, Middleware, Router etc) before calling ExceptionHandler
* based on HTTP code of Exception (default 500).
*
* @param Throwable $e The Exception / Error thrown.
* @param Request $request The request that caused the exception.
* @param mixed $currentContext Some data to try and guess the context from.
* @return Response The response to the exception (e.g. error page)
*/
protected function handleException(\Throwable $e, Request $request, $currentContext = null) : Response
{
// Figure out which Middleware/Controller we're in
if ($currentContext instanceof Middleware) {
Expand Down Expand Up @@ -185,31 +235,69 @@ public function handleException(\Throwable $e, Request $request, $currentContext
}
}

/**
* Set arguments that will be passed to the constructor for any controllers invoked
*
* @param mixed $args Array containing all passed variadic arguments
* @return self
*/
public function setControllerArguments(...$args)
{
$this->controllerArguments = $args;
return $this;
}

/**
* Register a middleware against a name.
* This allows middleware to be created on startup and then refered to in serialised/cached route table
*
* @param string $name Unique name for middleware instance
* @param Middleware $middleware Middleware object
* @return self
*/
public function registerMiddleware($name, Middleware $middleware)
{
$this->middleware[$name] = $middleware;
return $self;
}

/**
* Retrieve a middleware by name.
*
* @param string $name Name of middleware set by ->registerMiddleware($name)
* @throws UnexpectedValueException For unrecognised names
* @return Middleware The referenced middleware instance
*/
public function getMiddleware($name) : Middleware
{
if (!array_key_exists($name, $this->middleware)) {
throw new \Exception("No middleware registered under name '{$name}'");
throw new \UnexpectedValueException("No middleware registered under name '{$name}'");
}
return $this->middleware[$name];
}

/**
* Register an exception handler for a particular HTTP code.
*
* @param string $code HTTP code handler is responsible for
* @param ExceptionHandler $hander Handler
* @return self
*/
public function setExceptionHandler($code, ExceptionHandler $handler)
{
$this->exceptionHandlers[$code] = $handler;
return $this;
}

/**
* Add a middleware that will be run before routes are matched
*
* @param mixed $middleware Middleware object or named middleware (via ->registerMiddleware($name))
* @return self
*/
public function setPrerouteMiddleware($middleware)
{
$this->preRouteMiddlewareStack[] = $middleware;
return $this;
}
}

0 comments on commit d6917ac

Please sign in to comment.