Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
ncou committed Jun 15, 2019
1 parent e97309b commit 053be21
Show file tree
Hide file tree
Showing 7 changed files with 99 additions and 42 deletions.
1 change: 1 addition & 0 deletions src/Chiron/Http/Middleware/RoutingMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
$allowedMethods = $result->getAllowedMethods();
// The OPTIONS request should send back a response with some headers like "Allow" header.
// TODO : vérifier le comportement avec CORS.
// TODO : regarder si ce code peut aider : https://github.com/illuminate/routing/blob/master/RouteCollection.php#L234
if ($request->getMethod() === 'OPTIONS') {
return ($this->responseFactory->createResponse())->withHeader('Allow', implode(', ', $allowedMethods));
}
Expand Down
2 changes: 2 additions & 0 deletions src/Chiron/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@

// TODO : ajouter une méthode getEmitter() et setEmitter()
// TODO : renommer la méthode getRequest en getServerRequest()

// TODO : faire un imlplements de l'interface RequestHandlerInterface car il y a la méthode ->handle() qui existe dans cette classe Kernel
class Kernel extends Container
{
// TODO : ajouter la possibiilité de passer directement un objet Config dans le constructeur, si il est null on initialise un nouveau config.
Expand Down
4 changes: 4 additions & 0 deletions src/Chiron/Routing/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use Chiron\Routing\Traits\StrategyAwareTrait;
use InvalidArgumentException;

//https://github.com/symfony/routing/blob/master/Route.php

class Route implements RouteConditionHandlerInterface, StrategyAwareInterface, MiddlewareAwareInterface
{
use MiddlewareAwareTrait;
Expand Down Expand Up @@ -368,6 +370,7 @@ public function getAllowedMethods(): array
*
* @param string or list of string
*/
// TODO : faire plutot des méthodes : getMethods() et setMethods()
public function method(string $method, string ...$methods): self
{
array_unshift($methods, $method);
Expand Down Expand Up @@ -400,6 +403,7 @@ public function setAllowedMethods(array $methods): self
*
* @return string[]
*/
// TODO : regarder aussi ici pour une méthode de vérification : https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php#L197
private function validateHttpMethods(array $methods): array
{
if (empty($methods)) {
Expand Down
21 changes: 20 additions & 1 deletion src/Chiron/Routing/RouteGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ public function map(string $path, $handler): Route

$route = $this->router->map($path, $handler);

// TODO : Vérifier l'utilité de conserver le group dans l'objet Route. On l'utilise que pour récuipérer les middlewares du group qu'on fusionne avec les middlewares de la route.
// Il faudrait plutot faire cette fusion ici !!!! c'est à dire virer la méthode Route::gatherMiddlewareStack() qui ne servirait plus.
$route->setParentGroup($this);

if ($host = $this->getHost()) {
Expand All @@ -87,16 +89,22 @@ public function map(string $path, $handler): Route
$route->setStrategy($this->getStrategy());
}

// TODO : ajouter aussi les middlewares du group à la route, et virer la propriété setParentGroup de la route car cela ne servira plus !!!!

return $route;
}

// TODO : vérifier si on pas plutot utiliser un Closure au lieu d'un callable pour le typehint
// 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
{
// TODO : vérifier si on doit pas utiliser un code comme ca : https://github.com/illuminate/routing/blob/master/RouteGroup.php#L58 => isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old;
// TODO : ou utiliser ce code : https://github.com/illuminate/routing/blob/master/Router.php#L560
$prefix = ($prefix === '/') ? $this->prefix : rtrim($this->prefix, '/') . sprintf('/%s', ltrim($prefix, '/'));

$group = $this->router->group($prefix, $callback);

// TODO : je pense que ce bout de code ne servira plus à rien si dans la classe Router on invoke() le group directement dans la méthode d'ajout au group ->group() executerai donc le invoke plutot que de le faire à la fin avec la méthode processGroup !!!
// in cases of group of groups, we need to persist the settings from the previous group in the new one.
if ($host = $this->getHost()) {
$group->setHost($host);
Expand All @@ -112,6 +120,8 @@ public function group(string $prefix, callable $callback): RouteGroup
}

// merge all the previous group middlewares in this last group.
// TODO : créer une méthode setMiddlewareStack(array $middlewares) dans la classe MiddlewareAwareTrait.php pour remplacer le tableau de middleware ??? non ???
// TODO : vérifier si il n'y a pas un bug, on dirait qu'on va ajouter au $group des middleware qu'il posséde déjà !!!! ou alors c'est que l'objet group nouvellement créé n'a pas de middleware mais dans ce cas c'est la méthode array_merge qui ne sert à rien !!!!
$group->middleware(array_merge($this->getMiddlewareStack(), $group->getMiddlewareStack()));

return $group;
Expand All @@ -121,10 +131,19 @@ public function group(string $prefix, callable $callback): RouteGroup
* Process the group and ensure routes are added to the collection.
*/
// TODO : regarder aussi ici : https://github.com/slimphp/Slim/blob/3.x/Slim/RouteGroup.php#L38
// TODO : créer plutot une méthode collectRoutes() qui rempplacerai le invoke et qui retournerai $this
public function __invoke(): void
{
// TODO : voir si on fait un bind sur $this
//call_user_func_array($this->callback->bindTo($this), [$this]);
($this->callback)($this);
}

/*
public function collectRoutes(): RouteGroupInterface
{
$callable = $this->callableResolver->resolve($this->callable);
$callable($this->routeCollectorProxy);
return $this;
}*/
}
74 changes: 52 additions & 22 deletions src/Chiron/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ class Router implements RouterInterface, StrategyAwareInterface, RouteCollection
/**
* @var array
*/
// TODO : regarder ici : https://github.com/ncou/router-group-middleware/blob/master/src/Router/Router.php#L25
// TODO : regarder ici : https://github.com/ncou/php-router-group-middleware/blob/master/src/Router.php#L26
private $patternMatchers = [
'/{(.+?):number}/' => '{$1:[0-9]+}',
'/{(.+?):word}/' => '{$1:[a-zA-Z]+}',
Expand Down Expand Up @@ -188,7 +190,8 @@ public function map(string $path, $handler): Route
*
* @return \Chiron\Routing\RouteGroup
*/
// TODO : vérifier si on pas plutot utiliser un Closure au lieu d'un callable pour le typehint
// 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);
Expand Down Expand Up @@ -218,6 +221,7 @@ public function dispatch_OLD(ServerRequestInterface $request) : ResponseInterfac

public function match(ServerRequestInterface $request): RouteResult
{
// TODO : virer cette ligne processGroups et utiliser dans la méthode injectRoutes un "->getRoutes()" au lieu d'accéder à l'objet $this->routes car la méthode get va faire le processgroup.
$this->processGroups();
$this->injectRoutes($request);

Expand All @@ -227,6 +231,27 @@ public function match(ServerRequestInterface $request): RouteResult
return $dispatcher->dispatchRequest($request);
}

/**
* 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);
}
}

/**
* Prepare all routes, build name index and filter out none matching
* routes before being passed off to the parser.
Expand All @@ -235,6 +260,7 @@ public function match(ServerRequestInterface $request): RouteResult
*/
private function injectRoutes(ServerRequestInterface $request): void
{
// TODO : utiliser dans la méthode "->getRoutes()" au lieu d'accéder à l'objet $this->routes car la méthode get va faire le processgroup et retourner les routes sans avoir besoin d'utiliser la clé "$key" qui ne sert à rien dans cette boucle !!!!
foreach ($this->routes as $key => $route) {
// check for scheme condition
if (! is_null($route->getScheme()) && $route->getScheme() !== $request->getUri()->getScheme()) {
Expand Down Expand Up @@ -265,19 +291,6 @@ private function injectRoutes(ServerRequestInterface $request): void
}
}

/**
* Process all groups.
*/
private function processGroups(): void
{
// 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) {
unset($this->groups[$key]);
$group();
//array_pop($this->groups);
}
}

/**
* Add or replace the requirement pattern inside the route path.
*
Expand Down Expand Up @@ -374,23 +387,36 @@ public function removeNamedRoute(string $name)
$route = $this->getNamedRoute($name);
// no exception, route exists, now remove by id
unset($this->routes[$route->getIdentifier()]);
//unset($this->routes[array_search($route,$this->routes)]);
}

/**
* {@inheritdoc}
*/
/*
public function lookupRoute(string $identifier): Route
{
if (!isset($this->routes[$identifier])) {
throw new InvalidArgumentException('Route not found for identifier: ' . $identifier);
}
return $this->routes[$identifier];
}*/

/**
* Build the path for a named route including the base path.
*
* @param string $name Route name
* @param array $data Named argument replacement data
* @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
*/
public function pathFor(string $name, array $data = [], array $queryParams = []): string
public function urlFor(string $routeName, array $substitutions = [], array $queryParams = []): string
{
$url = $this->relativePathFor($name, $data, $queryParams);
$url = $this->relativeUrlFor($routeName, $substitutions, $queryParams);

if ($this->basePath) {
$url = $this->basePath . $url;
Expand All @@ -402,7 +428,7 @@ public function pathFor(string $name, array $data = [], array $queryParams = [])
/**
* Build the path for a named route excluding the base path.
*
* @param string $name Route name
* @param string $routeName Route name
* @param array $substitutions Named argument replacement data
* @param array $queryParams Optional query string parameters
*
Expand All @@ -411,20 +437,24 @@ public function pathFor(string $name, array $data = [], array $queryParams = [])
*
* @return string
*/
// TODO : renommer cette fonction en "generateUri()", et renommer le paramétre "$data" en "$substitutions" et éventuellement virer la partie $queryParams ???? non ????
// TODO : ajouter la gestion des segments en plus des query params ???? https://github.com/ellipsephp/url-generator/blob/master/src/UrlGenerator.php#L42
// TODO : regarder si on peut améliorer le code => https://github.com/zendframework/zend-expressive-fastroute/blob/master/src/FastRouteRouter.php#L239
public function relativePathFor(string $name, array $substitutions = [], array $queryParams = []): string
// 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
public function relativeUrlFor(string $routeName, array $substitutions = [], array $queryParams = []): string
{
$route = $this->getNamedRoute($name);
$route = $this->getNamedRoute($routeName);
$pattern = $route->getPath();
$routeDatas = $this->parser->parse($pattern);
// $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.
//
// The most specific is last, so we look for that first.
$routeDatas = array_reverse($routeDatas);

$segments = [];
$segmentName = '';

foreach ($routeDatas as $routeData) {
foreach ($routeData as $item) {
if (is_string($item)) {
Expand Down
1 change: 1 addition & 0 deletions src/Chiron/Routing/Traits/MiddlewareAwareTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ public function shiftMiddleware() : MiddlewareInterface
/**
* {@inheritdoc}
*/
// TODO : créer une méthode setMiddlewareStack(array $middlewares) pour pouvoir remplacer le tableau de middleware ??? non ???
public function getMiddlewareStack(): array
{
return $this->middlewares;
Expand Down

0 comments on commit 053be21

Please sign in to comment.