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

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 $router;
  27.     private $httpPort;
  28.     private $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, $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.         if (null === $scheme) {
  112.             $scheme = $request->getScheme();
  113.         }
  114.         if ($qs = $request->server->get('QUERY_STRING') ?: $request->getQueryString()) {
  115.             if (!str_contains($path, '?')) {
  116.                 $qs = '?'.$qs;
  117.             } else {
  118.                 $qs = '&'.$qs;
  119.             }
  120.         }
  121.         $port = '';
  122.         if ('http' === $scheme) {
  123.             if (null === $httpPort) {
  124.                 if ('http' === $request->getScheme()) {
  125.                     $httpPort = $request->getPort();
  126.                 } else {
  127.                     $httpPort = $this->httpPort;
  128.                 }
  129.             }
  130.             if (null !== $httpPort && 80 != $httpPort) {
  131.                 $port = ":$httpPort";
  132.             }
  133.         } elseif ('https' === $scheme) {
  134.             if (null === $httpsPort) {
  135.                 if ('https' === $request->getScheme()) {
  136.                     $httpsPort = $request->getPort();
  137.                 } else {
  138.                     $httpsPort = $this->httpsPort;
  139.                 }
  140.             }
  141.             if (null !== $httpsPort && 443 != $httpsPort) {
  142.                 $port = ":$httpsPort";
  143.             }
  144.         }
  145.         $url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$path.$qs;
  146.         return new RedirectResponse($url, $statusCode);
  147.     }
  148.     public function __invoke(Request $request): Response
  149.     {
  150.         $p = $request->attributes->get('_route_params', []);
  151.         if (\array_key_exists('route', $p)) {
  152.             if (\array_key_exists('path', $p)) {
  153.                 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')));
  154.             }
  155.             return $this->redirectAction($request, $p['route'], $p['permanent'] ?? false, $p['ignoreAttributes'] ?? false, $p['keepRequestMethod'] ?? false, $p['keepQueryParams'] ?? false);
  156.         }
  157.         if (\array_key_exists('path', $p)) {
  158.             return $this->urlRedirectAction($request, $p['path'], $p['permanent'] ?? false, $p['scheme'] ?? null, $p['httpPort'] ?? null, $p['httpsPort'] ?? null, $p['keepRequestMethod'] ?? false);
  159.         }
  160.         throw new \RuntimeException(sprintf('The parameter "path" or "route" is required to configure the redirect action in "%s" routing configuration.', $request->attributes->get('_route')));
  161.     }
  162. }