Add RouteFactory
This commit is contained in:
parent
04561076d5
commit
3d68a0af86
|
|
@ -0,0 +1,56 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* pjdietz\WellRESTed\RouteCreator
|
||||
*
|
||||
* @author PJ Dietz <pj@pjdietz.com>
|
||||
* @copyright Copyright 2015 by PJ Dietz
|
||||
* @license MIT
|
||||
*/
|
||||
|
||||
namespace pjdietz\WellRESTed\Routes;
|
||||
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* Class for creating routes
|
||||
*/
|
||||
class RouteFactory
|
||||
{
|
||||
public function createRoute()
|
||||
{
|
||||
$args = func_get_args();
|
||||
$path = $args[0];
|
||||
|
||||
if ($path[0] === "/") {
|
||||
|
||||
// Possible static, prefix, or template
|
||||
|
||||
// PrefixRoutes end with *
|
||||
if (substr($path, -1) === "*") {
|
||||
// Remove the trailing *, since the PrefixRoute constructor doesn't expect it.
|
||||
$path = substr($path, 0, -1);
|
||||
$constructorArgs = $args;
|
||||
$constructorArgs[0] = $path;
|
||||
$reflector = new ReflectionClass("\\pjdietz\\WellRESTed\\Routes\\PrefixRoute");
|
||||
return $reflector->newInstanceArgs($constructorArgs);
|
||||
}
|
||||
|
||||
// TempalateRoutes contain {variable}
|
||||
if (preg_match(TemplateRoute::URI_TEMPLATE_EXPRESSION_RE, $path)) {
|
||||
$reflector = new ReflectionClass("\\pjdietz\\WellRESTed\\Routes\\TemplateRoute");
|
||||
return $reflector->newInstanceArgs($args);
|
||||
}
|
||||
|
||||
// StaticRoute
|
||||
$reflector = new ReflectionClass("\\pjdietz\\WellRESTed\\Routes\\StaticRoute");
|
||||
return $reflector->newInstanceArgs($args);
|
||||
|
||||
}
|
||||
|
||||
// Regex
|
||||
$reflector = new ReflectionClass("\\pjdietz\\WellRESTed\\Routes\\RegexRoute");
|
||||
return $reflector->newInstanceArgs($args);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
<?php
|
||||
|
||||
namespace pjdietz\WellRESTed\Test;
|
||||
|
||||
use pjdietz\WellRESTed\Routes\RouteFactory;
|
||||
use Prophecy\Argument;
|
||||
|
||||
/**
|
||||
* @covers pjdietz\WellRESTed\Routes\RouteFactory
|
||||
*/
|
||||
class RouteFactoryTest extends \PHPUnit_Framework_TestCase
|
||||
{
|
||||
/**
|
||||
* @dataProvider routeProvider
|
||||
*/
|
||||
public function testCreatesRouteOfCorrectType($path, $expectedType)
|
||||
{
|
||||
$factory = new RouteFactory();
|
||||
$route = $factory->createRoute($path, "\\MyHandler");
|
||||
$this->assertInstanceOf($expectedType, $route);
|
||||
}
|
||||
|
||||
public function routeProvider()
|
||||
{
|
||||
$static = "\\pjdietz\\WellRESTed\\Routes\\StaticRoute";
|
||||
$prefix = "\\pjdietz\\WellRESTed\\Routes\\PrefixRoute";
|
||||
$template = "\\pjdietz\\WellRESTed\\Routes\\TemplateRoute";
|
||||
$regex = "\\pjdietz\\WellRESTed\\Routes\\RegexRoute";
|
||||
|
||||
return [
|
||||
["/cats/", $static],
|
||||
["/cats/*", $prefix],
|
||||
["/cats/{catId}", $template],
|
||||
["~/cat/[0-9]+~", $regex]
|
||||
];
|
||||
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue