-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
ApplicationConfigInjectionDelegator.php
306 lines (285 loc) · 10.2 KB
/
ApplicationConfigInjectionDelegator.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
<?php
declare(strict_types=1);
namespace Mezzio\Container;
use Mezzio\Application;
use Mezzio\Exception\InvalidArgumentException;
use Mezzio\MiddlewareFactoryInterface;
use Mezzio\Router\Route;
use Psr\Container\ContainerInterface;
use SplPriorityQueue;
use function array_key_exists;
use function array_map;
use function array_reduce;
use function gettype;
use function is_array;
use function is_int;
use function is_object;
use function is_string;
use function sprintf;
use const PHP_INT_MAX;
/**
* @psalm-import-type MiddlewareParam from MiddlewareFactoryInterface
* @psalm-type RouteSpec = array{
* path: non-empty-string,
* middleware: MiddlewareParam,
* allowed_methods?: list<string>,
* name?: null|non-empty-string,
* options?: array<string, mixed>,
* ...
* }
* @psalm-type MiddlewareSpec = array{
* middleware: MiddlewareParam,
* path?: non-empty-string,
* priority?: int,
* ...
* }
*/
class ApplicationConfigInjectionDelegator
{
/**
* Decorate an Application instance by injecting routes and/or middleware
* from configuration.
*
* @throws Exception\InvalidServiceException If the $callback produces
* something other than an `Application` instance, as the delegator cannot
* proceed with its operations.
*/
public function __invoke(ContainerInterface $container, string $serviceName, callable $callback): Application
{
$application = $callback();
if (! $application instanceof Application) {
throw new Exception\InvalidServiceException(sprintf(
'Delegator factory %s cannot operate on a %s; please map it only to the %s service',
self::class,
is_object($application) ? $application::class . ' instance' : gettype($application),
Application::class
));
}
if (! $container->has('config')) {
return $application;
}
/**
* The array shape is forced here as it cannot be inferred
*
* @psalm-var array{
* middleware_pipeline?: list<MiddlewareSpec>,
* routes?: array<int|non-empty-string, RouteSpec>,
* } $config
*/
$config = $container->get('config');
if (! empty($config['middleware_pipeline'])) {
self::injectPipelineFromConfig($application, (array) $config);
}
if (! empty($config['routes'])) {
self::injectRoutesFromConfig($application, (array) $config);
}
return $application;
}
/**
* Inject a middleware pipeline from the middleware_pipeline configuration.
*
* Inspects the configuration provided to determine if a middleware pipeline
* exists to inject in the application.
*
* Use the following configuration format:
*
* <code>
* return [
* 'middleware_pipeline' => [
* // An array of middleware to register with the pipeline.
* // entries to register prior to routing/dispatching...
* // - entry for \Mezzio\Router\Middleware\PathBasedRoutingMiddleware::class
* // - entry for \Mezzio\Router\Middleware\MethodNotAllowedMiddleware::class
* // - entry for \Mezzio\Router\Middleware\DispatchMiddleware::class
* // entries to register after routing/dispatching...
* ],
* ];
* </code>
*
* Each item in the middleware_pipeline array must be of the following
* specification:
*
* <code>
* [
* // required:
* 'middleware' => 'Name of middleware service, or a callable',
* // optional:
* 'path' => '/path/to/match',
* 'priority' => 1, // integer
* ]
* </code>
*
* Note that the `path` element can only be a literal.
*
* `priority` is used to shape the order in which middleware is piped to the
* application. Values are integers, with high values having higher priority
* (piped earlier), and low/negative values having lower priority (piped last).
* Default priority if none is specified is 1. Middleware with the same
* priority are piped in the order in which they appear.
*
* Middleware piped may be either callables or service names.
*
* Additionally, you can specify an array of callables or service names as
* the `middleware` value of a specification. Internally, this will create
* a `Laminas\Stratigility\MiddlewarePipe` instance, with the middleware
* specified piped in the order provided.
*
* @psalm-param array{
* middleware_pipeline?: list<MiddlewareSpec>,
* ...
* } $config
*/
public static function injectPipelineFromConfig(Application $application, array $config): void
{
if (empty($config['middleware_pipeline'])) {
return;
}
/**
* Create a priority queue from the specifications
*
* @psalm-var SplPriorityQueue<int, MiddlewareSpec> $queue
*/
$queue = array_reduce(
array_map(self::createCollectionMapper(), $config['middleware_pipeline']),
self::createPriorityQueueReducer(),
new SplPriorityQueue()
);
foreach ($queue as $spec) {
$path = $spec['path'] ?? '/';
$application->pipe($path, $spec['middleware']);
}
}
/**
* Inject routes from configuration.
*
* Introspects the provided configuration for routes to inject in the
* application instance.
*
* The following configuration structure can be used to define routes:
*
* <code>
* return [
* 'routes' => [
* [
* 'path' => '/path/to/match',
* 'middleware' => 'Middleware Service Name or Callable',
* 'allowed_methods' => ['GET', 'POST', 'PATCH'],
* 'options' => [
* 'stuff' => 'to',
* 'pass' => 'to',
* 'the' => 'underlying router',
* ],
* ],
* // etc.
* ],
* ];
* </code>
*
* Each route MUST have a path and middleware key at the minimum.
*
* The "allowed_methods" key may be omitted, can be either an array or the
* value of the Mezzio\Router\Route::HTTP_METHOD_ANY constant; any
* valid HTTP method token is allowed, which means you can specify custom HTTP
* methods as well.
*
* The "options" key may also be omitted, and its interpretation will be
* dependent on the underlying router used.
*
* @psalm-param array{routes?: array<array-key, RouteSpec>, ...} $config
* @throws InvalidArgumentException
*/
public static function injectRoutesFromConfig(Application $application, array $config): void
{
if (empty($config['routes']) || ! is_array($config['routes'])) {
return;
}
foreach ($config['routes'] as $key => $spec) {
if (! isset($spec['path']) || ! isset($spec['middleware'])) {
continue;
}
$methods = Route::HTTP_METHOD_ANY;
if (isset($spec['allowed_methods'])) {
$methods = $spec['allowed_methods'];
if (! is_array($methods)) {
throw new InvalidArgumentException(sprintf(
'Allowed HTTP methods for a route must be in form of an array; received "%s"',
gettype($methods)
));
}
}
$name = $spec['name'] ?? (is_string($key) ? $key : null);
$route = $application->route(
$spec['path'],
$spec['middleware'],
$methods,
$name
);
if (isset($spec['options'])) {
$options = $spec['options'];
if (! is_array($options)) {
throw new InvalidArgumentException(sprintf(
'Route options must be an array; received "%s"',
gettype($options)
));
}
$route->setOptions($options);
}
}
}
/**
* Create the collection mapping function.
*
* Returns a callable with the following signature:
*
* <code>
* function (array|string $item) : array
* </code>
*
* If the 'middleware' value is missing, or not viable as middleware, it
* raises an exception, to ensure the pipeline is built correctly.
*
* @return callable(MiddlewareSpec): MiddlewareSpec
* @throws InvalidArgumentException
*/
private static function createCollectionMapper(): callable
{
return static function ($item): array {
if (! is_array($item) || ! array_key_exists('middleware', $item)) {
throw new InvalidArgumentException(sprintf(
'Invalid pipeline specification received; must be an array'
. ' containing a middleware key; received %s',
is_object($item) ? $item::class : gettype($item)
));
}
return $item;
};
}
/**
* Create reducer function that will reduce an array to a priority queue.
*
* Creates and returns a function with the signature:
*
* <code>
* function (SplQueue $queue, array $item) : SplQueue
* </code>
*
* The function is useful to reduce an array of pipeline middleware to a
* priority queue.
*
* @return callable(SplPriorityQueue, MiddlewareSpec): SplPriorityQueue
*/
private static function createPriorityQueueReducer(): callable
{
// $serial is used to ensure that items of the same priority are enqueued
// in the order in which they are inserted.
$serial = PHP_INT_MAX;
return static function (SplPriorityQueue $queue, array $item) use (&$serial): SplPriorityQueue {
$priority = isset($item['priority']) && is_int($item['priority'])
? $item['priority']
: 1;
$queue->insert($item, [$priority, $serial]);
$serial -= 1;
return $queue;
};
}
}