PathProcessorAlias.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Drupal\Core\PathProcessor;
  3. use Drupal\Core\Path\AliasManagerInterface;
  4. use Drupal\Core\Render\BubbleableMetadata;
  5. use Symfony\Component\HttpFoundation\Request;
  6. /**
  7. * Processes the inbound path using path alias lookups.
  8. */
  9. class PathProcessorAlias implements InboundPathProcessorInterface, OutboundPathProcessorInterface {
  10. /**
  11. * An alias manager for looking up the system path.
  12. *
  13. * @var \Drupal\Core\Path\AliasManagerInterface
  14. */
  15. protected $aliasManager;
  16. /**
  17. * Constructs a PathProcessorAlias object.
  18. *
  19. * @param \Drupal\Core\Path\AliasManagerInterface $alias_manager
  20. * An alias manager for looking up the system path.
  21. */
  22. public function __construct(AliasManagerInterface $alias_manager) {
  23. $this->aliasManager = $alias_manager;
  24. }
  25. /**
  26. * {@inheritdoc}
  27. */
  28. public function processInbound($path, Request $request) {
  29. $path = $this->aliasManager->getPathByAlias($path);
  30. return $path;
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
  36. if (empty($options['alias'])) {
  37. $langcode = isset($options['language']) ? $options['language']->getId() : NULL;
  38. $path = $this->aliasManager->getAliasByPath($path, $langcode);
  39. // Ensure the resulting path has at most one leading slash, to prevent it
  40. // becoming an external URL without a protocol like //example.com. This
  41. // is done in \Drupal\Core\Routing\UrlGenerator::generateFromRoute()
  42. // also, to protect against this problem in arbitrary path processors,
  43. // but it is duplicated here to protect any other URL generation code
  44. // that might call this method separately.
  45. if (strpos($path, '//') === 0) {
  46. $path = '/' . ltrim($path, '/');
  47. }
  48. }
  49. return $path;
  50. }
  51. }