This repository has been archived by the owner on Jan 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 57
/
MiddlewarePipe.php
330 lines (294 loc) · 9.82 KB
/
MiddlewarePipe.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @see http://github.com/zendframework/zend-stratigility for the canonical source repository
* @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license https://github.com/zendframework/zend-stratigility/blob/master/LICENSE.md New BSD License
*/
namespace Zend\Stratigility;
use Closure;
use Interop\Http\Middleware\DelegateInterface;
use Interop\Http\Middleware\MiddlewareInterface as InteropMiddlewareInterface;
use Interop\Http\Middleware\ServerMiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use ReflectionFunction;
use ReflectionMethod;
use SplQueue;
use Zend\Stratigility\Exception\InvalidMiddlewareException;
/**
* Pipe middleware like unix pipes.
*
* This class implements a pipeline of middleware, which can be attached using
* the `pipe()` method, and is itself middleware.
*
* The request and response objects are decorated using the Zend\Stratigility\Http
* variants in this package, ensuring that the request may store arbitrary
* properties, and the response exposes the convenience `write()`, `end()`, and
* `isComplete()` methods.
*
* It creates an instance of `Next` internally, invoking it with the provided
* request and response instances; if no `$out` argument is provided, it will
* create a `FinalHandler` instance and pass that to `Next` as well.
*
* Inspired by Sencha Connect.
*
* @see https://github.com/sencha/connect
*/
class MiddlewarePipe implements MiddlewareInterface, ServerMiddlewareInterface
{
/**
* @var SplQueue
*/
protected $pipeline;
/**
* @var Response
*/
private $responsePrototype;
/**
* Constructor
*
* Initializes the queue.
*/
public function __construct()
{
$this->pipeline = new SplQueue();
}
/**
* Handle a request
*
* Takes the pipeline, creates a Next handler, and delegates to the
* Next handler.
*
* If $out is a callable, it is used as the "final handler" when
* $next has exhausted the pipeline; otherwise, a FinalHandler instance
* is created and passed to $next during initialization.
*
* @todo Make $out required for 2.0.0.
* @todo Remove trigger of deprecation notice when preparing for 2.0.0.
* @param Request $request
* @param Response $response
* @param callable $out
* @return Response
*/
public function __invoke(Request $request, Response $response, callable $out = null)
{
$request = $this->decorateRequest($request);
$response = $this->decorateResponse($response);
if (null === $out) {
trigger_error(sprintf(
'The third argument to %s() ($out) will be required starting with '
. 'Stratigility version 2; please see '
. 'https://docs.zendframework.com/zend-stratigility/migration/to-v2/ for '
. 'more details on how to update your application to remove this message.',
__CLASS__
), E_USER_DEPRECATED);
}
$done = $out ?: new FinalHandler([], $response);
$next = new Next($this->pipeline, $done);
$next->setResponsePrototype($response);
$result = $next($request, $response);
return ($result instanceof Response ? $result : $response);
}
/**
* http-interop invocation: single-pass with delegate.
*
* Executes the internal pipeline, passing $delegate as the "final
* handler" in cases when the pipeline exhausts itself.
*
* @param Request $request
* @param DelegateInterface $delegate
* @return Response
*/
public function process(Request $request, DelegateInterface $delegate)
{
$response = $this->responsePrototype;
$next = new Next($this->pipeline, $delegate);
if ($response) {
$next->setResponsePrototype($response);
}
$result = $next->process($request);
return ($result instanceof Response ? $result : $response);
}
/**
* Attach middleware to the pipeline.
*
* Each middleware can be associated with a particular path; if that
* path is matched when that middleware is invoked, it will be processed;
* otherwise it is skipped.
*
* No path means it should be executed every request cycle.
*
* A handler CAN implement MiddlewareInterface, but MUST be callable.
*
* Handlers with arity >= 4 or those implementing ErrorMiddlewareInterface
* are considered error handlers, and will be executed when a handler calls
* $next with an error or raises an exception.
*
* @see MiddlewareInterface
* @see ErrorMiddlewareInterface
* @see Next
* @param string|callable|object $path Either a URI path prefix, or middleware.
* @param null|callable|object $middleware Middleware
* @return self
*/
public function pipe($path, $middleware = null)
{
if (null === $middleware
&& $this->isValidMiddleware($path)
) {
$middleware = $path;
$path = '/';
}
// Decorate callable middleware as http-interop middleware if we have
// a response prototype present.
if (is_callable($middleware)
&& ! $this->isInteropMiddleware($middleware)
&& ! $this->isErrorMiddleware($middleware)
) {
$middleware = $this->decorateCallableMiddleware($middleware);
}
// Ensure we have a valid handler
if (! $this->isValidMiddleware($middleware)) {
throw InvalidMiddlewareException::fromValue($middleware);
}
$this->pipeline->enqueue(new Route(
$this->normalizePipePath($path),
$middleware
));
// @todo Trigger event here with route details?
return $this;
}
/**
* @param Response $prototype
* @return void
*/
public function setResponsePrototype(Response $prototype)
{
$this->responsePrototype = $prototype;
}
/**
* @return bool
*/
public function hasResponsePrototype()
{
return $this->responsePrototype instanceof Response;
}
/**
* Normalize a path used when defining a pipe
*
* Strips trailing slashes, and prepends a slash.
*
* @param string $path
* @return string
*/
private function normalizePipePath($path)
{
// Prepend slash if missing
if (empty($path) || $path[0] !== '/') {
$path = '/' . $path;
}
// Trim trailing slash if present
if (strlen($path) > 1 && '/' === substr($path, -1)) {
$path = rtrim($path, '/');
}
return $path;
}
/**
* Decorate the Request instance
*
* @param Request $request
* @return Http\Request
*/
private function decorateRequest(Request $request)
{
if ($request instanceof Http\Request) {
return $request;
}
return new Http\Request($request);
}
/**
* Decorate the Response instance
*
* @param Response $response
* @return Http\Response
*/
private function decorateResponse(Response $response)
{
if ($response instanceof Http\Response) {
return $response;
}
return new Http\Response($response);
}
/**
* Is the provided middleware argument valid middleware?
*
* @param mixed $middleware
* @return bool
*/
private function isValidMiddleware($middleware)
{
return is_callable($middleware)
|| $middleware instanceof ServerMiddlewareInterface
|| $middleware instanceof InteropMiddlewareInterface;
}
/**
* Is the provided middleware argument http-interop middleware?
*
* @param mixed $middleware
* @return bool
*/
private function isInteropMiddleware($middleware)
{
return ! is_callable($middleware)
&& ($middleware instanceof ServerMiddlewareInterface
|| $middleware instanceof InteropMiddlewareInterface);
}
/**
* Is the middleware error middleware?
*
* @todo Remove for 2.0.0
* @param mixed $middleware
* @return bool
*/
private function isErrorMiddleware($middleware)
{
return $middleware instanceof ErrorMiddlewareInterface
|| Utils::getArity($middleware) >= 4;
}
/**
* @param callable $middleware
* @return ServerMiddlewareInterface|callable Callable, if unable to
* decorate the middleware; ServerMiddlewareInterface if it can.
*/
private function decorateCallableMiddleware(callable $middleware)
{
$r = $this->getReflectionFunction($middleware);
$paramsCount = $r->getNumberOfParameters();
if ($paramsCount !== 2) {
return $this->responsePrototype
? new Middleware\CallableMiddlewareWrapper($middleware, $this->responsePrototype)
: $middleware;
}
$params = $r->getParameters();
$type = $params[1]->getClass();
if (! $type || $type->getName() !== DelegateInterface::class) {
return $this->responsePrototype
? new Middleware\CallableMiddlewareWrapper($middleware, $this->responsePrototype)
: $middleware;
}
return new Middleware\CallableInteropMiddlewareWrapper($middleware);
}
/**
* @param callable $middleware
* @return \ReflectionFunctionAbstract
*/
private function getReflectionFunction(callable $middleware)
{
if ($middleware instanceof Closure || ! is_object($middleware)) {
return new ReflectionFunction($middleware);
}
return new ReflectionMethod($middleware, '__invoke');
}
}