Ei kuvausta

CompiledUrlGenerator.php 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. $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. }