EnumRequirement.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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\Requirement;
  11. use Symfony\Component\Routing\Exception\InvalidArgumentException;
  12. final class EnumRequirement implements \Stringable
  13. {
  14. private string $requirement;
  15. /**
  16. * @template T of \BackedEnum
  17. *
  18. * @param class-string<T>|list<T> $cases
  19. */
  20. public function __construct(string|array $cases = [])
  21. {
  22. if (\is_string($cases)) {
  23. if (!is_subclass_of($cases, \BackedEnum::class, true)) {
  24. throw new InvalidArgumentException(\sprintf('"%s" is not a "BackedEnum" class.', $cases));
  25. }
  26. $cases = $cases::cases();
  27. } else {
  28. $class = null;
  29. foreach ($cases as $case) {
  30. if (!$case instanceof \BackedEnum) {
  31. throw new InvalidArgumentException(\sprintf('Case must be a "BackedEnum" instance, "%s" given.', get_debug_type($case)));
  32. }
  33. $class ??= $case::class;
  34. if (!$case instanceof $class) {
  35. throw new InvalidArgumentException(\sprintf('"%s::%s" is not a case of "%s".', get_debug_type($case), $case->name, $class));
  36. }
  37. }
  38. }
  39. $this->requirement = implode('|', array_map(static fn ($e) => preg_quote($e->value), $cases));
  40. }
  41. public function __toString(): string
  42. {
  43. return $this->requirement;
  44. }
  45. }