|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace DutchCodingCompany\LaravelJsonSchema\Rules; |
| 4 | + |
| 5 | +use DutchCodingCompany\LaravelJsonSchema\Contracts\JsonSchemaNameProvider; |
| 6 | +use DutchCodingCompany\LaravelJsonSchema\Contracts\JsonSchemaValidator; |
| 7 | +use Illuminate\Contracts\Validation\DataAwareRule; |
| 8 | +use InvalidArgumentException; |
| 9 | + |
| 10 | +class JsonSchemaAttributeRule extends BaseRule implements DataAwareRule |
| 11 | +{ |
| 12 | + /** |
| 13 | + * All of the data under validation. |
| 14 | + * |
| 15 | + * @var array<string, mixed> |
| 16 | + */ |
| 17 | + protected $data = []; |
| 18 | + |
| 19 | + /** |
| 20 | + * @param string $attribute from with other attribute to retrieve the schema name |
| 21 | + * @param class-string<\BackedEnum&\DutchCodingCompany\LaravelJsonSchema\Contracts\JsonSchemaNameProvider>|null $enum which enum to cast the schema name into (if applicable) |
| 22 | + */ |
| 23 | + public function __construct( |
| 24 | + protected string $attribute, |
| 25 | + protected ?string $enum = null, |
| 26 | + protected bool $detailedMessage = true, |
| 27 | + JsonSchemaValidator | null $schemaValidator = null, |
| 28 | + ) { |
| 29 | + parent::__construct($detailedMessage, $schemaValidator); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * Set the data under validation. |
| 34 | + * |
| 35 | + * @param array<string, mixed> $data |
| 36 | + */ |
| 37 | + public function setData(array $data): static |
| 38 | + { |
| 39 | + $this->data = $data; |
| 40 | + |
| 41 | + return $this; |
| 42 | + } |
| 43 | + |
| 44 | + protected function determineSchemaName(): string |
| 45 | + { |
| 46 | + $schemaName = data_get($this->data, $this->attribute); |
| 47 | + |
| 48 | + if ($this->enum !== null) { |
| 49 | + $enum = ($this->enum)::tryFrom($schemaName); |
| 50 | + |
| 51 | + if ($enum instanceof JsonSchemaNameProvider) { |
| 52 | + return $enum->getSchemaName(); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + if (is_string($schemaName)) { |
| 57 | + return $schemaName; |
| 58 | + } |
| 59 | + |
| 60 | + throw new InvalidArgumentException('Cannot determine schema name from attribute "'.$this->attribute.'"'); |
| 61 | + } |
| 62 | +} |
0 commit comments