anonymous//src/MiddlewareResolver.php$2   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 10
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
/**
56
 * @class MiddlewareResolver
57
 * @package Platine\Http\Handler
58
 */
59
class MiddlewareResolver implements MiddlewareResolverInterface
60
{
61
    /**
62
     * Create new resolver instance
63
     * @param ContainerInterface|null $container The container instance
64
     * to use to resolve handler
65
     */
66
    public function __construct(protected ?ContainerInterface $container = null)
67
    {
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     *
73
     * The handler must be one of:
74
     * - a string (class name or identifier of a container definition) or an instance
75
     * that implements `MiddlewareInterface` or `RequestHandlerInterface`;
76
     * - a callable without arguments that returns an instance of `ResponseInterface`;
77
     * - a callable matching signature of `MiddlewareInterface::process()`;
78
     *
79
     * @throws MiddlewareResolverException if the handler is not valid.
80
     */
81
    public function resolve(
82
        string|MiddlewareInterface|RequestHandlerInterface|callable $handler
83
    ): MiddlewareInterface {
84
        if ($handler instanceof MiddlewareInterface) {
85
            return $handler;
86
        }
87
88
        if ($handler instanceof RequestHandlerInterface) {
89
            return $this->handler($handler);
90
        }
91
92
        if (is_string($handler)) {
93
            return $this->stringHandler($handler);
94
        }
95
96
        return $this->callableHandler($handler);
97
    }
98
99
    /**
100
     * @param  callable $handler the callable handler
101
     * @return MiddlewareInterface
102
     *
103
     * if the handler does not return a `ResponseInterface` instance.
104
     */
105
    protected function callableHandler(callable $handler): MiddlewareInterface
106
    {
107
        return new class ($handler) implements MiddlewareInterface {
108
            /**
109
             *
110
             * @var callable
111
             */
112
            private $callable;
113
114
            /**
115
             * @param callable $callable
116
             */
117
            public function __construct($callable)
118
            {
119
                $this->callable = $callable;
120
            }
121
122
            public function process(
123
                ServerRequestInterface $request,
124
                RequestHandlerInterface $handler
125
            ): ResponseInterface {
126
                $response = ($this->callable)($request, $handler);
127
128
                if (!$response instanceof ResponseInterface) {
129
                    throw MiddlewareResolverException::forCallableMissingResponse($response);
130
                }
131
132
                return $response;
133
            }
134
        };
135
    }
136
137
    /**
138
     * @param  RequestHandlerInterface $handler the request handler
139
     * @return MiddlewareInterface
140
     */
141
    protected function handler(RequestHandlerInterface $handler): MiddlewareInterface
142
    {
143
        return new class ($handler) implements MiddlewareInterface {
144
            private RequestHandlerInterface $handler;
145
146
            public function __construct(RequestHandlerInterface $handler)
147
            {
148
                $this->handler = $handler;
149
            }
150
151
            public function process(
152
                ServerRequestInterface $request,
153
                RequestHandlerInterface $handler
154
            ): ResponseInterface {
155
                return $this->handler->handle($request);
156
            }
157
        };
158
    }
159
160
    /**
161
     * @param  string $handler the string handler name
162
     * @return MiddlewareInterface
163
     *
164
     */
165
    protected function stringHandler(string $handler): MiddlewareInterface
166
    {
167
        return new class ($handler, $this->container) implements MiddlewareInterface {
168
            private string $handler;
169
            private ?ContainerInterface $container;
170
171
            public function __construct(string $handler, ?ContainerInterface $container)
172
            {
173
                $this->handler = $handler;
174
                $this->container = $container;
175
            }
176
177
            public function process(
178
                ServerRequestInterface $request,
179
                RequestHandlerInterface $handler
180
            ): ResponseInterface {
181
                $name = $this->handler;
182
                $class = $name;
183
                $method = null;
184
                $instance = null;
185
186
                //if the value is something like Namespace1\Namespace2\ClassName@Method
187
                if (strpos($name, '@') !== false) {
188
                    $parts = explode('@', $name, 2);
189
                    $class = $parts[0];
190
                    $method = $parts[1];
191
                }
192
193
                if ($this->container !== null && $this->container->has($class)) {
194
                    $instance = $this->container->get($class);
195
                } elseif (class_exists($class)) {
196
                    $instance = new $class();
197
                }
198
199
200
                if ($instance instanceof MiddlewareInterface) {
201
                    return $instance->process($request, $handler);
202
                }
203
204
                if ($instance instanceof RequestHandlerInterface) {
205
                    return $instance->handle($request);
206
                }
207
208
                if ($method !== null && method_exists($instance, $method)) {
209
                    return $instance->{$method}($request, $handler);
210
                }
211
212
                throw MiddlewareResolverException::forStringNotConvertedToInstance($this->handler);
213
            }
214
        };
215
    }
216
}
217