Alias.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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;
  11. use Symfony\Component\Routing\Exception\InvalidArgumentException;
  12. class Alias
  13. {
  14. private array $deprecation = [];
  15. public function __construct(
  16. private string $id,
  17. ) {
  18. }
  19. public function withId(string $id): static
  20. {
  21. $new = clone $this;
  22. $new->id = $id;
  23. return $new;
  24. }
  25. /**
  26. * Returns the target name of this alias.
  27. *
  28. * @return string The target name
  29. */
  30. public function getId(): string
  31. {
  32. return $this->id;
  33. }
  34. /**
  35. * Whether this alias is deprecated, that means it should not be referenced anymore.
  36. *
  37. * @param string $package The name of the composer package that is triggering the deprecation
  38. * @param string $version The version of the package that introduced the deprecation
  39. * @param string $message The deprecation message to use
  40. *
  41. * @return $this
  42. *
  43. * @throws InvalidArgumentException when the message template is invalid
  44. */
  45. public function setDeprecated(string $package, string $version, string $message): static
  46. {
  47. if ('' !== $message) {
  48. if (preg_match('#[\r\n]|\*/#', $message)) {
  49. throw new InvalidArgumentException('Invalid characters found in deprecation template.');
  50. }
  51. if (!str_contains($message, '%alias_id%')) {
  52. throw new InvalidArgumentException('The deprecation template must contain the "%alias_id%" placeholder.');
  53. }
  54. }
  55. $this->deprecation = [
  56. 'package' => $package,
  57. 'version' => $version,
  58. 'message' => $message ?: 'The "%alias_id%" route alias is deprecated. You should stop using it, as it will be removed in the future.',
  59. ];
  60. return $this;
  61. }
  62. public function isDeprecated(): bool
  63. {
  64. return (bool) $this->deprecation;
  65. }
  66. /**
  67. * @param string $name Route name relying on this alias
  68. */
  69. public function getDeprecation(string $name): array
  70. {
  71. return [
  72. 'package' => $this->deprecation['package'],
  73. 'version' => $this->deprecation['version'],
  74. 'message' => str_replace('%alias_id%', $name, $this->deprecation['message']),
  75. ];
  76. }
  77. }