Enum.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Doctrine\Common\Annotations\Annotation;
  3. use InvalidArgumentException;
  4. use function get_class;
  5. use function gettype;
  6. use function in_array;
  7. use function is_object;
  8. use function is_scalar;
  9. use function sprintf;
  10. /**
  11. * Annotation that can be used to signal to the parser
  12. * to check the available values during the parsing process.
  13. *
  14. * @Annotation
  15. * @Attributes({
  16. * @Attribute("value", required = true, type = "array"),
  17. * @Attribute("literal", required = false, type = "array")
  18. * })
  19. */
  20. final class Enum
  21. {
  22. /** @phpstan-var list<scalar> */
  23. public $value;
  24. /**
  25. * Literal target declaration.
  26. *
  27. * @var mixed[]
  28. */
  29. public $literal;
  30. /**
  31. * @throws InvalidArgumentException
  32. *
  33. * @phpstan-param array{literal?: mixed[], value: list<scalar>} $values
  34. */
  35. public function __construct(array $values)
  36. {
  37. if (! isset($values['literal'])) {
  38. $values['literal'] = [];
  39. }
  40. foreach ($values['value'] as $var) {
  41. if (! is_scalar($var)) {
  42. throw new InvalidArgumentException(sprintf(
  43. '@Enum supports only scalar values "%s" given.',
  44. is_object($var) ? get_class($var) : gettype($var)
  45. ));
  46. }
  47. }
  48. foreach ($values['literal'] as $key => $var) {
  49. if (! in_array($key, $values['value'])) {
  50. throw new InvalidArgumentException(sprintf(
  51. 'Undefined enumerator value "%s" for literal "%s".',
  52. $key,
  53. $var
  54. ));
  55. }
  56. }
  57. $this->value = $values['value'];
  58. $this->literal = $values['literal'];
  59. }
  60. }