This repository has been archived by the owner on Jul 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 718
/
Application.php
506 lines (449 loc) · 16.3 KB
/
Application.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
<?php
/*
* This file is part of the Silex framework.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Silex;
use Pimple\Container;
use Pimple\ServiceProviderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\TerminableInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Silex\Api\BootableProviderInterface;
use Silex\Api\EventListenerProviderInterface;
use Silex\Api\ControllerProviderInterface;
use Silex\Provider\ExceptionHandlerServiceProvider;
use Silex\Provider\RoutingServiceProvider;
use Silex\Provider\HttpKernelServiceProvider;
/**
* The Silex framework class.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Application extends Container implements HttpKernelInterface, TerminableInterface
{
const VERSION = '2.3.1-DEV';
const EARLY_EVENT = 512;
const LATE_EVENT = -512;
protected $providers = [];
protected $booted = false;
/**
* Instantiate a new Application.
*
* Objects and parameters can be passed as argument to the constructor.
*
* @param array $values the parameters or objects
*/
public function __construct(array $values = [])
{
parent::__construct();
$this['request.http_port'] = 80;
$this['request.https_port'] = 443;
$this['debug'] = false;
$this['charset'] = 'UTF-8';
$this['logger'] = null;
$this->register(new HttpKernelServiceProvider());
$this->register(new RoutingServiceProvider());
$this->register(new ExceptionHandlerServiceProvider());
foreach ($values as $key => $value) {
$this[$key] = $value;
}
}
/**
* Registers a service provider.
*
* @param ServiceProviderInterface $provider A ServiceProviderInterface instance
* @param array $values An array of values that customizes the provider
*
* @return Application
*/
public function register(ServiceProviderInterface $provider, array $values = [])
{
$this->providers[] = $provider;
parent::register($provider, $values);
return $this;
}
/**
* Boots all service providers.
*
* This method is automatically called by handle(), but you can use it
* to boot all service providers when not handling a request.
*/
public function boot()
{
if ($this->booted) {
return;
}
$this->booted = true;
foreach ($this->providers as $provider) {
if ($provider instanceof EventListenerProviderInterface) {
$provider->subscribe($this, $this['dispatcher']);
}
if ($provider instanceof BootableProviderInterface) {
$provider->boot($this);
}
}
}
/**
* Maps a pattern to a callable.
*
* You can optionally specify HTTP methods that should be matched.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function match($pattern, $to = null)
{
return $this['controllers']->match($pattern, $to);
}
/**
* Maps a GET request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function get($pattern, $to = null)
{
return $this['controllers']->get($pattern, $to);
}
/**
* Maps a POST request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function post($pattern, $to = null)
{
return $this['controllers']->post($pattern, $to);
}
/**
* Maps a PUT request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function put($pattern, $to = null)
{
return $this['controllers']->put($pattern, $to);
}
/**
* Maps a DELETE request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function delete($pattern, $to = null)
{
return $this['controllers']->delete($pattern, $to);
}
/**
* Maps an OPTIONS request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function options($pattern, $to = null)
{
return $this['controllers']->options($pattern, $to);
}
/**
* Maps a PATCH request to a callable.
*
* @param string $pattern Matched route pattern
* @param mixed $to Callback that returns the response when matched
*
* @return Controller
*/
public function patch($pattern, $to = null)
{
return $this['controllers']->patch($pattern, $to);
}
/**
* Adds an event listener that listens on the specified events.
*
* @param string $eventName The event to listen on
* @param callable $callback The listener
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function on($eventName, $callback, $priority = 0)
{
if ($this->booted) {
$this['dispatcher']->addListener($eventName, $this['callback_resolver']->resolveCallback($callback), $priority);
return;
}
$this->extend('dispatcher', function (EventDispatcherInterface $dispatcher, $app) use ($callback, $priority, $eventName) {
$dispatcher->addListener($eventName, $app['callback_resolver']->resolveCallback($callback), $priority);
return $dispatcher;
});
}
/**
* Registers a before filter.
*
* Before filters are run before any route has been matched.
*
* @param mixed $callback Before filter callback
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function before($callback, $priority = 0)
{
$app = $this;
$this->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($callback, $app) {
if (!$event->isMasterRequest()) {
return;
}
$ret = call_user_func($app['callback_resolver']->resolveCallback($callback), $event->getRequest(), $app);
if ($ret instanceof Response) {
$event->setResponse($ret);
}
}, $priority);
}
/**
* Registers an after filter.
*
* After filters are run after the controller has been executed.
*
* @param mixed $callback After filter callback
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function after($callback, $priority = 0)
{
$app = $this;
$this->on(KernelEvents::RESPONSE, function (FilterResponseEvent $event) use ($callback, $app) {
if (!$event->isMasterRequest()) {
return;
}
$response = call_user_func($app['callback_resolver']->resolveCallback($callback), $event->getRequest(), $event->getResponse(), $app);
if ($response instanceof Response) {
$event->setResponse($response);
} elseif (null !== $response) {
throw new \RuntimeException('An after middleware returned an invalid response value. Must return null or an instance of Response.');
}
}, $priority);
}
/**
* Registers a finish filter.
*
* Finish filters are run after the response has been sent.
*
* @param mixed $callback Finish filter callback
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function finish($callback, $priority = 0)
{
$app = $this;
$this->on(KernelEvents::TERMINATE, function (PostResponseEvent $event) use ($callback, $app) {
call_user_func($app['callback_resolver']->resolveCallback($callback), $event->getRequest(), $event->getResponse(), $app);
}, $priority);
}
/**
* Aborts the current request by sending a proper HTTP error.
*
* @param int $statusCode The HTTP status code
* @param string $message The status message
* @param array $headers An array of HTTP headers
*/
public function abort($statusCode, $message = '', array $headers = [])
{
throw new HttpException($statusCode, $message, null, $headers);
}
/**
* Registers an error handler.
*
* Error handlers are simple callables which take a single Exception
* as an argument. If a controller throws an exception, an error handler
* can return a specific response.
*
* When an exception occurs, all handlers will be called, until one returns
* something (a string or a Response object), at which point that will be
* returned to the client.
*
* For this reason you should add logging handlers before output handlers.
*
* @param mixed $callback Error handler callback, takes an Exception argument
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to -8)
*/
public function error($callback, $priority = -8)
{
$this->on(KernelEvents::EXCEPTION, new ExceptionListenerWrapper($this, $callback), $priority);
}
/**
* Registers a view handler.
*
* View handlers are simple callables which take a controller result and the
* request as arguments, whenever a controller returns a value that is not
* an instance of Response. When this occurs, all suitable handlers will be
* called, until one returns a Response object.
*
* @param mixed $callback View handler callback
* @param int $priority The higher this value, the earlier an event
* listener will be triggered in the chain (defaults to 0)
*/
public function view($callback, $priority = 0)
{
$this->on(KernelEvents::VIEW, new ViewListenerWrapper($this, $callback), $priority);
}
/**
* Flushes the controller collection.
*/
public function flush()
{
$this['routes']->addCollection($this['controllers']->flush());
}
/**
* Redirects the user to another URL.
*
* @param string $url The URL to redirect to
* @param int $status The status code (302 by default)
*
* @return RedirectResponse
*/
public function redirect($url, $status = 302)
{
return new RedirectResponse($url, $status);
}
/**
* Creates a streaming response.
*
* @param mixed $callback A valid PHP callback
* @param int $status The response status code
* @param array $headers An array of response headers
*
* @return StreamedResponse
*/
public function stream($callback = null, $status = 200, array $headers = [])
{
return new StreamedResponse($callback, $status, $headers);
}
/**
* Escapes a text for HTML.
*
* @param string $text The input text to be escaped
* @param int $flags The flags (@see htmlspecialchars)
* @param string $charset The charset
* @param bool $doubleEncode Whether to try to avoid double escaping or not
*
* @return string Escaped text
*/
public function escape($text, $flags = ENT_COMPAT, $charset = null, $doubleEncode = true)
{
return htmlspecialchars($text, $flags, $charset ?: $this['charset'], $doubleEncode);
}
/**
* Convert some data into a JSON response.
*
* @param mixed $data The response data
* @param int $status The response status code
* @param array $headers An array of response headers
*
* @return JsonResponse
*/
public function json($data = [], $status = 200, array $headers = [])
{
return new JsonResponse($data, $status, $headers);
}
/**
* Sends a file.
*
* @param \SplFileInfo|string $file The file to stream
* @param int $status The response status code
* @param array $headers An array of response headers
* @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
*
* @return BinaryFileResponse
*/
public function sendFile($file, $status = 200, array $headers = [], $contentDisposition = null)
{
return new BinaryFileResponse($file, $status, $headers, true, $contentDisposition);
}
/**
* Mounts controllers under the given route prefix.
*
* @param string $prefix The route prefix
* @param ControllerCollection|callable|ControllerProviderInterface $controllers A ControllerCollection, a callable, or a ControllerProviderInterface instance
*
* @return Application
*
* @throws \LogicException
*/
public function mount($prefix, $controllers)
{
if ($controllers instanceof ControllerProviderInterface) {
$connectedControllers = $controllers->connect($this);
if (!$connectedControllers instanceof ControllerCollection) {
throw new \LogicException(sprintf('The method "%s::connect" must return a "ControllerCollection" instance. Got: "%s"', get_class($controllers), is_object($connectedControllers) ? get_class($connectedControllers) : gettype($connectedControllers)));
}
$controllers = $connectedControllers;
} elseif (!$controllers instanceof ControllerCollection && !is_callable($controllers)) {
throw new \LogicException('The "mount" method takes either a "ControllerCollection" instance, "ControllerProviderInterface" instance, or a callable.');
}
$this['controllers']->mount($prefix, $controllers);
return $this;
}
/**
* Handles the request and delivers the response.
*
* @param Request|null $request Request to process
*/
public function run(Request $request = null)
{
if (null === $request) {
$request = Request::createFromGlobals();
}
$response = $this->handle($request);
$response->send();
$this->terminate($request, $response);
}
/**
* {@inheritdoc}
*
* If you call this method directly instead of run(), you must call the
* terminate() method yourself if you want the finish filters to be run.
*/
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
if (!$this->booted) {
$this->boot();
}
$this->flush();
return $this['kernel']->handle($request, $type, $catch);
}
/**
* {@inheritdoc}
*/
public function terminate(Request $request, Response $response)
{
$this['kernel']->terminate($request, $response);
}
}