MockAliasManager.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Drupal\system\Tests\Routing;
  3. use Drupal\Core\Path\AliasManagerInterface;
  4. /**
  5. * An easily configurable mock alias manager.
  6. */
  7. class MockAliasManager implements AliasManagerInterface {
  8. /**
  9. * Array of mocked aliases. Keys are system paths, followed by language.
  10. *
  11. * @var array
  12. */
  13. protected $aliases = [];
  14. /**
  15. * Array of mocked aliases. Keys are aliases, followed by language.
  16. *
  17. * @var array
  18. */
  19. protected $systemPaths = [];
  20. /**
  21. * An index of aliases that have been requested.
  22. *
  23. * @var array
  24. */
  25. protected $lookedUp = [];
  26. /**
  27. * The language to assume a path alias is for if not specified.
  28. *
  29. * @var string
  30. */
  31. public $defaultLanguage = 'en';
  32. /**
  33. * Adds an alias to the in-memory alias table for this object.
  34. *
  35. * @param string $path
  36. * The system path of the alias.
  37. * @param string $alias
  38. * The alias of the system path.
  39. * @param string $path_language
  40. * The language of this alias.
  41. */
  42. public function addAlias($path, $alias, $path_language = NULL) {
  43. $language = $path_language ?: $this->defaultLanguage;
  44. if ($path[0] !== '/') {
  45. throw new \InvalidArgumentException('The path needs to start with a slash.');
  46. }
  47. if ($alias[0] !== '/') {
  48. throw new \InvalidArgumentException('The alias needs to start with a slash.');
  49. }
  50. $this->aliases[$path][$language] = $alias;
  51. $this->systemPaths[$alias][$language] = $path;
  52. }
  53. /**
  54. * {@inheritdoc}
  55. */
  56. public function getPathByAlias($alias, $langcode = NULL) {
  57. $langcode = $langcode ?: $this->defaultLanguage;
  58. return $this->systemPaths[$alias][$langcode];
  59. }
  60. /**
  61. * {@inheritdoc}
  62. * @param $path
  63. * @param null $langcode
  64. * @return
  65. */
  66. public function getAliasByPath($path, $langcode = NULL) {
  67. if ($path[0] !== '/') {
  68. throw new \InvalidArgumentException(sprintf('Source path %s has to start with a slash.', $path));
  69. }
  70. $langcode = $langcode ?: $this->defaultLanguage;
  71. $this->lookedUp[$path] = 1;
  72. return $this->aliases[$path][$langcode];
  73. }
  74. /**
  75. * {@inheritdoc}
  76. */
  77. public function cacheClear($source = NULL) {
  78. // Not needed.
  79. }
  80. }