You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.3 KiB

3 years ago
  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(string $name, array $parameters = [], int $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. $name .= '.'.$locale;
  37. break;
  38. }
  39. } while (false !== $locale = strstr($locale, '_', true));
  40. }
  41. if (!isset($this->compiledRoutes[$name])) {
  42. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  43. }
  44. [$variables, $defaults, $requirements, $tokens, $hostTokens, $requiredSchemes] = $this->compiledRoutes[$name];
  45. if (isset($defaults['_canonical_route']) && isset($defaults['_locale'])) {
  46. if (!\in_array('_locale', $variables, true)) {
  47. unset($parameters['_locale']);
  48. } elseif (!isset($parameters['_locale'])) {
  49. $parameters['_locale'] = $defaults['_locale'];
  50. }
  51. }
  52. return $this->doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, $requiredSchemes);
  53. }
  54. }