Passed
Push — main ( 601ab0...1650cb )
by Jeroen
11:10
created

SlimRouteAttributeProvider::createFromApp()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 9
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
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 Slim\App;
12
use Slim\Interfaces\RouteCollectorInterface;
13
14
final class SlimRouteAttributeProvider implements RouteAttributeProviderInterface
15
{
16
    private RouteCollectorInterface $routeCollector;
17
    private ContainerInterface $container;
18
19 2
    public function __construct(RouteCollectorInterface $routeCollector, ContainerInterface $container)
20
    {
21 2
        $this->routeCollector = $routeCollector;
22 2
        $this->container      = $container;
23
    }
24
25 1
    public static function createFromApp(App $app) : self
26
    {
27 1
        $container = $app->getContainer();
28
29 1
        if ($container === null) {
30
            throw new LogicException('A PSR-11 container implementation is required');
31
        }
32
33 1
        return new self($app->getRouteCollector(), $container);
34
    }
35
36 1
    public function configure(string $className, string $methodName, Route $route) : void
37
    {
38 1
        $routeMap = $this->routeCollector->map(
39 1
            $route->getMethods(),
40 1
            $route->getPattern(),
41 1
            sprintf('%s:%s', $className, $methodName)
42
        );
43
44 1
        $routeName = $route->getName();
45 1
        if ($routeName !== null) {
46 1
            $routeMap->setName($routeName);
47
        }
48
49
        /**
50
         * Slims order of execution of middleware feels counterintuitive,
51
         * therefore, reverse the order of the middleware, so that the first set middleware will be executed first.
52
         */
53 1
        foreach (array_reverse($route->getMiddleware()) as $middleware) {
54 1
            $routeMap->addMiddleware($this->container->get($middleware));
55
        }
56
    }
57
58 1
    public function getRouteCollector() : RouteCollectorInterface
59
    {
60 1
        return $this->routeCollector;
61
    }
62
63 1
    public function getContainer() : ContainerInterface
64
    {
65 1
        return $this->container;
66
    }
67
}
68