|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Jerowork\RouteAttributeProvider\Slim; |
|
6
|
|
|
|
|
7
|
|
|
use Jerowork\RouteAttributeProvider\Api\Route; |
|
8
|
|
|
use Jerowork\RouteAttributeProvider\RouteAttributeProviderInterface; |
|
9
|
|
|
use LogicException; |
|
10
|
|
|
use Psr\Container\ContainerInterface; |
|
11
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
12
|
|
|
use Slim\App; |
|
13
|
|
|
use Slim\Interfaces\RouteCollectorInterface; |
|
14
|
|
|
|
|
15
|
|
|
final class SlimRouteAttributeProvider implements RouteAttributeProviderInterface |
|
16
|
|
|
{ |
|
17
|
|
|
private RouteCollectorInterface $routeCollector; |
|
18
|
|
|
private ContainerInterface $container; |
|
19
|
|
|
|
|
20
|
2 |
|
public function __construct(RouteCollectorInterface $routeCollector, ContainerInterface $container) |
|
21
|
|
|
{ |
|
22
|
2 |
|
$this->routeCollector = $routeCollector; |
|
23
|
2 |
|
$this->container = $container; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
1 |
|
public static function createFromApp(App $app) : self |
|
27
|
|
|
{ |
|
28
|
1 |
|
$container = $app->getContainer(); |
|
29
|
|
|
|
|
30
|
1 |
|
if ($container === null) { |
|
31
|
|
|
throw new LogicException('A PSR-11 container implementation is required'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
1 |
|
return new self($app->getRouteCollector(), $container); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
1 |
|
public function configure(string $className, string $methodName, Route $route) : void |
|
38
|
|
|
{ |
|
39
|
1 |
|
$routeMap = $this->routeCollector->map( |
|
40
|
1 |
|
$route->getMethods(), |
|
41
|
1 |
|
$route->getPattern(), |
|
42
|
1 |
|
sprintf('%s:%s', $className, $methodName) |
|
43
|
1 |
|
); |
|
44
|
|
|
|
|
45
|
1 |
|
$routeName = $route->getName(); |
|
46
|
1 |
|
if ($routeName !== null) { |
|
47
|
1 |
|
$routeMap->setName($routeName); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* Slims order of execution of middleware feels counterintuitive, |
|
52
|
|
|
* therefore, reverse the order of the middleware, so that the first set middleware will be executed first. |
|
53
|
|
|
*/ |
|
54
|
1 |
|
foreach (array_reverse($route->getMiddleware()) as $middleware) { |
|
55
|
|
|
/** @var MiddlewareInterface $service */ |
|
56
|
1 |
|
$service = $this->container->get($middleware); |
|
57
|
1 |
|
$routeMap->addMiddleware($service); |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
1 |
|
public function getRouteCollector() : RouteCollectorInterface |
|
62
|
|
|
{ |
|
63
|
1 |
|
return $this->routeCollector; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
public function getContainer() : ContainerInterface |
|
67
|
|
|
{ |
|
68
|
1 |
|
return $this->container; |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|