From bb01d98e11ee49d5a936b5b6960c06db57808c1e Mon Sep 17 00:00:00 2001 From: ncou Date: Mon, 1 Jul 2019 00:28:42 +0200 Subject: [PATCH] update --- src/Chiron/Provider/RouterServiceProvider.php | 4 + src/Chiron/Routing/Dispatcher.php | 11 +- src/Chiron/Routing/RouteCollector.php | 145 ++++++++++++++++++ .../Routing/RouteCollectorInterface.php | 39 +++++ src/Chiron/Routing/RouteGroup.php | 1 + src/Chiron/Routing/RouteUrlGenerator.php | 60 ++------ src/Chiron/Routing/Router.php | 143 +++++------------ src/Chiron/Routing/RouterInterface.php | 31 ++-- .../Traits/RouteCollectionInterface.php | 47 +++++- .../Routing/Traits/RouteCollectionTrait.php | 3 +- tests/Routing/ApplicationRouterTest.php | 33 ++-- tests/Routing/FastRouterTest.php | 16 +- tests/Routing/RouteCollectorTest.php | 92 +++++------ tests/Routing/RouteGroupTest.php | 22 +-- tests/Routing/RouterTest.php | 37 ++--- tests/Routing/Strategy/HtmlStrategyTest.php | 12 +- 16 files changed, 420 insertions(+), 276 deletions(-) create mode 100644 src/Chiron/Routing/RouteCollector.php create mode 100644 src/Chiron/Routing/RouteCollectorInterface.php diff --git a/src/Chiron/Provider/RouterServiceProvider.php b/src/Chiron/Provider/RouterServiceProvider.php index 20029eb..49ff394 100644 --- a/src/Chiron/Provider/RouterServiceProvider.php +++ b/src/Chiron/Provider/RouterServiceProvider.php @@ -21,6 +21,7 @@ use Chiron\Kernel; use Chiron\Routing\Resolver\ControllerResolver; use Chiron\Routing\Router; +use Chiron\Routing\RouteCollector; use Chiron\Routing\RouterInterface; use Chiron\Routing\Strategy\HtmlStrategy; use Psr\Container\ContainerInterface; @@ -62,6 +63,9 @@ public function register(Container $container): void // TODO : aller chercher la controllerResolver directement dans le container plutot que de faire un new !!!! ca permettra de faire un override de cette classe si l'utilisateur souhaite redéfinir le resolver. $router->setStrategy(new HtmlStrategy($container->get('kernel'))); + //$collector = new RouteCollector(); + //$router->setRouteCollector($collector); + return $router; }); diff --git a/src/Chiron/Routing/Dispatcher.php b/src/Chiron/Routing/Dispatcher.php index 0a55654..dd94226 100644 --- a/src/Chiron/Routing/Dispatcher.php +++ b/src/Chiron/Routing/Dispatcher.php @@ -9,14 +9,15 @@ class Dispatcher extends GroupCountBasedDispatcher { - private $routes; + //private $routes; // mixed[] $data + /* public function __construct(array $routes, array $data) { $this->routes = $routes; parent::__construct($data); - } + }*/ /** * Dispatch the current route. @@ -60,8 +61,10 @@ private function marshalFailedRoute(array $result): RouteResult // TODO : attention le paramétre $method n'est pas utilisé !!!! => https://github.com/zendframework/zend-expressive-fastroute/blob/master/src/FastRouteRouter.php#L397 private function marshalMatchedRoute(array $result): RouteResult { - $identifier = $result[1]; - $route = $this->routes[$identifier]; + //$identifier = $result[1]; + //$route = $this->routes[$identifier]; + + $route = $result[1]; $params = $result[2]; return RouteResult::fromRoute($route, $params); diff --git a/src/Chiron/Routing/RouteCollector.php b/src/Chiron/Routing/RouteCollector.php new file mode 100644 index 0000000..34a3378 --- /dev/null +++ b/src/Chiron/Routing/RouteCollector.php @@ -0,0 +1,145 @@ +routes[uniqid('UID_', true)] = $route; + $this->routes[] = $route; + + return $route; + } + + /** + * Add a group of routes to the collection. + * + * @param string $prefix + * @param callable $group + * + * @return \Chiron\Routing\RouteGroup + */ + // TODO : vérifier si on pas plutot utiliser un Closure au lieu d'un callable pour le typehint. + // TODO : il semble pôssible dans Slim de passer une string, ou un callable. Vérifier l'utilité de cette possibilité d'avoir un string !!!! + public function group(string $prefix, callable $callback): RouteGroup + { + $group = new RouteGroup($prefix, $callback, $this); + + $this->groups[] = $group; + + return $group; + } + + /** + * Process all groups. + */ + // A voir si cette méthode ne devrait pas être appellée directement dans la méthode ->group() pour préparer les routes dés qu'on ajoute un group !!!! + // https://github.com/slimphp/Slim/blob/4.x/Slim/Routing/RouteCollector.php#L255 + private function processGroups(): void + { + // TODO : vérifier si il ne faut pas faire un array_reverse lorsqu'on execute les groups. Surtout dans le cas ou on ajoute des middlewares au group et qui seront propagés à la route. + //https://github.com/slimphp/Slim/blob/4.x/Slim/Routing/Route.php#L350 + + // Call the $group by reference because in the case : group of group the size of the array is modified because a new group is added in the group() function. + foreach ($this->groups as $key => &$group) { + // TODO : déplacer le unset aprés la méthode invoke ou collectroute du group. Voir si c'est pas plus ^propre de remplacer le unset par un array_pop ou un array_shift !!!! + unset($this->groups[$key]); + // TODO : créer une méthode ->collectRoutes() dans la classe RouteGroup, au lieu d'utiliser le invoke() on utilisera cette méthode, c'est plus propre !!!! + $group(); + //array_pop($this->groups); + //array_shift($this->routeGroups); + } + } + + /** + * Get route objects. + * + * @return Route[] + */ + public function getRoutes(): array + { + //return array_values($this->toArray()); + //return iterator_to_array($this->getIterator()); + + + $this->processGroups(); + + return $this->routes; + } + + /** + * Get a named route. + * + * @param string $name Route name + * + * @throws \InvalidArgumentException If named route does not exist + * + * @return \Chiron\Routing\Route + */ + public function getNamedRoute(string $name): Route + { + foreach ($this->getRoutes() as $route) { + if ($route->getName() === $name) { + return $route; + } + } + + throw new InvalidArgumentException('Named route does not exist for name: ' . $name); + } + + /** + * Remove named route. + * + * @param string $name Route name + * + * @throws \InvalidArgumentException If named route does not exist + */ + public function removeNamedRoute(string $name): void + { + $route = $this->getNamedRoute($name); + // no exception, route exists, now remove by id + //unset($this->routes[$route->getIdentifier()]); + // no exception so far so the route exists we can remove the object safely. + unset($this->routes[array_search($route, $this->routes)]); + } + +} diff --git a/src/Chiron/Routing/RouteCollectorInterface.php b/src/Chiron/Routing/RouteCollectorInterface.php new file mode 100644 index 0000000..8b6dcac --- /dev/null +++ b/src/Chiron/Routing/RouteCollectorInterface.php @@ -0,0 +1,39 @@ +callback = $callback; diff --git a/src/Chiron/Routing/RouteUrlGenerator.php b/src/Chiron/Routing/RouteUrlGenerator.php index 466fd84..30291a5 100644 --- a/src/Chiron/Routing/RouteUrlGenerator.php +++ b/src/Chiron/Routing/RouteUrlGenerator.php @@ -12,17 +12,12 @@ class RouteUrlGenerator { - /** @var FastRoute\RouteParser\Std */ - private $parser; - - private $router; - /** * Characters that should not be URL encoded. * * @var array */ - private $dontEncode = [ + private static $dontEncode = [ '%2F' => '/', '%40' => '@', '%3A' => ':', @@ -39,42 +34,10 @@ class RouteUrlGenerator '%25' => '%', ]; - // TODO : lui passer plutot un routeCollector en paramétre !!!! - public function __construct(Router $router) - { - // build parent route collector - $this->parser = new Std(); - $this->router = $router; - } - - /** - * Build the path for a named route including the base path. - * - * @param string $routeName Route name - * @param array $substitutions Named argument replacement data - * @param array $queryParams Optional query string parameters - * - * @throws InvalidArgumentException If named route does not exist - * @throws InvalidArgumentException If required data not provided - * - * @return string - */ - //https://github.com/illuminate/routing/blob/master/RouteUrlGenerator.php#L77 - public function urlFor(string $routeName, array $substitutions = [], array $queryParams = []): string - { - $url = $this->relativeUrlFor($routeName, $substitutions, $queryParams); - - if ($basePath = $this->router->getBasePath()) { - $url = $basePath . $url; - } - - return $url; - } - /** * Build the path for a named route excluding the base path. * - * @param string $routeName Route name + * @param string $routePath Route path pattern * @param array $substitutions Named argument replacement data * @param array $queryParams Optional query string parameters * @@ -88,11 +51,12 @@ public function urlFor(string $routeName, array $substitutions = [], array $quer // TODO ; utiliser ce bout de code : https://github.com/slimphp/Slim/blob/4.x/Slim/Routing/RouteParser.php#L42 // TODO : améliorer le code avec cette partie là => https://github.com/illuminate/routing/blob/master/RouteUrlGenerator.php#L77 // https://github.com/zendframework/zend-expressive-fastroute/blob/master/src/FastRouteRouter.php#L239 - public function relativeUrlFor(string $routeName, array $substitutions = [], array $queryParams = []): string + //https://github.com/illuminate/routing/blob/master/RouteUrlGenerator.php#L77 + public static function generate(string $routePath, array $substitutions = [], array $queryParams = []): string { - $route = $this->router->getNamedRoute($routeName); - $pattern = $route->getPath(); - $routeDatas = $this->parser->parse($pattern); + $parser = new Std(); + $routeDatas = $parser->parse($routePath); + // $routeDatas is an array of all possible routes that can be made. There is // one routedata for each optional parameter plus one for no optional parameters. // @@ -150,11 +114,11 @@ public function relativeUrlFor(string $routeName, array $substitutions = [], arr if ($queryParams) { // TODO : améliorer le code avec ca : https://github.com/illuminate/routing/blob/master/RouteUrlGenerator.php#L255 et ca : https://github.com/illuminate/support/blob/master/Arr.php#L599 //$url .= '?' . http_build_query($queryParams); - $url = $this->addQueryString($url, $queryParams); + $url = self::addQueryString($url, $queryParams); } // We will encode the URI and prepare it for returning to the developer. - $url = strtr(rawurlencode($url), $this->dontEncode); + $url = strtr(rawurlencode($url), self::$dontEncode); return $url; } @@ -167,7 +131,7 @@ public function relativeUrlFor(string $routeName, array $substitutions = [], arr * * @return mixed|string */ - protected function addQueryString(string $url, array $parameters): string + private static function addQueryString(string $url, array $parameters): string { // If the URI has a fragment we will move it to the end of this URI since it will // need to come after any query string that may be added to the URL else it is @@ -175,7 +139,7 @@ protected function addQueryString(string $url, array $parameters): string if (! is_null($fragment = parse_url($url, PHP_URL_FRAGMENT))) { $url = preg_replace('/#.*/', '', $url); } - $url .= $this->getRouteQueryString($parameters); + $url .= self::getRouteQueryString($parameters); return is_null($fragment) ? $url : $url . "#{$fragment}"; } @@ -187,7 +151,7 @@ protected function addQueryString(string $url, array $parameters): string * * @return string */ - protected function getRouteQueryString(array $parameters): string + private static function getRouteQueryString(array $parameters): string { $query = http_build_query($parameters, '', '&', PHP_QUERY_RFC3986); diff --git a/src/Chiron/Routing/Router.php b/src/Chiron/Routing/Router.php index bd4b76e..f9c0a6a 100644 --- a/src/Chiron/Routing/Router.php +++ b/src/Chiron/Routing/Router.php @@ -41,10 +41,9 @@ * attaching via one of the exposed methods, and will raise an exception when a * collision occurs. */ -class Router implements RouterInterface, StrategyAwareInterface, RouteCollectionInterface, MiddlewareAwareInterface +class Router implements RouterInterface { use MiddlewareAwareTrait; - use RouteCollectionTrait; use StrategyAwareTrait; /** @var FastRoute\RouteParser */ @@ -53,15 +52,7 @@ class Router implements RouterInterface, StrategyAwareInterface, RouteCollection /** @var FastRoute\DataGenerator */ private $generator; - /** - * @var \Chiron\Routing\Route[] - */ - private $routes = []; - - /** - * @var \Chiron\Routing\RouteGroup[] - */ - private $groups = []; + private $routeCollector; /** * @var array @@ -115,12 +106,16 @@ class Router implements RouterInterface, StrategyAwareInterface, RouteCollection * @param \FastRoute\RouteParser $parser * @param \FastRoute\DataGenerator $generator */ + // TODO : créer un constructeur qui prendra en paramétre un routeCollector, ca évitera de faire un appel à setRouteCollector() !!!! + // TODO : virer le DataGenerator qui est en paramétre et faire un new directement dans le constructeur. public function __construct(DataGenerator $generator = null) { $this->parser = new RouteParser\Std(); // build parent route collector $this->generator = ($generator) ?? new DataGenerator\GroupCountBased(); + $this->routeCollector = new RouteCollector(); + // TODO utiliser ce bout de code et faire un tableau de pattern dans la classe de ce type ['slug' => 'xxxx', 'number' => 'yyyy'] /* array_walk($this->patternMatchers, function ($value, $key) { @@ -165,43 +160,17 @@ public function getBasePath(): string return $this->basePath; } - /** - * {@inheritdoc} - */ - public function map(string $path, $handler): Route + public function getRouteCollector(): RouteCollectorInterface { - // TODO : il faudrait peut etre remonter ce controle durectement dans l'objet Route() non ???? - if (! is_string($handler) && ! is_callable($handler)) { - throw new InvalidArgumentException('Route Handler should be a callable or a string (service name in the container or class name).'); - } - - // TODO : attention vérifier si cette modification du path avec un slash n'est pas en doublon avec celle qui est faite dans la classe Route !!!! - $path = sprintf('/%s', ltrim($path, '/')); - $route = new Route($path, $handler); - - $this->routes[uniqid('UID_', true)] = $route; - - return $route; + return $this->routeCollector; } - /** - * Add a group of routes to the collection. - * - * @param string $prefix - * @param callable $group - * - * @return \Chiron\Routing\RouteGroup - */ - // TODO : vérifier si on pas plutot utiliser un Closure au lieu d'un callable pour le typehint. - // TODO : il semble pôssible dans Slim de passer une string, ou un callable. Vérifier l'utilité de cette possibilité d'avoir un string !!!! - public function group(string $prefix, callable $callback): RouteGroup + public function setRouteCollector(RouteCollectorInterface $collector): void { - $group = new RouteGroup($prefix, $callback, $this); - $this->groups[] = $group; - - return $group; + $this->routeCollector = $collector; } + /** * {@inheritdoc} */ @@ -226,7 +195,8 @@ public function match(ServerRequestInterface $request): RouteResult $this->injectRoutes($request); // process routes - $dispatcher = new Dispatcher($this->routes, $this->generator->getData()); + //$dispatcher = new Dispatcher($this->routeCollector->getRoutes(), $this->generator->getData()); + $dispatcher = new Dispatcher($this->generator->getData()); return $dispatcher->dispatchRequest($request); } @@ -239,9 +209,7 @@ public function match(ServerRequestInterface $request): RouteResult */ private function injectRoutes(ServerRequestInterface $request): void { - $this->processGroups(); - - foreach ($this->routes as $identifier => $route) { + foreach ($this->routeCollector->getRoutes() as $route) { // check for scheme condition if (! is_null($route->getScheme()) && $route->getScheme() !== $request->getUri()->getScheme()) { continue; @@ -267,28 +235,7 @@ private function injectRoutes(ServerRequestInterface $request): void $routePath = $this->replaceAssertPatterns($route->getRequirements(), $route->getPath()); $routePath = $this->replaceWordPatterns($routePath); - $this->injectRoute($identifier, $route->getAllowedMethods(), $this->basePath . $routePath); - } - } - - /** - * Process all groups. - */ - // A voir si cette méthode ne devrait pas être appellée directement dans la méthode ->group() pour préparer les routes dés qu'on ajoute un group !!!! - // https://github.com/slimphp/Slim/blob/4.x/Slim/Routing/RouteCollector.php#L255 - private function processGroups(): void - { - // TODO : vérifier si il ne faut pas faire un array_reverse lorsqu'on execute les groups. Surtout dans le cas ou on ajoute des middlewares au group et qui seront propagés à la route. - //https://github.com/slimphp/Slim/blob/4.x/Slim/Routing/Route.php#L350 - - // Call the $group by reference because in the case : group of group the size of the array is modified because a new group is added in the group() function. - foreach ($this->groups as $key => &$group) { - // TODO : déplacer le unset aprés la méthode invoke ou collectroute du group. Voir si c'est pas plus ^propre de remplacer le unset par un array_pop ou un array_shift !!!! - unset($this->groups[$key]); - // TODO : créer une méthode ->collectRoutes() dans la classe RouteGroup, au lieu d'utiliser le invoke() on utilisera cette méthode, c'est plus propre !!!! - $group(); - //array_pop($this->groups); - //array_shift($this->routeGroups); + $this->injectRoute($route, $route->getAllowedMethods(), $this->basePath . $routePath); } } @@ -334,14 +281,14 @@ private function replaceWordPatterns(string $path): string * @param string[] $httpMethod * @param string $routePath */ - private function injectRoute(string $routeId, array $httpMethod, string $routePath): void + private function injectRoute(Route $route, array $httpMethod, string $routePath): void { $routeDatas = $this->parser->parse($routePath); foreach ($httpMethod as $method) { foreach ($routeDatas as $routeData) { // TODO : réactiver le try catch si on souhaite pouvoir gérer les doublons de routes. //try { - $this->generator->addRoute($method, $routeData, $routeId); + $this->generator->addRoute($method, $routeData, $route); //} catch (\Throwable $e) { //} } @@ -349,51 +296,45 @@ private function injectRoute(string $routeId, array $httpMethod, string $routePa } /** - * Get route objects. + * Build the path for a named route including the base path. * - * @return Route[] - */ - public function getRoutes(): array - { - $this->processGroups(); - - return array_values($this->routes); - } - - /** - * Get a named route. - * - * @param string $name Route name + * @param string $routeName Route name + * @param array $substitutions Named argument replacement data + * @param array $queryParams Optional query string parameters * - * @throws \InvalidArgumentException If named route does not exist + * @throws InvalidArgumentException If named route does not exist + * @throws InvalidArgumentException If required data not provided * - * @return \Chiron\Routing\Route + * @return string */ - public function getNamedRoute(string $name): Route + public function urlFor(string $routeName, array $substitutions = [], array $queryParams = []): string { - foreach ($this->getRoutes() as $route) { - if ($route->getName() === $name) { - return $route; - } + $url = $this->relativeUrlFor($routeName, $substitutions, $queryParams); + + if ($basePath = $this->getBasePath()) { + $url = $basePath . $url; } - throw new InvalidArgumentException('Named route does not exist for name: ' . $name); + return $url; } /** - * Remove named route. + * Build the path for a named route excluding the base path. + * + * @param string $routeName Route name + * @param array $substitutions Named argument replacement data + * @param array $queryParams Optional query string parameters * - * @param string $name Route name + * @throws InvalidArgumentException If named route does not exist + * @throws InvalidArgumentException If required data not provided * - * @throws \InvalidArgumentException If named route does not exist + * @return string */ - public function removeNamedRoute(string $name) + public function relativeUrlFor(string $routeName, array $substitutions = [], array $queryParams = []): string { - $route = $this->getNamedRoute($name); - // no exception, route exists, now remove by id - //unset($this->routes[$route->getIdentifier()]); - // no exception so far so the route exists we can remove the object safely. - unset($this->routes[array_search($route, $this->routes)]); + $route = $this->routeCollector->getNamedRoute($routeName); + + return RouteUrlGenerator::generate($route->getPath(), $substitutions, $queryParams); } /* diff --git a/src/Chiron/Routing/RouterInterface.php b/src/Chiron/Routing/RouterInterface.php index 060253d..21bbc49 100644 --- a/src/Chiron/Routing/RouterInterface.php +++ b/src/Chiron/Routing/RouterInterface.php @@ -4,29 +4,12 @@ namespace Chiron\Routing; +use Chiron\Routing\Traits\MiddlewareAwareInterface; +use Chiron\Routing\Traits\StrategyAwareInterface; use Psr\Http\Message\ServerRequestInterface; -interface RouterInterface +interface RouterInterface extends MiddlewareAwareInterface, StrategyAwareInterface { - /** - * Group a bunch of routes. - * - * @param string $prefix - * @param callable $group - * - * @return \Chiron\Routing\RouteGroup - */ - public function group(string $prefix, callable $group): RouteGroup; - - /** - * Add a route to the map. - * - * @param string $path - * @param callable|string $handler - * - * @return \Chiron\Routing\Route - */ - public function map(string $path, $handler): Route; public function match(ServerRequestInterface $request): RouteResult; @@ -42,6 +25,14 @@ public function setBasePath(string $basePath): void; */ public function getBasePath(): string; + public function getRouteCollector(): RouteCollectorInterface; + + public function setRouteCollector(RouteCollectorInterface $collector): void; + + public function urlFor(string $routeName, array $substitutions = [], array $queryParams = []): string; + + public function relativeUrlFor(string $routeName, array $substitutions = [], array $queryParams = []): string; + // TODO : ajouter les méthodes : generateUri / getRoutes => attention pas la peine de mettre la méthode addRoute car c'est géré via map() pour ajouter une route. // TODO : réflaichir si on doit ajouter les méthodes : getNamedRoute/removeNamedRoute dans cette interface. } diff --git a/src/Chiron/Routing/Traits/RouteCollectionInterface.php b/src/Chiron/Routing/Traits/RouteCollectionInterface.php index fe734ff..24d27c9 100644 --- a/src/Chiron/Routing/Traits/RouteCollectionInterface.php +++ b/src/Chiron/Routing/Traits/RouteCollectionInterface.php @@ -5,9 +5,22 @@ namespace Chiron\Routing\Traits; use Chiron\Routing\Route; +use Chiron\Routing\RouteGroup; + +// TODO : on devrait pas aussi ajouter les méthodes map et group dans cette interface ????? interface RouteCollectionInterface { + /** + * Group a bunch of routes. + * + * @param string $prefix + * @param callable $group + * + * @return \Chiron\Routing\RouteGroup + */ + public function group(string $prefix, callable $group): RouteGroup; + /** * Add a route to the map. * @@ -16,7 +29,7 @@ interface RouteCollectionInterface * * @return \Chiron\Routing\Route */ - //public function map(string $path, $handler): Route; + public function map(string $path, $handler): Route; /** * Add GET route. @@ -135,4 +148,36 @@ public function patch(string $pattern, $handler): Route; * @return \Chiron\Routing\Route */ public function any(string $pattern, $handler): Route; + + /** + * Create a redirect from one URI to another. + * + * @param string $url + * @param string $destination + * @param int $status + * + * @return \Chiron\Routing\Route + */ + public function redirect(string $url, string $destination, int $status = 302): Route; + + /** + * Create a permanent redirect from one URI to another. + * + * @param string $url + * @param string $destination + * + * @return \Chiron\Routing\Route + */ + public function permanentRedirect(string $url, string $destination): Route; + + /** + * Register a new route that returns a view. + * + * @param string $url + * @param string $view + * @param array $params + * + * @return \Chiron\Routing\Route + */ + public function view(string $url, string $view, array $params = []): Route; } diff --git a/src/Chiron/Routing/Traits/RouteCollectionTrait.php b/src/Chiron/Routing/Traits/RouteCollectionTrait.php index 62d7b58..a234afd 100644 --- a/src/Chiron/Routing/Traits/RouteCollectionTrait.php +++ b/src/Chiron/Routing/Traits/RouteCollectionTrait.php @@ -214,7 +214,8 @@ public function permanentRedirect(string $url, string $destination): Route */ public function view(string $url, string $view, array $params = []): Route { - return $this->match(['GET', 'HEAD'], $url, '\Chiron\Routing\Controller\ViewController@__invoke') + return $this->map($url, '\Chiron\Routing\Controller\ViewController@__invoke') + ->method('GET', 'HEAD') ->setDefault('view', $view) ->setDefault('params', $params); } diff --git a/tests/Routing/ApplicationRouterTest.php b/tests/Routing/ApplicationRouterTest.php index 138a06d..12a7d03 100644 --- a/tests/Routing/ApplicationRouterTest.php +++ b/tests/Routing/ApplicationRouterTest.php @@ -24,7 +24,8 @@ public function testGetRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->get($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->get($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('GET', 'methods', $route); } @@ -36,7 +37,8 @@ public function testPostRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->post($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->post($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('POST', 'methods', $route); } @@ -48,7 +50,8 @@ public function testPutRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->put($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->put($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('PUT', 'methods', $route); } @@ -60,7 +63,8 @@ public function testPatchRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->patch($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->patch($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('PATCH', 'methods', $route); } @@ -72,7 +76,8 @@ public function testDeleteRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->delete($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->delete($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('DELETE', 'methods', $route); } @@ -84,7 +89,8 @@ public function testOptionsRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->options($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->options($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('OPTIONS', 'methods', $route); } @@ -96,7 +102,8 @@ public function testHeadRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->head($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->head($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('HEAD', 'methods', $route); } @@ -108,7 +115,8 @@ public function testAnyRoute() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->any($path, $callable); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->any($path, $callable); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('GET', 'methods', $route); $this->assertAttributeContains('POST', 'methods', $route); @@ -125,7 +133,8 @@ public function testRouteMapping() // Do something }; $app = new Kernel(); - $route = $app->getRouter()->map($path, $callable)->method('GET', 'POST'); + $collector = $app->getRouter()->getRouteCollector(); + $route = $collector->map($path, $callable)->method('GET', 'POST'); $this->assertInstanceOf(Route::class, $route); $this->assertAttributeContains('GET', 'methods', $route); $this->assertAttributeContains('POST', 'methods', $route); @@ -141,7 +150,7 @@ public function testRouteRedirect() throw new \Exception('Route should not be reachable.'); }); */ - $app->getRouter()->redirect('/contact_us', 'contact'); + $app->getRouter()->getRouteCollector()->redirect('/contact_us', 'contact'); $request = new ServerRequest('GET', new Uri('/contact_us')); $response = $app->handle($request); @@ -160,7 +169,7 @@ public function testRouteRedirectWithCustomStatus() throw new \Exception('Route should not be reachable.'); }); */ - $app->getRouter()->redirect('/contact_us', 'contact', 301); + $app->getRouter()->getRouteCollector()->redirect('/contact_us', 'contact', 301); $request = new ServerRequest('GET', new Uri('/contact_us')); $response = $app->handle($request); @@ -179,7 +188,7 @@ public function testRoutePermanentRedirect() throw new \Exception('Route should not be reachable.'); }); */ - $app->getRouter()->permanentRedirect('/contact_us', 'contact'); + $app->getRouter()->getRouteCollector()->permanentRedirect('/contact_us', 'contact'); $request = new ServerRequest('GET', new Uri('/contact_us')); $response = $app->handle($request); diff --git a/tests/Routing/FastRouterTest.php b/tests/Routing/FastRouterTest.php index 28c10fc..39afa67 100644 --- a/tests/Routing/FastRouterTest.php +++ b/tests/Routing/FastRouterTest.php @@ -25,7 +25,7 @@ public function testDuplicateVariableNameError() $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get('/foo/{test}/{test:\d+}', 'handler0'); + $router->getRouteCollector()->get('/foo/{test}/{test:\d+}', 'handler0'); $routeResult = $router->match($request); } @@ -42,8 +42,8 @@ public function testDuplicateVariableRoute() $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get('/user/{id}', 'handler0'); // oops, forgot \d+ restriction ;) - $router->get('/user/{name}', 'handler1'); + $router->getRouteCollector()->get('/user/{id}', 'handler0'); // oops, forgot \d+ restriction ;) + $router->getRouteCollector()->get('/user/{name}', 'handler1'); $routeResult = $router->match($request); } @@ -60,8 +60,8 @@ public function testDuplicateStaticRoute() $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get('/user', 'handler0'); - $router->get('/user', 'handler1'); + $router->getRouteCollector()->get('/user', 'handler0'); + $router->getRouteCollector()->get('/user', 'handler1'); $routeResult = $router->match($request); } @@ -80,8 +80,8 @@ public function testShadowedStaticRoute() $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get('/user/{name}', 'handler0'); - $router->get('/user/nikic', 'handler1'); + $router->getRouteCollector()->get('/user/{name}', 'handler0'); + $router->getRouteCollector()->get('/user/nikic', 'handler1'); $routeResult = $router->match($request); } @@ -98,7 +98,7 @@ public function testCapturing() $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get('/{lang:(en|de)}', 'handler0'); + $router->getRouteCollector()->get('/{lang:(en|de)}', 'handler0'); $routeResult = $router->match($request); } diff --git a/tests/Routing/RouteCollectorTest.php b/tests/Routing/RouteCollectorTest.php index 3fe4f60..13321f5 100644 --- a/tests/Routing/RouteCollectorTest.php +++ b/tests/Routing/RouteCollectorTest.php @@ -21,14 +21,14 @@ public function testRelativeUrlFor() $router->setBasePath('/base/path'); $pattern = '/hello/{first:\w+}/{last}'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); $this->assertEquals( '/hello/josh/lockhart', - $urlGenerator->relativeUrlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) + $router->relativeUrlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) ); } @@ -39,14 +39,14 @@ public function testUrlForWithNoBasePath() $router->setBasePath(''); $pattern = '/hello/{first:\w+}/{last}'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); $this->assertEquals( '/hello/josh/lockhart', - $urlGenerator->urlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) + $router->urlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) ); } @@ -57,14 +57,14 @@ public function testUrlForWithBasePath() $pattern = '/hello/{first:\w+}/{last}'; $router->setBasePath('/base/path'); - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); $this->assertEquals( '/base/path/hello/josh/lockhart', - $urlGenerator->urlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) + $router->urlFor('foo', ['first' => 'josh', 'last' => 'lockhart']) ); } @@ -74,22 +74,22 @@ public function testUrlForWithOptionalParameters() $pattern = '/archive/{year}[/{month}[/d/{day}]]'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); $this->assertEquals( '/archive/2015', - $urlGenerator->urlFor('foo', ['year' => '2015']) + $router->urlFor('foo', ['year' => '2015']) ); $this->assertEquals( '/archive/2015/7', - $urlGenerator->urlFor('foo', ['year' => '2015', 'month' => 7]) + $router->urlFor('foo', ['year' => '2015', 'month' => 7]) ); $this->assertEquals( '/archive/2015/12/d/19', - $urlGenerator->urlFor('foo', ['year' => '2015', 'month' => '12', 'day' => '19']) + $router->urlFor('foo', ['year' => '2015', 'month' => '12', 'day' => '19']) ); } @@ -99,14 +99,14 @@ public function testUrlForWithQueryParameters() $pattern = '/hello/{name}'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); $this->assertEquals( '/hello/josh?a=b&c=d', - $urlGenerator->urlFor('foo', ['name' => 'josh'], ['a' => 'b', 'c' => 'd']) + $router->urlFor('foo', ['name' => 'josh'], ['a' => 'b', 'c' => 'd']) ); } @@ -120,12 +120,12 @@ public function testUrlForWithMissingSegmentData() $pattern = '/hello/{first}/{last}'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $urlGenerator->urlFor('foo', ['last' => 'lockhart']); + $router->urlFor('foo', ['last' => 'lockhart']); } /** @@ -138,12 +138,12 @@ public function testUrlForRouteNotExists() $pattern = '/hello/{first}/{last}'; - $route = $router->map($pattern, 'callable'); + $route = $router->getRouteCollector()->map($pattern, 'callable'); $route->setName('foo'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $urlGenerator->urlFor('bar', ['first' => 'josh', 'last' => 'lockhart']); + $router->urlFor('bar', ['first' => 'josh', 'last' => 'lockhart']); } // TODO : améliorer les tests, il faut que les queryParams soient calculés automatiquement. regarder les tests mis en commentaire !!! https://github.com/laravel/framework/blob/5.8/tests/Routing/RoutingUrlGeneratorTest.php#L168 @@ -155,36 +155,36 @@ public function testBasicRouteGeneration() /* * Empty Named Route */ - $route = $router->get('/', $callable)->setName('plain'); + $route = $router->getRouteCollector()->get('/', $callable)->setName('plain'); /* * Named Routes */ - $route = $router->get('foo/bar', $callable)->setName('foo'); + $route = $router->getRouteCollector()->get('foo/bar', $callable)->setName('foo'); /* * Parameters... */ - $route = $router->get('foo/bar/{baz}/breeze/{boom}', $callable)->setName('bar'); + $route = $router->getRouteCollector()->get('foo/bar/{baz}/breeze/{boom}', $callable)->setName('bar'); /* * Single Parameter... */ - $route = $router->get('foo/bar/{baz}', $callable)->setName('foobar'); + $route = $router->getRouteCollector()->get('foo/bar/{baz}', $callable)->setName('foobar'); /* * Non ASCII routes */ - $route = $router->get('foo/bar/åαф/{baz}', $callable)->setName('foobarbaz'); + $route = $router->getRouteCollector()->get('foo/bar/åαф/{baz}', $callable)->setName('foobarbaz'); /* * Fragments */ - $route = $router->get('foo/bar#derp', $callable)->setName('fragment'); + $route = $router->getRouteCollector()->get('foo/bar#derp', $callable)->setName('fragment'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $this->assertEquals('/', $urlGenerator->urlFor('plain', [])); + $this->assertEquals('/', $router->urlFor('plain', [])); // $this->assertEquals('/?foo=bar', $urlGenerator->urlFor('plain', ['foo' => 'bar'])); - $this->assertEquals('/foo/bar', $urlGenerator->urlFor('foo')); - $this->assertEquals('/foo/bar', $urlGenerator->urlFor('foo', [])); + $this->assertEquals('/foo/bar', $router->urlFor('foo')); + $this->assertEquals('/foo/bar', $router->urlFor('foo', [])); // $this->assertEquals('/foo/bar?foo=bar', $urlGenerator->urlFor('foo', ['foo' => 'bar'])); // $this->assertEquals('/foo/bar/taylor/breeze/otwell?fly=wall', $urlGenerator->urlFor('bar', ['taylor', 'otwell', 'fly' => 'wall'])); @@ -194,10 +194,10 @@ public function testBasicRouteGeneration() // $this->assertEquals('/foo/bar/taylor/breeze/otwell?fly=wall', $urlGenerator->urlFor('bar', ['taylor', 'otwell', 'fly' => 'wall'])); // $this->assertEquals('/foo/bar/taylor/breeze/otwell?wall&woz', $urlGenerator->urlFor('bar', ['wall', 'woz', 'boom' => 'otwell', 'baz' => 'taylor'])); // $this->assertEquals('/foo/bar/taylor/breeze/otwell?wall&woz', $urlGenerator->urlFor('bar', ['taylor', 'otwell', 'wall', 'woz'])); - $this->assertEquals('/foo/bar/%C3%A5%CE%B1%D1%84/%C3%A5%CE%B1%D1%84', $urlGenerator->urlFor('foobarbaz', ['baz' => 'åαф'])); - $this->assertEquals('/foo/bar#derp', $urlGenerator->urlFor('fragment', [], [])); - $this->assertEquals('/foo/bar?foo=bar#derp', $urlGenerator->urlFor('fragment', [], ['foo' => 'bar'])); - $this->assertEquals('/foo/bar?baz=%C3%A5%CE%B1%D1%84#derp', $urlGenerator->urlFor('fragment', [], ['baz' => 'åαф'])); + $this->assertEquals('/foo/bar/%C3%A5%CE%B1%D1%84/%C3%A5%CE%B1%D1%84', $router->urlFor('foobarbaz', ['baz' => 'åαф'])); + $this->assertEquals('/foo/bar#derp', $router->urlFor('fragment', [], [])); + $this->assertEquals('/foo/bar?foo=bar#derp', $router->urlFor('fragment', [], ['foo' => 'bar'])); + $this->assertEquals('/foo/bar?baz=%C3%A5%CE%B1%D1%84#derp', $router->urlFor('fragment', [], ['baz' => 'åαф'])); } /** @@ -209,11 +209,11 @@ public function testRouteGenerationWrongRegex() $router = new Router(); $callable = 'callable'; - $route = $router->get('/test/{ param : \d{1,9} }', $callable)->setName('numeric'); + $route = $router->getRouteCollector()->get('/test/{ param : \d{1,9} }', $callable)->setName('numeric'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $urlGenerator->urlFor('numeric', ['param' => 1234567890]); + $router->urlFor('numeric', ['param' => 1234567890]); } /** @@ -225,11 +225,11 @@ public function testRouteGenerationWrongRegex_2() $router = new Router(); $callable = 'callable'; - $route = $router->get('/test[/{param}[/{id:[0-9]+}]]', $callable)->setName('numeric'); + $route = $router->getRouteCollector()->get('/test[/{param}[/{id:[0-9]+}]]', $callable)->setName('numeric'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $urlGenerator->urlFor('numeric', ['param' => 'foo', 'id' => 'foo']); + $router->urlFor('numeric', ['param' => 'foo', 'id' => 'foo']); } /** @@ -241,10 +241,10 @@ public function testRouteGenerationWrongRegex_3() $router = new Router(); $callable = 'callable'; - $route = $router->get('/{lang:(fr|en)}', $callable)->setName('string'); + $route = $router->getRouteCollector()->get('/{lang:(fr|en)}', $callable)->setName('string'); - $urlGenerator = new RouteUrlGenerator($router); + $urlGenerator = new RouteUrlGenerator($router->getRouteCollector()); - $urlGenerator->urlFor('string', ['lang' => 'foo']); + $router->urlFor('string', ['lang' => 'foo']); } } diff --git a/tests/Routing/RouteGroupTest.php b/tests/Routing/RouteGroupTest.php index d5423c4..a0897df 100644 --- a/tests/Routing/RouteGroupTest.php +++ b/tests/Routing/RouteGroupTest.php @@ -14,7 +14,7 @@ class RouteGroupTest extends TestCase { public function testRouteGroup() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $res = $router->group('/prefix', function ($group) { $group->get('/', function () { @@ -46,7 +46,7 @@ public function testRouteGroup() public function testRouteGroupOfGroup() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $routeGroup = $router->group('/prefix', function ($group) { $group->group('/group/', function ($group) { @@ -71,7 +71,7 @@ public function testRouteGroupOfGroup() public function testRouteOverrideStrategyAndConditions() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $strategyMock = $this->createMock(StrategyInterface::class); $routeGroup = $router->group('/prefix', function ($group) use ($strategyMock) { @@ -105,7 +105,7 @@ public function testRouteOverrideStrategyAndConditions() public function testRouteGroupOfGroupWithOverrideHostPortScheme() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $router->group('/prefix', function ($group) { $group->get('/', function () { @@ -140,7 +140,7 @@ public function testRouteGroupOfGroupWithOverrideHostPortScheme() public function testRouteGroupWithOverrideMiddleware() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $router->group('/prefix', function ($group) { $group->get('/', function () { @@ -169,7 +169,7 @@ public function testRouteGroupWithOverrideMiddleware() public function testRouteNestedGroupWithOverrideMiddleware() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $grp = $router->group('/prefix', function ($group) { $group->get('/', function () { @@ -200,7 +200,7 @@ public function testRouteNestedGroupWithOverrideMiddleware() public function testRouteMiddlewareTrait() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $group = $router->group('/prefix', function () { }); @@ -217,7 +217,7 @@ public function testRouteMiddlewareTrait() public function testRouteConditionTrait() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $group = $router->group('/prefix', function () { }); @@ -252,7 +252,7 @@ public function testRouteConditionTrait() public function testRouteStrategyTrait() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $group = $router->group('/prefix', function () { }); @@ -280,7 +280,7 @@ public function httpMethods() */ public function testRouteCollectionTraitHttpMethods($method) { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $group = $router->group('/prefix', function ($group) use ($method) { $group->{$method}('/', 'foobar'); @@ -297,7 +297,7 @@ public function testRouteCollectionTraitHttpMethods($method) public function testRouteCollectionTraitMapAndAny() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $group = $router->group('/prefix', function ($group) { $group->map('/', 'foobar'); $group->any('/', 'foobar'); diff --git a/tests/Routing/RouterTest.php b/tests/Routing/RouterTest.php index b205d2d..23f15c1 100644 --- a/tests/Routing/RouterTest.php +++ b/tests/Routing/RouterTest.php @@ -9,6 +9,7 @@ use Chiron\Routing\Route; use Chiron\Routing\Router; use Chiron\Routing\RouterInterface; +use Chiron\Routing\RouteCollectorInterface; use Chiron\Routing\Strategy\StrategyInterface; use PHPUnit\Framework\TestCase; @@ -49,7 +50,7 @@ public function httpMethods() */ public function testRouteCollectionTraitHttpMethods($method) { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $path = '/something'; $callable = function () { }; @@ -61,7 +62,7 @@ public function testRouteCollectionTraitHttpMethods($method) public function testRouteCollectionTraitMapAndAny() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); $path = '/something'; $callable = function () { }; @@ -99,7 +100,7 @@ public function testMatchWithUrlEncodedSpecialChars($routePath, $requestPath, $e $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $router->get($routePath, 'handler')->name('foo'); + $router->getRouteCollector()->get($routePath, 'handler')->name('foo'); $routeResult = $router->match($request); @@ -114,9 +115,9 @@ public function testMatchWithUrlEncodedSpecialChars($routePath, $requestPath, $e */ public function testRemoveRoute() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); - $router->setBasePath('/base/path'); + //$router->setBasePath('/base/path'); $route1 = $router->map('/foo', 'callable'); $route1->setName('foo'); $route2 = $router->map('/bar', 'callable'); @@ -157,9 +158,9 @@ public function testRemoveRoute() */ public function testRouteRemovalNotExists() { - $router = new Router(); + $router = (new Router())->getRouteCollector(); - $router->setBasePath('/base/path'); + //$router->setBasePath('/base/path'); $router->removeNamedRoute('non-existing-route-name'); } @@ -191,7 +192,7 @@ public function testMethodNotAllowedDispatches($method, $uri, $callback, $availa $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $callback($router); + $callback($router->getRouteCollector()); $routeResult = $router->match($request); @@ -204,7 +205,7 @@ public function provideMethodNotAllowedDispatchCases() { $cases = []; // 0 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/resource/123/456', 'handler0'); }; $method = 'POST'; @@ -212,7 +213,7 @@ public function provideMethodNotAllowedDispatchCases() $allowedMethods = ['GET']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 1 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/resource/123/456', 'handler0'); $r->post('/resource/123/456', 'handler1'); $r->put('/resource/123/456', 'handler2'); @@ -223,7 +224,7 @@ public function provideMethodNotAllowedDispatchCases() $allowedMethods = ['GET', 'POST', 'PUT']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 2 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/user/{name}/{id:[0-9]+}', 'handler0'); $r->post('/user/{name}/{id:[0-9]+}', 'handler1'); $r->put('/user/{name}/{id:[0-9]+}', 'handler2'); @@ -234,7 +235,7 @@ public function provideMethodNotAllowedDispatchCases() $allowedMethods = ['GET', 'POST', 'PUT', 'PATCH']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 3 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->post('/user/{name}', 'handler1'); $r->put('/user/{name:[a-z]+}', 'handler2'); $r->patch('/user/{name:[a-z]+}', 'handler3'); @@ -244,13 +245,13 @@ public function provideMethodNotAllowedDispatchCases() $allowedMethods = ['POST', 'PUT', 'PATCH']; $cases[] = [$method, $uri, $callback, $allowedMethods]; // 4 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->map('/user', 'handlerGetPost')->setAllowedMethods(['GET', 'POST']); $r->delete('/user', 'handlerDelete'); }; $cases[] = ['PUT', '/user', $callback, ['GET', 'POST', 'DELETE']]; // 5 - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->post('/user.json', 'handler0'); $r->get('/{entity}.json', 'handler1'); }; @@ -270,7 +271,7 @@ public function testNotFoundDispatches($method, $uri, $callback) $strategyMock = $this->createMock(StrategyInterface::class); $router->setStrategy($strategyMock); - $callback($router); + $callback($router->getRouteCollector()); $routeResult = $router->match($request); @@ -283,7 +284,7 @@ public function provideNotFoundDispatchCases() { $cases = []; // 0 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/resource/123/456', 'handler0'); }; $method = 'GET'; @@ -300,7 +301,7 @@ public function provideNotFoundDispatchCases() $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 3 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/handler0', 'handler0'); $r->get('/handler1', 'handler1'); $r->get('/handler2', 'handler2'); @@ -309,7 +310,7 @@ public function provideNotFoundDispatchCases() $uri = '/not-found'; $cases[] = [$method, $uri, $callback]; // 4 --------------------------------------------------------------------------------------> - $callback = function (RouterInterface $r) { + $callback = function (RouteCollectorInterface $r) { $r->get('/user/{name}/{id:[0-9]+}', 'handler0'); $r->get('/user/{id:[0-9]+}', 'handler1'); $r->get('/user/{name}', 'handler2'); diff --git a/tests/Routing/Strategy/HtmlStrategyTest.php b/tests/Routing/Strategy/HtmlStrategyTest.php index 8ab707d..d0d31cb 100644 --- a/tests/Routing/Strategy/HtmlStrategyTest.php +++ b/tests/Routing/Strategy/HtmlStrategyTest.php @@ -29,7 +29,7 @@ public function testRouteStrategyWithRequestTypeHintting() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo', $routeCallback); $response = $app->handle($request); @@ -53,7 +53,7 @@ public function testRouteStrategyWithoutRequestTypeHintting() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo', $routeCallback); $response = $app->handle($request); @@ -77,7 +77,7 @@ public function testRouteStrategyWithBadTypeHintting() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo', $routeCallback); $response = $app->handle($request); } @@ -94,7 +94,7 @@ public function testRouteStrategyWithScalarTypeHintting() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo/{id}/{name}/{isRegistered}/{floatNumber}', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo/{id}/{name}/{isRegistered}/{floatNumber}', $routeCallback); $response = $app->handle($request); @@ -113,7 +113,7 @@ public function testRouteStrategyWithScalarTypeHinttingAndDefaultValue() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo/[{id}/{name}/{isRegistered}/{floatNumber}]', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo/[{id}/{name}/{isRegistered}/{floatNumber}]', $routeCallback); $response = $app->handle($request); @@ -132,7 +132,7 @@ public function testRouteStrategyStoreParamsInRequestAttributes() $app = new Kernel(); $app->middleware([RoutingMiddleware::class, DispatcherMiddleware::class]); - $route = $app->getRouter()->get('/foo/{name}', $routeCallback); + $route = $app->getRouter()->getRouteCollector()->get('/foo/{name}', $routeCallback); $app->handle($request); }