Passed
Pull Request — master (#14)
by Sergei
07:44 queued 06:02
created

MiddlewareFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Middleware\Dispatcher;
6
7
use Psr\Container\ContainerInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Yiisoft\Injector\Injector;
13
14
final class MiddlewareFactory implements MiddlewareFactoryInterface
15
{
16
    private ContainerInterface $container;
17
18 15
    public function __construct(ContainerInterface $container)
19
    {
20 15
        $this->container = $container;
21 15
    }
22
23 15
    public function create($middlewareDefinition): MiddlewareInterface
24
    {
25 15
        return $this->createMiddleware($middlewareDefinition);
26
    }
27
28
    /**
29
     * @param array|callable|string $middlewareDefinition A name of PSR-15 middleware, a callable with
30
     * `function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface` signature or
31
     * a handler action (an array of [handlerClass, handlerMethod]). For handler action and callable typed parameters
32
     * are automatically injected using dependency injection container passed to the route.
33
     * Current request and handler could be obtained by type-hinting for {@see ServerRequestInterface}
34
     * and {@see RequestHandlerInterface}.
35
     *
36
     * @return MiddlewareInterface
37
     */
38 15
    private function createMiddleware($middlewareDefinition): MiddlewareInterface
39
    {
40 15
        $this->validateMiddleware($middlewareDefinition);
41
42 9
        if (is_string($middlewareDefinition)) {
43 1
            return $this->container->get($middlewareDefinition);
44
        }
45
46 8
        return $this->wrapCallable($middlewareDefinition);
47
    }
48
49 8
    private function wrapCallable($callback): MiddlewareInterface
50
    {
51 8
        if (is_array($callback) && !is_object($callback[0])) {
52 3
            [$controller, $action] = $callback;
53 3
            return new class($controller, $action, $this->container) implements MiddlewareInterface {
54
                private string $class;
55
                private string $method;
56
                private ContainerInterface $container;
57
58
                public function __construct(string $class, string $method, ContainerInterface $container)
59
                {
60 3
                    $this->class = $class;
61 3
                    $this->method = $method;
62 3
                    $this->container = $container;
63 3
                }
64
65
                public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
66
                {
67 2
                    $controller = $this->container->get($this->class);
68 2
                    return (new Injector($this->container))->invoke([$controller, $this->method], [$request, $handler]);
69
                }
70
            };
71
        }
72
73 5
        return new class($callback, $this->container) implements MiddlewareInterface {
74
            private ContainerInterface $container;
75
            private $callback;
76
77
            public function __construct(callable $callback, ContainerInterface $container)
78
            {
79 5
                $this->callback = $callback;
80 5
                $this->container = $container;
81 5
            }
82
83
            public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
84
            {
85 5
                $response = (new Injector($this->container))->invoke($this->callback, [$request, $handler]);
86 5
                return $response instanceof MiddlewareInterface ? $response->process($request, $handler) : $response;
87
            }
88
        };
89
    }
90
91
    /**
92
     * @param array|callable|string $middlewareDefinition A name of PSR-15 middleware, a callable with
93
     * `function(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface` signature or
94
     * a handler action (an array of [handlerClass, handlerMethod]). For handler action and callable typed parameters
95
     * are automatically injected using dependency injection container passed to the route.
96
     * Current request and handler could be obtained by type-hinting for {@see ServerRequestInterface}
97
     * and {@see RequestHandlerInterface}.
98
     *
99
     * @throws InvalidMiddlewareDefinitionException
100
     */
101 15
    private function validateMiddleware($middlewareDefinition): void
102
    {
103 15
        if (is_string($middlewareDefinition) && is_subclass_of($middlewareDefinition, MiddlewareInterface::class)) {
104 1
            return;
105
        }
106
107 14
        if ($this->isCallable($middlewareDefinition) && (!is_array($middlewareDefinition) || !is_object($middlewareDefinition[0]))) {
108 8
            return;
109
        }
110
111 6
        throw new InvalidMiddlewareDefinitionException($middlewareDefinition);
112
    }
113
114 14
    private function isCallable($definition): bool
115
    {
116 14
        if (is_callable($definition)) {
117 8
            return is_object($definition)
118 5
                ? !$definition instanceof MiddlewareInterface
119 8
                : true;
120
        }
121
122 6
        return is_array($definition)
123 6
            && array_keys($definition) === [0, 1]
124 1
            && in_array(
125 1
                $definition[1],
126 1
                class_exists($definition[0]) ? get_class_methods($definition[0]) : [],
127 6
                true
128
            );
129
    }
130
}
131