mirror of
https://github.com/Combodo/iTop.git
synced 2026-04-28 13:08:45 +02:00
migration symfony 5 4 (#300)
* symfony 5.4 (diff dev) * symfony 5.4 (working) * symfony 5.4 (update autoload) * symfony 5.4 (remove swiftmailer mailer implementation) * symfony 5.4 (php doc and split Global accessor class) ### Impacted packages: composer require php:">=7.2.5 <8.0.0" symfony/console:5.4.* symfony/dotenv:5.4.* symfony/framework-bundle:5.4.* symfony/twig-bundle:5.4.* symfony/yaml:5.4.* --update-with-dependencies composer require symfony/stopwatch:5.4.* symfony/web-profiler-bundle:5.4.* --dev --update-with-dependencies
This commit is contained in:
@@ -11,41 +11,60 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Doctrine\Common\Persistence\ManagerRegistry as LegacyManagerRegistry;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Symfony\Component\DependencyInjection\ServiceSubscriberInterface;
|
||||
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\Form\FormView;
|
||||
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\SessionInterface;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\HttpKernel\HttpKernelInterface;
|
||||
use Symfony\Component\Messenger\Envelope;
|
||||
use Symfony\Component\Messenger\MessageBusInterface;
|
||||
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\Templating\EngineInterface;
|
||||
use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener;
|
||||
use Symfony\Component\WebLink\GenericLinkProvider;
|
||||
use Symfony\Contracts\Service\ServiceSubscriberInterface;
|
||||
use Twig\Environment;
|
||||
|
||||
/**
|
||||
* Provides common features needed in controllers.
|
||||
* Provides shortcuts for HTTP-related features in controllers.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
abstract class AbstractController implements ServiceSubscriberInterface
|
||||
{
|
||||
use ControllerTrait;
|
||||
|
||||
/**
|
||||
* @var ContainerInterface
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @required
|
||||
*/
|
||||
public function setContainer(ContainerInterface $container)
|
||||
public function setContainer(ContainerInterface $container): ?ContainerInterface
|
||||
{
|
||||
$previous = $this->container;
|
||||
$this->container = $container;
|
||||
@@ -53,6 +72,20 @@ abstract class AbstractController implements ServiceSubscriberInterface
|
||||
return $previous;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a container parameter by its name.
|
||||
*
|
||||
* @return array|bool|float|int|string|\UnitEnum|null
|
||||
*/
|
||||
protected function getParameter(string $name)
|
||||
{
|
||||
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()
|
||||
{
|
||||
return [
|
||||
@@ -62,12 +95,382 @@ abstract class AbstractController implements ServiceSubscriberInterface
|
||||
'serializer' => '?'.SerializerInterface::class,
|
||||
'session' => '?'.SessionInterface::class,
|
||||
'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class,
|
||||
'templating' => '?'.EngineInterface::class,
|
||||
'twig' => '?'.Environment::class,
|
||||
'doctrine' => '?'.(interface_exists(ManagerRegistry::class) ? ManagerRegistry::class : LegacyManagerRegistry::class),
|
||||
'doctrine' => '?'.ManagerRegistry::class, // to be removed in 6.0
|
||||
'form.factory' => '?'.FormFactoryInterface::class,
|
||||
'security.token_storage' => '?'.TokenStorageInterface::class,
|
||||
'security.csrf.token_manager' => '?'.CsrfTokenManagerInterface::class,
|
||||
'parameter_bag' => '?'.ContainerBagInterface::class,
|
||||
'message_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
|
||||
'messenger.default_bus' => '?'.MessageBusInterface::class, // to be removed in 6.0
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the service id is defined.
|
||||
*
|
||||
* @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
|
||||
*/
|
||||
protected function has(string $id): bool
|
||||
{
|
||||
trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, use method or constructor injection in your controller instead.', __METHOD__);
|
||||
|
||||
return $this->container->has($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a container service by its id.
|
||||
*
|
||||
* @return object The service
|
||||
*
|
||||
* @deprecated since Symfony 5.4, use method or constructor injection in your controller instead
|
||||
*/
|
||||
protected function get(string $id): object
|
||||
{
|
||||
trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, use method or constructor injection in your controller instead.', __METHOD__);
|
||||
|
||||
return $this->container->get($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 Bundle\BlogBundle\Controller\PostController::indexAction)
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
protected function json($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.
|
||||
*
|
||||
* @param \SplFileInfo|string $file File object or path to file to be sent as response
|
||||
*/
|
||||
protected function file($file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse
|
||||
{
|
||||
$response = new BinaryFileResponse($file);
|
||||
$response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a flash message to the current session for type.
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
protected function addFlash(string $type, $message): void
|
||||
{
|
||||
try {
|
||||
$this->container->get('request_stack')->getSession()->getFlashBag()->add($type, $message);
|
||||
} 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the attribute is granted against the current authentication token and optionally supplied subject.
|
||||
*
|
||||
* @throws \LogicException
|
||||
*/
|
||||
protected function isGranted($attribute, $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($attribute, $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.
|
||||
*/
|
||||
protected function renderView(string $view, array $parameters = []): string
|
||||
{
|
||||
if (!$this->container->has('twig')) {
|
||||
throw new \LogicException('You cannot use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
|
||||
}
|
||||
|
||||
return $this->container->get('twig')->render($view, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a view.
|
||||
*/
|
||||
protected function render(string $view, array $parameters = [], Response $response = null): Response
|
||||
{
|
||||
$content = $this->renderView($view, $parameters);
|
||||
|
||||
if (null === $response) {
|
||||
$response = new Response();
|
||||
}
|
||||
|
||||
$response->setContent($content);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a view and sets the appropriate status code when a form is listed in parameters.
|
||||
*
|
||||
* If an invalid form is found in the list of parameters, a 422 status code is returned.
|
||||
*/
|
||||
protected function renderForm(string $view, array $parameters = [], Response $response = null): Response
|
||||
{
|
||||
if (null === $response) {
|
||||
$response = new Response();
|
||||
}
|
||||
|
||||
foreach ($parameters as $k => $v) {
|
||||
if ($v instanceof FormView) {
|
||||
throw new \LogicException(sprintf('Passing a FormView to "%s::renderForm()" is not supported, pass directly the form instead for parameter "%s".', get_debug_type($this), $k));
|
||||
}
|
||||
|
||||
if (!$v instanceof FormInterface) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$parameters[$k] = $v->createView();
|
||||
|
||||
if (200 === $response->getStatusCode() && $v->isSubmitted() && !$v->isValid()) {
|
||||
$response->setStatusCode(422);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->render($view, $parameters, $response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, $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($data = null, array $options = []): FormBuilderInterface
|
||||
{
|
||||
return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to return the Doctrine Registry service.
|
||||
*
|
||||
* @throws \LogicException If DoctrineBundle is not available
|
||||
*
|
||||
* @deprecated since Symfony 5.4, inject an instance of ManagerRegistry in your controller instead
|
||||
*/
|
||||
protected function getDoctrine(): ManagerRegistry
|
||||
{
|
||||
trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, inject an instance of ManagerRegistry in your controller instead.', __METHOD__);
|
||||
|
||||
if (!$this->container->has('doctrine')) {
|
||||
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
|
||||
}
|
||||
|
||||
return $this->container->get('doctrine');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user from the Security Token Storage.
|
||||
*
|
||||
* @return UserInterface|null
|
||||
*
|
||||
* @throws \LogicException If SecurityBundle is not available
|
||||
*
|
||||
* @see TokenInterface::getUser()
|
||||
*/
|
||||
protected function getUser()
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
// @deprecated since 5.4, $user will always be a UserInterface instance
|
||||
if (!\is_object($user = $token->getUser())) {
|
||||
// e.g. anonymous authentication
|
||||
return null;
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, ?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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatches a message to the bus.
|
||||
*
|
||||
* @param object|Envelope $message The message or the message pre-wrapped in an envelope
|
||||
*
|
||||
* @deprecated since Symfony 5.4, inject an instance of MessageBusInterface in your controller instead
|
||||
*/
|
||||
protected function dispatchMessage(object $message, array $stamps = []): Envelope
|
||||
{
|
||||
trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, inject an instance of MessageBusInterface in your controller instead.', __METHOD__);
|
||||
|
||||
if (!$this->container->has('messenger.default_bus')) {
|
||||
$message = class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' : 'Try running "composer require symfony/messenger".';
|
||||
throw new \LogicException('The message bus is not enabled in your application. '.$message);
|
||||
}
|
||||
|
||||
return $this->container->get('messenger.default_bus')->dispatch($message, $stamps);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (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 Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
|
||||
|
||||
/**
|
||||
* Controller is a simple implementation of a Controller.
|
||||
*
|
||||
* It provides methods to common features needed in controllers.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
abstract class Controller implements ContainerAwareInterface
|
||||
{
|
||||
use ContainerAwareTrait;
|
||||
use ControllerTrait;
|
||||
|
||||
/**
|
||||
* Gets a container configuration parameter by its name.
|
||||
*
|
||||
* @param string $name The parameter name
|
||||
*
|
||||
* @return mixed
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function getParameter($name)
|
||||
{
|
||||
return $this->container->getParameter($name);
|
||||
}
|
||||
}
|
||||
@@ -1,152 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (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 Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Symfony\Component\HttpKernel\KernelInterface;
|
||||
|
||||
/**
|
||||
* ControllerNameParser converts controller from the short notation a:b:c
|
||||
* (BlogBundle:Post:index) to a fully-qualified class::method string
|
||||
* (Bundle\BlogBundle\Controller\PostController::indexAction).
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class ControllerNameParser
|
||||
{
|
||||
protected $kernel;
|
||||
|
||||
public function __construct(KernelInterface $kernel)
|
||||
{
|
||||
$this->kernel = $kernel;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a short notation a:b:c to a class::method.
|
||||
*
|
||||
* @param string $controller A short notation controller (a:b:c)
|
||||
*
|
||||
* @return string A string in the class::method notation
|
||||
*
|
||||
* @throws \InvalidArgumentException when the specified bundle is not enabled
|
||||
* or the controller cannot be found
|
||||
*/
|
||||
public function parse($controller)
|
||||
{
|
||||
$parts = explode(':', $controller);
|
||||
if (3 !== \count($parts) || \in_array('', $parts, true)) {
|
||||
throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid "a:b:c" controller string.', $controller));
|
||||
}
|
||||
|
||||
$originalController = $controller;
|
||||
list($bundle, $controller, $action) = $parts;
|
||||
$controller = str_replace('/', '\\', $controller);
|
||||
$bundles = [];
|
||||
|
||||
try {
|
||||
// this throws an exception if there is no such bundle
|
||||
$allBundles = $this->kernel->getBundle($bundle, false, true);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
$message = sprintf(
|
||||
'The "%s" (from the _controller value "%s") does not exist or is not enabled in your kernel!',
|
||||
$bundle,
|
||||
$originalController
|
||||
);
|
||||
|
||||
if ($alternative = $this->findAlternative($bundle)) {
|
||||
$message .= sprintf(' Did you mean "%s:%s:%s"?', $alternative, $controller, $action);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException($message, 0, $e);
|
||||
}
|
||||
|
||||
if (!\is_array($allBundles)) {
|
||||
// happens when HttpKernel is version 4+
|
||||
$allBundles = [$allBundles];
|
||||
}
|
||||
|
||||
foreach ($allBundles as $b) {
|
||||
$try = $b->getNamespace().'\\Controller\\'.$controller.'Controller';
|
||||
if (class_exists($try)) {
|
||||
return $try.'::'.$action.'Action';
|
||||
}
|
||||
|
||||
$bundles[] = $b->getName();
|
||||
$msg = sprintf('The _controller value "%s:%s:%s" maps to a "%s" class, but this class was not found. Create this class or check the spelling of the class and its namespace.', $bundle, $controller, $action, $try);
|
||||
}
|
||||
|
||||
if (\count($bundles) > 1) {
|
||||
$msg = sprintf('Unable to find controller "%s:%s" in bundles %s.', $bundle, $controller, implode(', ', $bundles));
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException($msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a class::method notation to a short one (a:b:c).
|
||||
*
|
||||
* @param string $controller A string in the class::method notation
|
||||
*
|
||||
* @return string A short notation controller (a:b:c)
|
||||
*
|
||||
* @throws \InvalidArgumentException when the controller is not valid or cannot be found in any bundle
|
||||
*/
|
||||
public function build($controller)
|
||||
{
|
||||
if (0 === preg_match('#^(.*?\\\\Controller\\\\(.+)Controller)::(.+)Action$#', $controller, $match)) {
|
||||
throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid "class::method" string.', $controller));
|
||||
}
|
||||
|
||||
$className = $match[1];
|
||||
$controllerName = $match[2];
|
||||
$actionName = $match[3];
|
||||
foreach ($this->kernel->getBundles() as $name => $bundle) {
|
||||
if (0 !== strpos($className, $bundle->getNamespace())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return sprintf('%s:%s:%s', $name, $controllerName, $actionName);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('Unable to find a bundle that defines controller "%s".', $controller));
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to find a bundle that is *similar* to the given bundle name.
|
||||
*
|
||||
* @param string $nonExistentBundleName
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function findAlternative($nonExistentBundleName)
|
||||
{
|
||||
$bundleNames = array_map(function ($b) {
|
||||
return $b->getName();
|
||||
}, $this->kernel->getBundles());
|
||||
|
||||
$alternative = null;
|
||||
$shortest = null;
|
||||
foreach ($bundleNames as $bundleName) {
|
||||
// if there's a partial match, return it immediately
|
||||
if (false !== strpos($bundleName, $nonExistentBundleName)) {
|
||||
return $bundleName;
|
||||
}
|
||||
|
||||
$lev = levenshtein($nonExistentBundleName, $bundleName);
|
||||
if ($lev <= \strlen($nonExistentBundleName) / 3 && (null === $alternative || $lev < $shortest)) {
|
||||
$alternative = $bundleName;
|
||||
$shortest = $lev;
|
||||
}
|
||||
}
|
||||
|
||||
return $alternative;
|
||||
}
|
||||
}
|
||||
@@ -11,66 +11,32 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpKernel\Controller\ContainerControllerResolver;
|
||||
|
||||
/**
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @final
|
||||
*/
|
||||
class ControllerResolver extends ContainerControllerResolver
|
||||
{
|
||||
protected $parser;
|
||||
|
||||
public function __construct(ContainerInterface $container, ControllerNameParser $parser, LoggerInterface $logger = null)
|
||||
{
|
||||
$this->parser = $parser;
|
||||
|
||||
parent::__construct($container, $logger);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function createController($controller)
|
||||
protected function instantiateController(string $class): object
|
||||
{
|
||||
if (false === strpos($controller, '::') && 2 === substr_count($controller, ':')) {
|
||||
// controller in the a:b:c notation then
|
||||
$controller = $this->parser->parse($controller);
|
||||
}
|
||||
$controller = parent::instantiateController($class);
|
||||
|
||||
$resolvedController = parent::createController($controller);
|
||||
|
||||
if (1 === substr_count($controller, ':') && \is_array($resolvedController)) {
|
||||
$resolvedController[0] = $this->configureController($resolvedController[0]);
|
||||
}
|
||||
|
||||
return $resolvedController;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function instantiateController($class)
|
||||
{
|
||||
return $this->configureController(parent::instantiateController($class));
|
||||
}
|
||||
|
||||
private function configureController($controller)
|
||||
{
|
||||
if ($controller instanceof ContainerAwareInterface) {
|
||||
// @deprecated switch, to be removed in 4.0 where these classes
|
||||
// won't implement ContainerAwareInterface anymore
|
||||
switch (\get_class($controller)) {
|
||||
case RedirectController::class:
|
||||
case TemplateController::class:
|
||||
return $controller;
|
||||
}
|
||||
$controller->setContainer($this->container);
|
||||
}
|
||||
if ($controller instanceof AbstractController && null !== $previousContainer = $controller->setContainer($this->container)) {
|
||||
$controller->setContainer($previousContainer);
|
||||
if ($controller instanceof AbstractController) {
|
||||
if (null === $previousContainer = $controller->setContainer($this->container)) {
|
||||
throw new \LogicException(sprintf('"%s" has no container set, did you forget to define it as a service subscriber?', $class));
|
||||
} else {
|
||||
$controller->setContainer($previousContainer);
|
||||
}
|
||||
}
|
||||
|
||||
return $controller;
|
||||
|
||||
@@ -1,480 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (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 Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Doctrine\Common\Persistence\ManagerRegistry as LegacyManagerRegistry;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Psr\Container\ContainerInterface;
|
||||
use Symfony\Component\Form\Extension\Core\Type\FormType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\JsonResponse;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
|
||||
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\Security\Core\Exception\AccessDeniedException;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
use Symfony\Component\Security\Csrf\CsrfToken;
|
||||
|
||||
/**
|
||||
* Common features needed in controllers.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @property ContainerInterface $container
|
||||
*/
|
||||
trait ControllerTrait
|
||||
{
|
||||
/**
|
||||
* Returns true if the service id is defined.
|
||||
*
|
||||
* @param string $id The service id
|
||||
*
|
||||
* @return bool true if the service id is defined, false otherwise
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function has($id)
|
||||
{
|
||||
return $this->container->has($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a container service by its id.
|
||||
*
|
||||
* @param string $id The service id
|
||||
*
|
||||
* @return object The service
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function get($id)
|
||||
{
|
||||
return $this->container->get($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a URL from the given parameters.
|
||||
*
|
||||
* @param string $route The name of the route
|
||||
* @param array $parameters An array of parameters
|
||||
* @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
|
||||
*
|
||||
* @return string The generated URL
|
||||
*
|
||||
* @see UrlGeneratorInterface
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function generateUrl($route, $parameters = [], $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
|
||||
{
|
||||
return $this->container->get('router')->generate($route, $parameters, $referenceType);
|
||||
}
|
||||
|
||||
/**
|
||||
* Forwards the request to another controller.
|
||||
*
|
||||
* @param string $controller The controller name (a string like BlogBundle:Post:index)
|
||||
* @param array $path An array of path parameters
|
||||
* @param array $query An array of query parameters
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function forward($controller, array $path = [], array $query = [])
|
||||
{
|
||||
$request = $this->container->get('request_stack')->getCurrentRequest();
|
||||
$path['_forwarded'] = $request->attributes;
|
||||
$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 string $url The URL to redirect to
|
||||
* @param int $status The status code to use for the Response
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function redirect($url, $status = 302)
|
||||
{
|
||||
return new RedirectResponse($url, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a RedirectResponse to the given route with the given parameters.
|
||||
*
|
||||
* @param string $route The name of the route
|
||||
* @param array $parameters An array of parameters
|
||||
* @param int $status The status code to use for the Response
|
||||
*
|
||||
* @return RedirectResponse
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function redirectToRoute($route, array $parameters = [], $status = 302)
|
||||
{
|
||||
return $this->redirect($this->generateUrl($route, $parameters), $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a JsonResponse that uses the serializer component if enabled, or json_encode.
|
||||
*
|
||||
* @param mixed $data The response data
|
||||
* @param int $status The status code to use for the Response
|
||||
* @param array $headers Array of extra headers to add
|
||||
* @param array $context Context to pass to serializer when using serializer component
|
||||
*
|
||||
* @return JsonResponse
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function json($data, $status = 200, $headers = [], $context = [])
|
||||
{
|
||||
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.
|
||||
*
|
||||
* @param \SplFileInfo|string $file File object or path to file to be sent as response
|
||||
* @param string|null $fileName File name to be sent to response or null (will use original file name)
|
||||
* @param string $disposition Disposition of response ("attachment" is default, other type is "inline")
|
||||
*
|
||||
* @return BinaryFileResponse
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function file($file, $fileName = null, $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT)
|
||||
{
|
||||
$response = new BinaryFileResponse($file);
|
||||
$response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a flash message to the current session for type.
|
||||
*
|
||||
* @param string $type The type
|
||||
* @param mixed $message The message
|
||||
*
|
||||
* @throws \LogicException
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function addFlash($type, $message)
|
||||
{
|
||||
if (!$this->container->has('session')) {
|
||||
throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
|
||||
}
|
||||
|
||||
$this->container->get('session')->getFlashBag()->add($type, $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the attributes are granted against the current authentication token and optionally supplied subject.
|
||||
*
|
||||
* @param mixed $attributes The attributes
|
||||
* @param mixed $subject The subject
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws \LogicException
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function isGranted($attributes, $subject = null)
|
||||
{
|
||||
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($attributes, $subject);
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws an exception unless the attributes are granted against the current authentication token and optionally
|
||||
* supplied subject.
|
||||
*
|
||||
* @param mixed $attributes The attributes
|
||||
* @param mixed $subject The subject
|
||||
* @param string $message The message passed to the exception
|
||||
*
|
||||
* @throws AccessDeniedException
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function denyAccessUnlessGranted($attributes, $subject = null, $message = 'Access Denied.')
|
||||
{
|
||||
if (!$this->isGranted($attributes, $subject)) {
|
||||
$exception = $this->createAccessDeniedException($message);
|
||||
$exception->setAttributes($attributes);
|
||||
$exception->setSubject($subject);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a rendered view.
|
||||
*
|
||||
* @param string $view The view name
|
||||
* @param array $parameters An array of parameters to pass to the view
|
||||
*
|
||||
* @return string The rendered view
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function renderView($view, array $parameters = [])
|
||||
{
|
||||
if ($this->container->has('templating')) {
|
||||
return $this->container->get('templating')->render($view, $parameters);
|
||||
}
|
||||
|
||||
if (!$this->container->has('twig')) {
|
||||
throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
|
||||
}
|
||||
|
||||
return $this->container->get('twig')->render($view, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a view.
|
||||
*
|
||||
* @param string $view The view name
|
||||
* @param array $parameters An array of parameters to pass to the view
|
||||
* @param Response $response A response instance
|
||||
*
|
||||
* @return Response A Response instance
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function render($view, array $parameters = [], Response $response = null)
|
||||
{
|
||||
if ($this->container->has('templating')) {
|
||||
$content = $this->container->get('templating')->render($view, $parameters);
|
||||
} elseif ($this->container->has('twig')) {
|
||||
$content = $this->container->get('twig')->render($view, $parameters);
|
||||
} else {
|
||||
throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
|
||||
}
|
||||
|
||||
if (null === $response) {
|
||||
$response = new Response();
|
||||
}
|
||||
|
||||
$response->setContent($content);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams a view.
|
||||
*
|
||||
* @param string $view The view name
|
||||
* @param array $parameters An array of parameters to pass to the view
|
||||
* @param StreamedResponse $response A response instance
|
||||
*
|
||||
* @return StreamedResponse A StreamedResponse instance
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function stream($view, array $parameters = [], StreamedResponse $response = null)
|
||||
{
|
||||
if ($this->container->has('templating')) {
|
||||
$templating = $this->container->get('templating');
|
||||
|
||||
$callback = function () use ($templating, $view, $parameters) {
|
||||
$templating->stream($view, $parameters);
|
||||
};
|
||||
} elseif ($this->container->has('twig')) {
|
||||
$twig = $this->container->get('twig');
|
||||
|
||||
$callback = function () use ($twig, $view, $parameters) {
|
||||
$twig->display($view, $parameters);
|
||||
};
|
||||
} else {
|
||||
throw new \LogicException('You can not use the "stream" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".');
|
||||
}
|
||||
|
||||
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!');
|
||||
*
|
||||
* @param string $message A message
|
||||
* @param \Exception|null $previous The previous exception
|
||||
*
|
||||
* @return NotFoundHttpException
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function createNotFoundException($message = 'Not Found', \Exception $previous = null)
|
||||
{
|
||||
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!');
|
||||
*
|
||||
* @param string $message A message
|
||||
* @param \Exception|null $previous The previous exception
|
||||
*
|
||||
* @return AccessDeniedException
|
||||
*
|
||||
* @throws \LogicException If the Security component is not available
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
|
||||
{
|
||||
if (!class_exists(AccessDeniedException::class)) {
|
||||
throw new \LogicException('You can not 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.
|
||||
*
|
||||
* @param string $type The fully qualified class name of the form type
|
||||
* @param mixed $data The initial data for the form
|
||||
* @param array $options Options for the form
|
||||
*
|
||||
* @return FormInterface
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function createForm($type, $data = null, array $options = [])
|
||||
{
|
||||
return $this->container->get('form.factory')->create($type, $data, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates and returns a form builder instance.
|
||||
*
|
||||
* @param mixed $data The initial data for the form
|
||||
* @param array $options Options for the form
|
||||
*
|
||||
* @return FormBuilderInterface
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function createFormBuilder($data = null, array $options = [])
|
||||
{
|
||||
return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut to return the Doctrine Registry service.
|
||||
*
|
||||
* @return ManagerRegistry|LegacyManagerRegistry
|
||||
*
|
||||
* @throws \LogicException If DoctrineBundle is not available
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function getDoctrine()
|
||||
{
|
||||
if (!$this->container->has('doctrine')) {
|
||||
throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');
|
||||
}
|
||||
|
||||
return $this->container->get('doctrine');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a user from the Security Token Storage.
|
||||
*
|
||||
* @return UserInterface|object|null
|
||||
*
|
||||
* @throws \LogicException If SecurityBundle is not available
|
||||
*
|
||||
* @see TokenInterface::getUser()
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function getUser()
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
if (!\is_object($user = $token->getUser())) {
|
||||
// e.g. anonymous authentication
|
||||
return null;
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks the validity of a CSRF token.
|
||||
*
|
||||
* @param string $id The id used when generating the token
|
||||
* @param string $token The actual token sent with the request that should be validated
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @final since version 3.4
|
||||
*/
|
||||
protected function isCsrfTokenValid($id, $token)
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,7 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -24,37 +23,21 @@ use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @final since version 3.4
|
||||
* @final
|
||||
*/
|
||||
class RedirectController implements ContainerAwareInterface
|
||||
class RedirectController
|
||||
{
|
||||
/**
|
||||
* @deprecated since version 3.4, to be removed in 4.0
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
private $router;
|
||||
private $httpPort;
|
||||
private $httpsPort;
|
||||
|
||||
public function __construct(UrlGeneratorInterface $router = null, $httpPort = null, $httpsPort = null)
|
||||
public function __construct(UrlGeneratorInterface $router = null, int $httpPort = null, int $httpsPort = null)
|
||||
{
|
||||
$this->router = $router;
|
||||
$this->httpPort = $httpPort;
|
||||
$this->httpsPort = $httpsPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated since version 3.4, to be removed in 4.0 alongside with the ContainerAwareInterface type.
|
||||
*/
|
||||
public function setContainer(ContainerInterface $container = null)
|
||||
{
|
||||
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.4 and will be removed in 4.0. Inject an UrlGeneratorInterface using the constructor instead.', __METHOD__), \E_USER_DEPRECATED);
|
||||
|
||||
$this->container = $container;
|
||||
$this->router = $container->get('router');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to another route with the given name.
|
||||
*
|
||||
@@ -64,16 +47,14 @@ class RedirectController implements ContainerAwareInterface
|
||||
* In case the route name is empty, the status code will be 404 when permanent is false
|
||||
* and 410 otherwise.
|
||||
*
|
||||
* @param Request $request The request instance
|
||||
* @param string $route The route name to redirect to
|
||||
* @param bool $permanent Whether the redirection is permanent
|
||||
* @param bool|array $ignoreAttributes Whether to ignore attributes or an array of attributes to ignore
|
||||
*
|
||||
* @return Response A Response instance
|
||||
* @param string $route The route name to redirect to
|
||||
* @param bool $permanent Whether the redirection is permanent
|
||||
* @param bool|array $ignoreAttributes Whether to ignore attributes or an array of attributes to ignore
|
||||
* @param bool $keepRequestMethod Whether redirect action should keep HTTP request method
|
||||
*
|
||||
* @throws HttpException In case the route name is empty
|
||||
*/
|
||||
public function redirectAction(Request $request, $route, $permanent = false, $ignoreAttributes = false)
|
||||
public function redirectAction(Request $request, string $route, bool $permanent = false, $ignoreAttributes = false, bool $keepRequestMethod = false, bool $keepQueryParams = false): Response
|
||||
{
|
||||
if ('' == $route) {
|
||||
throw new HttpException($permanent ? 410 : 404);
|
||||
@@ -82,13 +63,30 @@ class RedirectController implements ContainerAwareInterface
|
||||
$attributes = [];
|
||||
if (false === $ignoreAttributes || \is_array($ignoreAttributes)) {
|
||||
$attributes = $request->attributes->get('_route_params');
|
||||
unset($attributes['route'], $attributes['permanent'], $attributes['ignoreAttributes']);
|
||||
|
||||
if ($keepQueryParams) {
|
||||
if ($query = $request->server->get('QUERY_STRING')) {
|
||||
$query = HeaderUtils::parseQuery($query);
|
||||
} else {
|
||||
$query = $request->query->all();
|
||||
}
|
||||
|
||||
$attributes = array_merge($query, $attributes);
|
||||
}
|
||||
|
||||
unset($attributes['route'], $attributes['permanent'], $attributes['ignoreAttributes'], $attributes['keepRequestMethod'], $attributes['keepQueryParams']);
|
||||
if ($ignoreAttributes) {
|
||||
$attributes = array_diff_key($attributes, array_flip($ignoreAttributes));
|
||||
}
|
||||
}
|
||||
|
||||
return new RedirectResponse($this->router->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $permanent ? 301 : 302);
|
||||
if ($keepRequestMethod) {
|
||||
$statusCode = $permanent ? 308 : 307;
|
||||
} else {
|
||||
$statusCode = $permanent ? 301 : 302;
|
||||
}
|
||||
|
||||
return new RedirectResponse($this->router->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $statusCode);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,24 +98,26 @@ class RedirectController implements ContainerAwareInterface
|
||||
* In case the path is empty, the status code will be 404 when permanent is false
|
||||
* and 410 otherwise.
|
||||
*
|
||||
* @param Request $request The request instance
|
||||
* @param string $path The absolute path or URL to redirect to
|
||||
* @param bool $permanent Whether the redirect is permanent or not
|
||||
* @param string|null $scheme The URL scheme (null to keep the current one)
|
||||
* @param int|null $httpPort The HTTP port (null to keep the current one for the same scheme or the configured port in the container)
|
||||
* @param int|null $httpsPort The HTTPS port (null to keep the current one for the same scheme or the configured port in the container)
|
||||
*
|
||||
* @return Response A Response instance
|
||||
* @param string $path The absolute path or URL to redirect to
|
||||
* @param bool $permanent Whether the redirect is permanent or not
|
||||
* @param string|null $scheme The URL scheme (null to keep the current one)
|
||||
* @param int|null $httpPort The HTTP port (null to keep the current one for the same scheme or the default configured port)
|
||||
* @param int|null $httpsPort The HTTPS port (null to keep the current one for the same scheme or the default configured port)
|
||||
* @param bool $keepRequestMethod Whether redirect action should keep HTTP request method
|
||||
*
|
||||
* @throws HttpException In case the path is empty
|
||||
*/
|
||||
public function urlRedirectAction(Request $request, $path, $permanent = false, $scheme = null, $httpPort = null, $httpsPort = null)
|
||||
public function urlRedirectAction(Request $request, string $path, bool $permanent = false, string $scheme = null, int $httpPort = null, int $httpsPort = null, bool $keepRequestMethod = false): Response
|
||||
{
|
||||
if ('' == $path) {
|
||||
throw new HttpException($permanent ? 410 : 404);
|
||||
}
|
||||
|
||||
$statusCode = $permanent ? 301 : 302;
|
||||
if ($keepRequestMethod) {
|
||||
$statusCode = $permanent ? 308 : 307;
|
||||
} else {
|
||||
$statusCode = $permanent ? 301 : 302;
|
||||
}
|
||||
|
||||
// redirect if the path is a full URL
|
||||
if (parse_url($path, \PHP_URL_SCHEME)) {
|
||||
@@ -129,7 +129,7 @@ class RedirectController implements ContainerAwareInterface
|
||||
}
|
||||
|
||||
if ($qs = $request->server->get('QUERY_STRING') ?: $request->getQueryString()) {
|
||||
if (false === strpos($path, '?')) {
|
||||
if (!str_contains($path, '?')) {
|
||||
$qs = '?'.$qs;
|
||||
} else {
|
||||
$qs = '&'.$qs;
|
||||
@@ -141,9 +141,6 @@ class RedirectController implements ContainerAwareInterface
|
||||
if (null === $httpPort) {
|
||||
if ('http' === $request->getScheme()) {
|
||||
$httpPort = $request->getPort();
|
||||
} elseif ($this->container && $this->container->hasParameter('request_listener.http_port')) {
|
||||
@trigger_error(sprintf('Passing the http port as a container parameter is deprecated since Symfony 3.4 and won\'t be possible in 4.0. Pass it to the constructor of the "%s" class instead.', __CLASS__), \E_USER_DEPRECATED);
|
||||
$httpPort = $this->container->getParameter('request_listener.http_port');
|
||||
} else {
|
||||
$httpPort = $this->httpPort;
|
||||
}
|
||||
@@ -156,9 +153,6 @@ class RedirectController implements ContainerAwareInterface
|
||||
if (null === $httpsPort) {
|
||||
if ('https' === $request->getScheme()) {
|
||||
$httpsPort = $request->getPort();
|
||||
} elseif ($this->container && $this->container->hasParameter('request_listener.https_port')) {
|
||||
@trigger_error(sprintf('Passing the https port as a container parameter is deprecated since Symfony 3.4 and won\'t be possible in 4.0. Pass it to the constructor of the "%s" class instead.', __CLASS__), \E_USER_DEPRECATED);
|
||||
$httpsPort = $this->container->getParameter('request_listener.https_port');
|
||||
} else {
|
||||
$httpsPort = $this->httpsPort;
|
||||
}
|
||||
@@ -173,4 +167,23 @@ class RedirectController implements ContainerAwareInterface
|
||||
|
||||
return new RedirectResponse($url, $statusCode);
|
||||
}
|
||||
|
||||
public function __invoke(Request $request): Response
|
||||
{
|
||||
$p = $request->attributes->get('_route_params', []);
|
||||
|
||||
if (\array_key_exists('route', $p)) {
|
||||
if (\array_key_exists('path', $p)) {
|
||||
throw new \RuntimeException(sprintf('Ambiguous redirection settings, use the "path" or "route" parameter, not both: "%s" and "%s" found respectively in "%s" routing configuration.', $p['path'], $p['route'], $request->attributes->get('_route')));
|
||||
}
|
||||
|
||||
return $this->redirectAction($request, $p['route'], $p['permanent'] ?? false, $p['ignoreAttributes'] ?? false, $p['keepRequestMethod'] ?? false, $p['keepQueryParams'] ?? false);
|
||||
}
|
||||
|
||||
if (\array_key_exists('path', $p)) {
|
||||
return $this->urlRedirectAction($request, $p['path'], $p['permanent'] ?? false, $p['scheme'] ?? null, $p['httpPort'] ?? null, $p['httpsPort'] ?? null, $p['keepRequestMethod'] ?? false);
|
||||
}
|
||||
|
||||
throw new \RuntimeException(sprintf('The parameter "path" or "route" is required to configure the redirect action in "%s" routing configuration.', $request->attributes->get('_route')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,7 @@
|
||||
|
||||
namespace Symfony\Bundle\FrameworkBundle\Controller;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Templating\EngineInterface;
|
||||
use Twig\Environment;
|
||||
|
||||
/**
|
||||
@@ -22,60 +19,36 @@ use Twig\Environment;
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @final since version 3.4
|
||||
* @final
|
||||
*/
|
||||
class TemplateController implements ContainerAwareInterface
|
||||
class TemplateController
|
||||
{
|
||||
/**
|
||||
* @deprecated since version 3.4, to be removed in 4.0
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
private $twig;
|
||||
private $templating;
|
||||
|
||||
public function __construct(Environment $twig = null, EngineInterface $templating = null)
|
||||
public function __construct(Environment $twig = null)
|
||||
{
|
||||
$this->twig = $twig;
|
||||
$this->templating = $templating;
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated since version 3.4, to be removed in 4.0 alongside with the ContainerAwareInterface type.
|
||||
*/
|
||||
public function setContainer(ContainerInterface $container = null)
|
||||
{
|
||||
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 3.4 and will be removed in 4.0. Inject a Twig Environment or an EngineInterface using the constructor instead.', __METHOD__), \E_USER_DEPRECATED);
|
||||
|
||||
if ($container->has('templating')) {
|
||||
$this->templating = $container->get('templating');
|
||||
} elseif ($container->has('twig')) {
|
||||
$this->twig = $container->get('twig');
|
||||
}
|
||||
$this->container = $container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a template.
|
||||
*
|
||||
* @param string $template The template name
|
||||
* @param int|null $maxAge Max age for client caching
|
||||
* @param int|null $sharedAge Max age for shared (proxy) caching
|
||||
* @param bool|null $private Whether or not caching should apply for client caches only
|
||||
*
|
||||
* @return Response A Response instance
|
||||
* @param string $template The template name
|
||||
* @param int|null $maxAge Max age for client caching
|
||||
* @param int|null $sharedAge Max age for shared (proxy) caching
|
||||
* @param bool|null $private Whether or not caching should apply for client caches only
|
||||
* @param array $context The context (arguments) of the template
|
||||
* @param int $statusCode The HTTP status code to return with the response. Defaults to 200
|
||||
*/
|
||||
public function templateAction($template, $maxAge = null, $sharedAge = null, $private = null)
|
||||
public function templateAction(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null, array $context = [], int $statusCode = 200): Response
|
||||
{
|
||||
if ($this->templating) {
|
||||
$response = new Response($this->templating->render($template));
|
||||
} elseif ($this->twig) {
|
||||
$response = new Response($this->twig->render($template));
|
||||
} else {
|
||||
throw new \LogicException('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.');
|
||||
if (null === $this->twig) {
|
||||
throw new \LogicException('You cannot use the TemplateController if the Twig Bundle is not available.');
|
||||
}
|
||||
|
||||
if (null !== $maxAge) {
|
||||
$response = new Response($this->twig->render($template, $context), $statusCode);
|
||||
|
||||
if ($maxAge) {
|
||||
$response->setMaxAge($maxAge);
|
||||
}
|
||||
|
||||
@@ -91,4 +64,9 @@ class TemplateController implements ContainerAwareInterface
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function __invoke(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null, array $context = [], int $statusCode = 200): Response
|
||||
{
|
||||
return $this->templateAction($template, $maxAge, $sharedAge, $private, $context, $statusCode);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user