Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
 
12
namespace Symfony\Component\HttpKernel;
13
 
14
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\RequestStack;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
19
use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface;
20
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
21
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
22
use Symfony\Component\HttpKernel\Event\ControllerEvent;
23
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
24
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
25
use Symfony\Component\HttpKernel\Event\RequestEvent;
26
use Symfony\Component\HttpKernel\Event\ResponseEvent;
27
use Symfony\Component\HttpKernel\Event\TerminateEvent;
28
use Symfony\Component\HttpKernel\Event\ViewEvent;
29
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
30
use Symfony\Component\HttpKernel\Exception\ControllerDoesNotReturnResponseException;
31
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
34
 
35
// Help opcache.preload discover always-needed symbols
36
class_exists(ControllerArgumentsEvent::class);
37
class_exists(ControllerEvent::class);
38
class_exists(ExceptionEvent::class);
39
class_exists(FinishRequestEvent::class);
40
class_exists(RequestEvent::class);
41
class_exists(ResponseEvent::class);
42
class_exists(TerminateEvent::class);
43
class_exists(ViewEvent::class);
44
class_exists(KernelEvents::class);
45
 
46
/**
47
 * HttpKernel notifies events to convert a Request object to a Response one.
48
 *
49
 * @author Fabien Potencier <fabien@symfony.com>
50
 */
51
class HttpKernel implements HttpKernelInterface, TerminableInterface
52
{
53
    protected $dispatcher;
54
    protected $resolver;
55
    protected $requestStack;
56
    private ArgumentResolverInterface $argumentResolver;
57
    private bool $handleAllThrowables;
58
 
59
    public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver, RequestStack $requestStack = null, ArgumentResolverInterface $argumentResolver = null, bool $handleAllThrowables = false)
60
    {
61
        $this->dispatcher = $dispatcher;
62
        $this->resolver = $resolver;
63
        $this->requestStack = $requestStack ?? new RequestStack();
64
        $this->argumentResolver = $argumentResolver ?? new ArgumentResolver();
65
        $this->handleAllThrowables = $handleAllThrowables;
66
    }
67
 
68
    public function handle(Request $request, int $type = HttpKernelInterface::MAIN_REQUEST, bool $catch = true): Response
69
    {
70
        $request->headers->set('X-Php-Ob-Level', (string) ob_get_level());
71
 
72
        $this->requestStack->push($request);
73
        try {
74
            return $this->handleRaw($request, $type);
75
        } catch (\Throwable $e) {
76
            if ($e instanceof \Error && !$this->handleAllThrowables) {
77
                throw $e;
78
            }
79
 
80
            if ($e instanceof RequestExceptionInterface) {
81
                $e = new BadRequestHttpException($e->getMessage(), $e);
82
            }
83
            if (false === $catch) {
84
                $this->finishRequest($request, $type);
85
 
86
                throw $e;
87
            }
88
 
89
            return $this->handleThrowable($e, $request, $type);
90
        } finally {
91
            $this->requestStack->pop();
92
        }
93
    }
94
 
95
    public function terminate(Request $request, Response $response)
96
    {
97
        $this->dispatcher->dispatch(new TerminateEvent($this, $request, $response), KernelEvents::TERMINATE);
98
    }
99
 
100
    /**
101
     * @internal
102
     */
103
    public function terminateWithException(\Throwable $exception, Request $request = null)
104
    {
105
        if (!$request ??= $this->requestStack->getMainRequest()) {
106
            throw $exception;
107
        }
108
 
109
        if ($pop = $request !== $this->requestStack->getMainRequest()) {
110
            $this->requestStack->push($request);
111
        }
112
 
113
        try {
114
            $response = $this->handleThrowable($exception, $request, self::MAIN_REQUEST);
115
        } finally {
116
            if ($pop) {
117
                $this->requestStack->pop();
118
            }
119
        }
120
 
121
        $response->sendHeaders();
122
        $response->sendContent();
123
 
124
        $this->terminate($request, $response);
125
    }
126
 
127
    /**
128
     * Handles a request to convert it to a response.
129
     *
130
     * Exceptions are not caught.
131
     *
132
     * @throws \LogicException       If one of the listener does not behave as expected
133
     * @throws NotFoundHttpException When controller cannot be found
134
     */
135
    private function handleRaw(Request $request, int $type = self::MAIN_REQUEST): Response
136
    {
137
        // request
138
        $event = new RequestEvent($this, $request, $type);
139
        $this->dispatcher->dispatch($event, KernelEvents::REQUEST);
140
 
141
        if ($event->hasResponse()) {
142
            return $this->filterResponse($event->getResponse(), $request, $type);
143
        }
144
 
145
        // load controller
146
        if (false === $controller = $this->resolver->getController($request)) {
147
            throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". The route is wrongly configured.', $request->getPathInfo()));
148
        }
149
 
150
        $event = new ControllerEvent($this, $controller, $request, $type);
151
        $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER);
152
        $controller = $event->getController();
153
 
154
        // controller arguments
155
        $arguments = $this->argumentResolver->getArguments($request, $controller, $event->getControllerReflector());
156
 
157
        $event = new ControllerArgumentsEvent($this, $event, $arguments, $request, $type);
158
        $this->dispatcher->dispatch($event, KernelEvents::CONTROLLER_ARGUMENTS);
159
        $controller = $event->getController();
160
        $arguments = $event->getArguments();
161
 
162
        // call controller
163
        $response = $controller(...$arguments);
164
 
165
        // view
166
        if (!$response instanceof Response) {
167
            $event = new ViewEvent($this, $request, $type, $response, $event);
168
            $this->dispatcher->dispatch($event, KernelEvents::VIEW);
169
 
170
            if ($event->hasResponse()) {
171
                $response = $event->getResponse();
172
            } else {
173
                $msg = sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.', $this->varToString($response));
174
 
175
                // the user may have forgotten to return something
176
                if (null === $response) {
177
                    $msg .= ' Did you forget to add a return statement somewhere in your controller?';
178
                }
179
 
180
                throw new ControllerDoesNotReturnResponseException($msg, $controller, __FILE__, __LINE__ - 17);
181
            }
182
        }
183
 
184
        return $this->filterResponse($response, $request, $type);
185
    }
186
 
187
    /**
188
     * Filters a response object.
189
     *
190
     * @throws \RuntimeException if the passed object is not a Response instance
191
     */
192
    private function filterResponse(Response $response, Request $request, int $type): Response
193
    {
194
        $event = new ResponseEvent($this, $request, $type, $response);
195
 
196
        $this->dispatcher->dispatch($event, KernelEvents::RESPONSE);
197
 
198
        $this->finishRequest($request, $type);
199
 
200
        return $event->getResponse();
201
    }
202
 
203
    /**
204
     * Publishes the finish request event, then pop the request from the stack.
205
     *
206
     * Note that the order of the operations is important here, otherwise
207
     * operations such as {@link RequestStack::getParentRequest()} can lead to
208
     * weird results.
209
     */
210
    private function finishRequest(Request $request, int $type)
211
    {
212
        $this->dispatcher->dispatch(new FinishRequestEvent($this, $request, $type), KernelEvents::FINISH_REQUEST);
213
    }
214
 
215
    /**
216
     * Handles a throwable by trying to convert it to a Response.
217
     */
218
    private function handleThrowable(\Throwable $e, Request $request, int $type): Response
219
    {
220
        $event = new ExceptionEvent($this, $request, $type, $e);
221
        $this->dispatcher->dispatch($event, KernelEvents::EXCEPTION);
222
 
223
        // a listener might have replaced the exception
224
        $e = $event->getThrowable();
225
 
226
        if (!$event->hasResponse()) {
227
            $this->finishRequest($request, $type);
228
 
229
            throw $e;
230
        }
231
 
232
        $response = $event->getResponse();
233
 
234
        // the developer asked for a specific status code
235
        if (!$event->isAllowingCustomResponseCode() && !$response->isClientError() && !$response->isServerError() && !$response->isRedirect()) {
236
            // ensure that we actually have an error response
237
            if ($e instanceof HttpExceptionInterface) {
238
                // keep the HTTP status code and headers
239
                $response->setStatusCode($e->getStatusCode());
240
                $response->headers->add($e->getHeaders());
241
            } else {
242
                $response->setStatusCode(500);
243
            }
244
        }
245
 
246
        try {
247
            return $this->filterResponse($response, $request, $type);
248
        } catch (\Throwable $e) {
249
            if ($e instanceof \Error && !$this->handleAllThrowables) {
250
                throw $e;
251
            }
252
 
253
            return $response;
254
        }
255
    }
256
 
257
    /**
258
     * Returns a human-readable string for the specified variable.
259
     */
260
    private function varToString(mixed $var): string
261
    {
262
        if (\is_object($var)) {
263
            return sprintf('an object of type %s', $var::class);
264
        }
265
 
266
        if (\is_array($var)) {
267
            $a = [];
268
            foreach ($var as $k => $v) {
269
                $a[] = sprintf('%s => ...', $k);
270
            }
271
 
272
            return sprintf('an array ([%s])', mb_substr(implode(', ', $a), 0, 255));
273
        }
274
 
275
        if (\is_resource($var)) {
276
            return sprintf('a resource (%s)', get_resource_type($var));
277
        }
278
 
279
        if (null === $var) {
280
            return 'null';
281
        }
282
 
283
        if (false === $var) {
284
            return 'a boolean value (false)';
285
        }
286
 
287
        if (true === $var) {
288
            return 'a boolean value (true)';
289
        }
290
 
291
        if (\is_string($var)) {
292
            return sprintf('a string ("%s%s")', mb_substr($var, 0, 255), mb_strlen($var) > 255 ? '...' : '');
293
        }
294
 
295
        if (is_numeric($var)) {
296
            return sprintf('a number (%s)', (string) $var);
297
        }
298
 
299
        return (string) $var;
300
    }
301
}