CompiledUrlGenerator.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 array $compiledRoutes = [];
  20. public function __construct(
  21. array $compiledRoutes,
  22. RequestContext $context,
  23. ?LoggerInterface $logger = null,
  24. private ?string $defaultLocale = null,
  25. ) {
  26. $this->compiledRoutes = $compiledRoutes;
  27. $this->context = $context;
  28. $this->logger = $logger;
  29. }
  30. public function generate(string $name, array $parameters = [], int $referenceType = self::ABSOLUTE_PATH): string
  31. {
  32. $locale = $parameters['_locale']
  33. ?? $this->context->getParameter('_locale')
  34. ?: $this->defaultLocale;
  35. if (null !== $locale) {
  36. do {
  37. if (($this->compiledRoutes[$name.'.'.$locale][1]['_canonical_route'] ?? null) === $name) {
  38. $name .= '.'.$locale;
  39. break;
  40. }
  41. } while (false !== $locale = strstr($locale, '_', true));
  42. }
  43. if (!isset($this->compiledRoutes[$name])) {
  44. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  45. }
  46. [$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes, $deprecations] = $this->compiledRoutes[$name] + [6 => []];
  47. foreach ($deprecations as $deprecation) {
  48. trigger_deprecation($deprecation['package'], $deprecation['version'], $deprecation['message']);
  49. }
  50. if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
  51. if (!\in_array('_locale', $variables, true)) {
  52. unset($parameters['_locale']);
  53. } elseif (!isset($parameters['_locale'])) {
  54. $parameters['_locale'] = $defaults['_locale'];
  55. }
  56. }
  57. return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
  58. }
  59. }