Passed
Push — develop ( 906464...fc23db )
by nguereza
18:23 queued 16:08
created

MiddlewareResolver.php$0 ➔ process()   A

Complexity

Conditions 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Request Handler
5
 *
6
 * Platine Request Handler is the implementation of PSR 15
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine Request Handler
11
 * Copyright (c) 2020 Evgeniy Zyubin
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file MiddlewareResolver.php
34
 *
35
 *  The callable resolver class
36
 *
37
 *  @package    Platine\Http\Handler
38
 *  @author Platine Developers Team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Http\Handler;
49
50
use Platine\Container\ContainerInterface;
51
use Platine\Http\Handler\Exception\MiddlewareResolverException;
52
use Platine\Http\ResponseInterface;
53
use Platine\Http\ServerRequestInterface;
54
55
class MiddlewareResolver implements MiddlewareResolverInterface
56
{
57
    /**
58
     * The container instance to use to resolve handler
59
     * @var ContainerInterface
60
     */
61
    protected ?ContainerInterface $container;
62
63
    /**
64
     * Create new resolver instance
65
     * @param ContainerInterface|null $container
66
     */
67
    public function __construct(?ContainerInterface $container = null)
68
    {
69
        $this->container = $container;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     *
75
     * The handler must be one of:
76
     * - a string (class name or identifier of a container definition) or an instance
77
     * that implements `MiddlewareInterface` or `RequestHandlerInterface`;
78
     * - a callable without arguments that returns an instance of `ResponseInterface`;
79
     * - a callable matching signature of `MiddlewareInterface::process()`;
80
     *
81
     * @throws MiddlewareResolverException if the handler is not valid.
82
     */
83
    public function resolve($handler): MiddlewareInterface
84
    {
85
        if ($handler instanceof MiddlewareInterface) {
86
            return $handler;
87
        }
88
89
        if ($handler instanceof RequestHandlerInterface) {
90
            return $this->handler($handler);
91
        }
92
93
        if (is_string($handler)) {
94
            return $this->stringHandler($handler);
95
        }
96
97
        if (is_callable($handler)) {
98
            return $this->callableHandler($handler);
99
        }
100
101
        throw MiddlewareResolverException::create($handler);
102
    }
103
104
    /**
105
     * @param  callable $handler the callable handler
106
     * @return MiddlewareInterface
107
     *
108
     * @throws MiddlewareResolverException
109
     * if the handler does not return a `ResponseInterface` instance.
110
     */
111
    protected function callableHandler(callable $handler): MiddlewareInterface
112
    {
113
        return new class ($handler) implements MiddlewareInterface {
114
            /**
115
             *
116
             * @var callable
117
             */
118
            private $callable;
119
120
            /**
121
             * @param callable $callable
122
             */
123
            public function __construct($callable)
124
            {
125
                $this->callable = $callable;
126
            }
127
128
            public function process(
129
                ServerRequestInterface $request,
130
                RequestHandlerInterface $handler
131
            ): ResponseInterface {
132
                $response = ($this->callable)($request, $handler);
133
134
                if (!$response instanceof ResponseInterface) {
135
                    throw MiddlewareResolverException::forCallableMissingResponse($response);
136
                }
137
138
                return $response;
139
            }
140
        };
141
    }
142
143
    /**
144
     * @param  RequestHandlerInterface $handler the request handler
145
     * @return MiddlewareInterface
146
     */
147
    protected function handler(RequestHandlerInterface $handler): MiddlewareInterface
148
    {
149
        return new class ($handler) implements MiddlewareInterface {
150
            private RequestHandlerInterface $handler;
151
152
            public function __construct(RequestHandlerInterface $handler)
153
            {
154
                $this->handler = $handler;
155
            }
156
157
            public function process(
158
                ServerRequestInterface $request,
159
                RequestHandlerInterface $handler
160
            ): ResponseInterface {
161
                return $this->handler->handle($request);
162
            }
163
        };
164
    }
165
166
    /**
167
     * @param  string $handler the string handler name
168
     * @return MiddlewareInterface
169
     *
170
     * @throws MiddlewareResolverException if the handler is not valid
171
     */
172
    protected function stringHandler(string $handler): MiddlewareInterface
173
    {
174
        return new class ($handler, $this->container) implements MiddlewareInterface {
175
            private string $handler;
176
            private ?ContainerInterface $container;
177
178
            public function __construct(string $handler, ?ContainerInterface $container)
179
            {
180
                $this->handler = $handler;
181
                $this->container = $container;
182
            }
183
184
            public function process(
185
                ServerRequestInterface $request,
186
                RequestHandlerInterface $handler
187
            ): ResponseInterface {
188
                $name = $this->handler;
189
                $class = $name;
190
                $method = null;
191
                $instance = null;
192
193
                //if the value is something like Namespace1\Namespace2\ClassName@Method
194
                if (strpos($name, '@') !== false) {
195
                    $parts = explode('@', $name, 2);
196
                    $class = $parts[0];
197
                    $method = $parts[1];
198
                }
199
200
                if ($this->container !== null && $this->container->has($class)) {
201
                    $instance = $this->container->get($class);
202
                } elseif (class_exists($class)) {
203
                    $instance = new $class();
204
                }
205
206
207
                if ($instance instanceof MiddlewareInterface) {
208
                    return $instance->process($request, $handler);
209
                }
210
211
                if ($instance instanceof RequestHandlerInterface) {
212
                    return $instance->handle($request);
213
                }
214
215
                if ($method !== null && method_exists($instance, $method)) {
216
                    return $instance->{$method}($request, $handler);
217
                }
218
219
                throw MiddlewareResolverException::forStringNotConvertedToInstance($this->handler);
220
            }
221
        };
222
    }
223
}
224