GenericParam.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Knuckles\Scribe\Attributes;
  3. use Attribute;
  4. #[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION | Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
  5. class GenericParam
  6. {
  7. public function __construct(
  8. public string $name,
  9. public ?string $type = 'string',
  10. public ?string $description = '',
  11. public ?bool $required = true,
  12. public mixed $example = null, /* Pass 'No-example' to omit the example */
  13. public mixed $enum = null, // Can pass a list of values, or a native PHP enum
  14. public ?bool $nullable = false,
  15. ) {
  16. }
  17. public function toArray()
  18. {
  19. return [
  20. "name" => $this->name,
  21. "description" => $this->description,
  22. "type" => $this->type,
  23. "required" => $this->required,
  24. "example" => $this->example,
  25. "enumValues" => $this->getEnumValues(),
  26. 'nullable' => $this->nullable,
  27. ];
  28. }
  29. protected function getEnumValues(): array
  30. {
  31. if (!$this->enum) {
  32. return [];
  33. }
  34. if (is_array($this->enum)) {
  35. return $this->enum;
  36. }
  37. if (function_exists('enum_exists') && enum_exists($this->enum)
  38. && method_exists($this->enum, 'tryFrom')
  39. ) {
  40. return array_map(
  41. // $case->value only exists on BackedEnums, not UnitEnums
  42. // method_exists($enum, 'tryFrom') implies $enum instanceof BackedEnum
  43. // @phpstan-ignore-next-line
  44. fn ($case) => $case->value,
  45. $this->enum::cases()
  46. );
  47. }
  48. throw new \InvalidArgumentException(
  49. 'The enum property of a parameter must be either a PHP enum or an array of values'
  50. );
  51. }
  52. }