-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathAbstractController.php
452 lines (388 loc) · 17.1 KB
/
AbstractController.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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Controller;
use Psr\Container\ContainerInterface;
use Psr\Link\EvolvableLinkInterface;
use Psr\Link\LinkInterface;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Exception\SessionNotFoundException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\FlashBagAwareSessionInterface;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
use Symfony\Component\WebLink\GenericLinkProvider;
use Symfony\Component\WebLink\HttpHeaderSerializer;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
use Twig\Environment;
/**
* Provides shortcuts for HTTP-related features in controllers.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class AbstractController implements ServiceSubscriberInterface
{
protected ContainerInterface $container;
#[Required]
public function setContainer(ContainerInterface $container): ?ContainerInterface
{
$previous = $this->container ?? null;
$this->container = $container;
return $previous;
}
/**
* Gets a container parameter by its name.
*/
protected function getParameter(string $name): array|bool|string|int|float|\UnitEnum|null
{
if (!$this->container->has('parameter_bag')) {
throw new ServiceNotFoundException('parameter_bag.', null, null, [], \sprintf('The "%s::getParameter()" method is missing a parameter bag to work properly. Did you forget to register your controller as a service subscriber? This can be fixed either by using autoconfiguration or by manually wiring a "parameter_bag" in the service locator passed to the controller.', static::class));
}
return $this->container->get('parameter_bag')->get($name);
}
public static function getSubscribedServices(): array
{
return [
'router' => '?'.RouterInterface::class,
'request_stack' => '?'.RequestStack::class,
'http_kernel' => '?'.HttpKernelInterface::class,
'serializer' => '?'.SerializerInterface::class,
'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
'twig' => '?'.Environment::class,
'form.factory' => '?'.FormFactoryInterface::class,
'security.token_storage' => '?'.TokenStorageInterface::class,
'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
'parameter_bag' => '?'.ContainerBagInterface::class,
'web_link.http_header_serializer' => '?'.HttpHeaderSerializer::class,
];
}
/**
* Generates a URL from the given parameters.
*
* @see UrlGeneratorInterface
*/
protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string
{
return $this->container->get('router')->generate($route, $parameters, $referenceType);
}
/**
* Forwards the request to another controller.
*
* @param string $controller The controller name (a string like "App\Controller\PostController::index" or "App\Controller\PostController" if it is invokable)
*/
protected function forward(string $controller, array $path = [], array $query = []): Response
{
$request = $this->container->get('request_stack')->getCurrentRequest();
$path['_controller'] = $controller;
$subRequest = $request->duplicate($query, null, $path);
return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
/**
* Returns a RedirectResponse to the given URL.
*
* @param int $status The HTTP status code (302 "Found" by default)
*/
protected function redirect(string $url, int $status = 302): RedirectResponse
{
return new RedirectResponse($url, $status);
}
/**
* Returns a RedirectResponse to the given route with the given parameters.
*
* @param int $status The HTTP status code (302 "Found" by default)
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse
{
return $this->redirect($this->generateUrl($route, $parameters), $status);
}
/**
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
*
* @param int $status The HTTP status code (200 "OK" by default)
*/
protected function json(mixed $data, int $status = 200, array $headers = [], array $context = []): JsonResponse
{
if ($this->container->has('serializer')) {
$json = $this->container->get('serializer')->serialize($data, 'json', array_merge([
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
], $context));
return new JsonResponse($json, $status, $headers, true);
}
return new JsonResponse($data, $status, $headers);
}
/**
* Returns a BinaryFileResponse object with original or customized file name and disposition header.
*/
protected function file(\SplFileInfo|string $file, ?string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
{
$response = new BinaryFileResponse($file);
$response->setContentDisposition($disposition, $fileName ?? $response->getFile()->getFilename());
return $response;
}
/**
* Adds a flash message to the current session for type.
*
* @throws \LogicException
*/
protected function addFlash(string $type, mixed $message): void
{
try {
$session = $this->container->get('request_stack')->getSession();
} catch (SessionNotFoundException $e) {
throw new \LogicException('You cannot use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".', 0, $e);
}
if (!$session instanceof FlashBagAwareSessionInterface) {
throw new \LogicException(\sprintf('You cannot use the addFlash method because class "%s" doesn\'t implement "%s".', get_debug_type($session), FlashBagAwareSessionInterface::class));
}
$session->getFlashBag()->add($type, $message);
}
/**
* Checks if the attribute is granted against the current authentication token and optionally supplied subject.
*
* @throws \LogicException
*/
protected function isGranted(mixed $attribute, mixed $subject = null): bool
{
if (!$this->container->has('security.authorization_checker')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
return $this->container->get('security.authorization_checker')->isGranted($attribute, $subject);
}
/**
* Throws an exception unless the attribute is granted against the current authentication token and optionally
* supplied subject.
*
* @throws AccessDeniedException
*/
protected function denyAccessUnlessGranted(mixed $attribute, mixed $subject = null, string $message = 'Access Denied.'): void
{
if (!$this->isGranted($attribute, $subject)) {
$exception = $this->createAccessDeniedException($message);
$exception->setAttributes([$attribute]);
$exception->setSubject($subject);
throw $exception;
}
}
/**
* Returns a rendered view.
*
* Forms found in parameters are auto-cast to form views.
*/
protected function renderView(string $view, array $parameters = []): string
{
return $this->doRenderView($view, null, $parameters, __FUNCTION__);
}
/**
* Returns a rendered block from a view.
*
* Forms found in parameters are auto-cast to form views.
*/
protected function renderBlockView(string $view, string $block, array $parameters = []): string
{
return $this->doRenderView($view, $block, $parameters, __FUNCTION__);
}
/**
* Renders a view.
*
* If an invalid form is found in the list of parameters, a 422 status code is returned.
* Forms found in parameters are auto-cast to form views.
*/
protected function render(string $view, array $parameters = [], ?Response $response = null): Response
{
return $this->doRender($view, null, $parameters, $response, __FUNCTION__);
}
/**
* Renders a block in a view.
*
* If an invalid form is found in the list of parameters, a 422 status code is returned.
* Forms found in parameters are auto-cast to form views.
*/
protected function renderBlock(string $view, string $block, array $parameters = [], ?Response $response = null): Response
{
return $this->doRender($view, $block, $parameters, $response, __FUNCTION__);
}
/**
* Streams a view.
*/
protected function stream(string $view, array $parameters = [], ?StreamedResponse $response = null): StreamedResponse
{
if (!$this->container->has('twig')) {
throw new \LogicException('You cannot use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
}
$twig = $this->container->get('twig');
$callback = function () use ($twig, $view, $parameters) {
$twig->display($view, $parameters);
};
if (null === $response) {
return new StreamedResponse($callback);
}
$response->setCallback($callback);
return $response;
}
/**
* Returns a NotFoundHttpException.
*
* This will result in a 404 response code. Usage example:
*
* throw $this->createNotFoundException('Page not found!');
*/
protected function createNotFoundException(string $message = 'Not Found', ?\Throwable $previous = null): NotFoundHttpException
{
return new NotFoundHttpException($message, $previous);
}
/**
* Returns an AccessDeniedException.
*
* This will result in a 403 response code. Usage example:
*
* throw $this->createAccessDeniedException('Unable to access this page!');
*
* @throws \LogicException If the Security component is not available
*/
protected function createAccessDeniedException(string $message = 'Access Denied.', ?\Throwable $previous = null): AccessDeniedException
{
if (!class_exists(AccessDeniedException::class)) {
throw new \LogicException('You cannot use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".');
}
return new AccessDeniedException($message, $previous);
}
/**
* Creates and returns a Form instance from the type of the form.
*/
protected function createForm(string $type, mixed $data = null, array $options = []): FormInterface
{
return $this->container->get('form.factory')->create($type, $data, $options);
}
/**
* Creates and returns a form builder instance.
*/
protected function createFormBuilder(mixed $data = null, array $options = []): FormBuilderInterface
{
return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options);
}
/**
* Get a user from the Security Token Storage.
*
* @throws \LogicException If SecurityBundle is not available
*
* @see TokenInterface::getUser()
*/
protected function getUser(): ?UserInterface
{
if (!$this->container->has('security.token_storage')) {
throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".');
}
if (null === $token = $this->container->get('security.token_storage')->getToken()) {
return null;
}
return $token->getUser();
}
/**
* Checks the validity of a CSRF token.
*
* @param string $id The id used when generating the token
* @param string|null $token The actual token sent with the request that should be validated
*/
protected function isCsrfTokenValid(string $id, #[\SensitiveParameter] ?string $token): bool
{
if (!$this->container->has('security.csrf.token_manager')) {
throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".');
}
return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token));
}
/**
* Adds a Link HTTP header to the current response.
*
* @see https://tools.ietf.org/html/rfc5988
*/
protected function addLink(Request $request, LinkInterface $link): void
{
if (!class_exists(AddLinkHeaderListener::class)) {
throw new \LogicException('You cannot use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
}
if (null === $linkProvider = $request->attributes->get('_links')) {
$request->attributes->set('_links', new GenericLinkProvider([$link]));
return;
}
$request->attributes->set('_links', $linkProvider->withLink($link));
}
/**
* @param LinkInterface[] $links
*/
protected function sendEarlyHints(iterable $links = [], ?Response $response = null): Response
{
if (!$this->container->has('web_link.http_header_serializer')) {
throw new \LogicException('You cannot use the "sendEarlyHints" method if the WebLink component is not available. Try running "composer require symfony/web-link".');
}
$response ??= new Response();
$populatedLinks = [];
foreach ($links as $link) {
if ($link instanceof EvolvableLinkInterface && !$link->getRels()) {
$link = $link->withRel('preload');
}
$populatedLinks[] = $link;
}
$response->headers->set('Link', $this->container->get('web_link.http_header_serializer')->serialize($populatedLinks), false);
$response->sendHeaders(103);
return $response;
}
private function doRenderView(string $view, ?string $block, array $parameters, string $method): string
{
if (!$this->container->has('twig')) {
throw new \LogicException(\sprintf('You cannot use the "%s" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".', $method));
}
foreach ($parameters as $k => $v) {
if ($v instanceof FormInterface) {
$parameters[$k] = $v->createView();
}
}
if (null !== $block) {
return $this->container->get('twig')->load($view)->renderBlock($block, $parameters);
}
return $this->container->get('twig')->render($view, $parameters);
}
private function doRender(string $view, ?string $block, array $parameters, ?Response $response, string $method): Response
{
$content = $this->doRenderView($view, $block, $parameters, $method);
$response ??= new Response();
if (200 === $response->getStatusCode()) {
foreach ($parameters as $v) {
if ($v instanceof FormInterface && $v->isSubmitted() && !$v->isValid()) {
$response->setStatusCode(422);
break;
}
}
}
$response->setContent($content);
return $response;
}
}