Alias.php 2.5 KB

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