CompiledUrlGenerator.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\Component\Routing\Generator;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  13. use Symfony\Component\Routing\RequestContext;
  14. /**
  15. * Generates URLs based on rules dumped by CompiledUrlGeneratorDumper.
  16. */
  17. class CompiledUrlGenerator extends UrlGenerator
  18. {
  19. private $compiledRoutes = [];
  20. private $defaultLocale;
  21. public function __construct(array $compiledRoutes, RequestContext $context, LoggerInterface $logger = null, string $defaultLocale = null)
  22. {
  23. $this->compiledRoutes = $compiledRoutes;
  24. $this->context = $context;
  25. $this->logger = $logger;
  26. $this->defaultLocale = $defaultLocale;
  27. }
  28. public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
  29. {
  30. $locale = $parameters['_locale']
  31. ?? $this->context->getParameter('_locale')
  32. ?: $this->defaultLocale;
  33. if (null !== $locale) {
  34. do {
  35. if (($this->compiledRoutes[$name.'.'.$locale][1]['_canonical_route'] ?? null) === $name) {
  36. unset($parameters['_locale']);
  37. $name .= '.'.$locale;
  38. break;
  39. }
  40. } while (false !== $locale = strstr($locale, '_', true));
  41. }
  42. if (!isset($this->compiledRoutes[$name])) {
  43. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  44. }
  45. list($variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes) = $this->compiledRoutes[$name];
  46. return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
  47. }
  48. }