vendor/symfony/framework-bundle/Controller/RedirectController.php line 110

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Bundle\FrameworkBundle\Controller;
  11. use Symfony\Component\HttpFoundation\HeaderUtils;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Exception\HttpException;
  16. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  17. /**
  18.  * Redirects a request to another URL.
  19.  *
  20.  * @author Fabien Potencier <fabien@symfony.com>
  21.  *
  22.  * @final
  23.  */
  24. class RedirectController
  25. {
  26.     private ?UrlGeneratorInterface $router;
  27.     private ?int $httpPort;
  28.     private ?int $httpsPort;
  29.     public function __construct(UrlGeneratorInterface $router = null, int $httpPort = null, int $httpsPort = null)
  30.     {
  31.         $this->router = $router;
  32.         $this->httpPort = $httpPort;
  33.         $this->httpsPort = $httpsPort;
  34.     }
  35.     /**
  36.      * Redirects to another route with the given name.
  37.      *
  38.      * The response status code is 302 if the permanent parameter is false (default),
  39.      * and 301 if the redirection is permanent.
  40.      *
  41.      * In case the route name is empty, the status code will be 404 when permanent is false
  42.      * and 410 otherwise.
  43.      *
  44.      * @param string     $route             The route name to redirect to
  45.      * @param bool       $permanent         Whether the redirection is permanent
  46.      * @param bool|array $ignoreAttributes  Whether to ignore attributes or an array of attributes to ignore
  47.      * @param bool       $keepRequestMethod Whether redirect action should keep HTTP request method
  48.      *
  49.      * @throws HttpException In case the route name is empty
  50.      */
  51.     public function redirectAction(Request $request, string $route, bool $permanent = false, bool|array $ignoreAttributes = false, bool $keepRequestMethod = false, bool $keepQueryParams = false): Response
  52.     {
  53.         if ('' == $route) {
  54.             throw new HttpException($permanent ? 410 : 404);
  55.         }
  56.         $attributes = [];
  57.         if (false === $ignoreAttributes || \is_array($ignoreAttributes)) {
  58.             $attributes = $request->attributes->get('_route_params');
  59.             if ($keepQueryParams) {
  60.                 if ($query = $request->server->get('QUERY_STRING')) {
  61.                     $query = HeaderUtils::parseQuery($query);
  62.                 } else {
  63.                     $query = $request->query->all();
  64.                 }
  65.                 $attributes = array_merge($query, $attributes);
  66.             }
  67.             unset($attributes['route'], $attributes['permanent'], $attributes['ignoreAttributes'], $attributes['keepRequestMethod'], $attributes['keepQueryParams']);
  68.             if ($ignoreAttributes) {
  69.                 $attributes = array_diff_key($attributes, array_flip($ignoreAttributes));
  70.             }
  71.         }
  72.         if ($keepRequestMethod) {
  73.             $statusCode = $permanent ? 308 : 307;
  74.         } else {
  75.             $statusCode = $permanent ? 301 : 302;
  76.         }
  77.         return new RedirectResponse($this->router->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $statusCode);
  78.     }
  79.     /**
  80.      * Redirects to a URL.
  81.      *
  82.      * The response status code is 302 if the permanent parameter is false (default),
  83.      * and 301 if the redirection is permanent.
  84.      *
  85.      * In case the path is empty, the status code will be 404 when permanent is false
  86.      * and 410 otherwise.
  87.      *
  88.      * @param string      $path              The absolute path or URL to redirect to
  89.      * @param bool        $permanent         Whether the redirect is permanent or not
  90.      * @param string|null $scheme            The URL scheme (null to keep the current one)
  91.      * @param int|null    $httpPort          The HTTP port (null to keep the current one for the same scheme or the default configured port)
  92.      * @param int|null    $httpsPort         The HTTPS port (null to keep the current one for the same scheme or the default configured port)
  93.      * @param bool        $keepRequestMethod Whether redirect action should keep HTTP request method
  94.      *
  95.      * @throws HttpException In case the path is empty
  96.      */
  97.     public function urlRedirectAction(Request $request, string $path, bool $permanent = false, string $scheme = null, int $httpPort = null, int $httpsPort = null, bool $keepRequestMethod = false): Response
  98.     {
  99.         if ('' == $path) {
  100.             throw new HttpException($permanent ? 410 : 404);
  101.         }
  102.         if ($keepRequestMethod) {
  103.             $statusCode = $permanent ? 308 : 307;
  104.         } else {
  105.             $statusCode = $permanent ? 301 : 302;
  106.         }
  107.         // redirect if the path is a full URL
  108.         if (parse_url($path, \PHP_URL_SCHEME)) {
  109.             return new RedirectResponse($path, $statusCode);
  110.         }
  111.         $scheme ??= $request->getScheme();
  112.         if ($qs = $request->server->get('QUERY_STRING') ?: $request->getQueryString()) {
  113.             if (!str_contains($path, '?')) {
  114.                 $qs = '?'.$qs;
  115.             } else {
  116.                 $qs = '&'.$qs;
  117.             }
  118.         }
  119.         $port = '';
  120.         if ('http' === $scheme) {
  121.             if (null === $httpPort) {
  122.                 if ('http' === $request->getScheme()) {
  123.                     $httpPort = $request->getPort();
  124.                 } else {
  125.                     $httpPort = $this->httpPort;
  126.                 }
  127.             }
  128.             if (null !== $httpPort && 80 != $httpPort) {
  129.                 $port = ":$httpPort";
  130.             }
  131.         } elseif ('https' === $scheme) {
  132.             if (null === $httpsPort) {
  133.                 if ('https' === $request->getScheme()) {
  134.                     $httpsPort = $request->getPort();
  135.                 } else {
  136.                     $httpsPort = $this->httpsPort;
  137.                 }
  138.             }
  139.             if (null !== $httpsPort && 443 != $httpsPort) {
  140.                 $port = ":$httpsPort";
  141.             }
  142.         }
  143.         $url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$path.$qs;
  144.         return new RedirectResponse($url, $statusCode);
  145.     }
  146.     public function __invoke(Request $request): Response
  147.     {
  148.         $p = $request->attributes->get('_route_params', []);
  149.         if (\array_key_exists('route', $p)) {
  150.             if (\array_key_exists('path', $p)) {
  151.                 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')));
  152.             }
  153.             return $this->redirectAction($request, $p['route'], $p['permanent'] ?? false, $p['ignoreAttributes'] ?? false, $p['keepRequestMethod'] ?? false, $p['keepQueryParams'] ?? false);
  154.         }
  155.         if (\array_key_exists('path', $p)) {
  156.             return $this->urlRedirectAction($request, $p['path'], $p['permanent'] ?? false, $p['scheme'] ?? null, $p['httpPort'] ?? null, $p['httpsPort'] ?? null, $p['keepRequestMethod'] ?? false);
  157.         }
  158.         throw new \RuntimeException(sprintf('The parameter "path" or "route" is required to configure the redirect action in "%s" routing configuration.', $request->attributes->get('_route')));
  159.     }
  160. }