|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Ark4ne\JsonApi\Asserts; |
| 4 | + |
| 5 | +use Ark4ne\JsonApi\Descriptors\Values\Value; |
| 6 | +use Ark4ne\JsonApi\Resources\JsonApiResource; |
| 7 | +use Ark4ne\JsonApi\Support\FakeModel; |
| 8 | +use Ark4ne\JsonApi\Support\Values; |
| 9 | +use Illuminate\Http\Request; |
| 10 | +use Illuminate\Http\Resources\MissingValue; |
| 11 | +use ReflectionClass; |
| 12 | + |
| 13 | +class AssertJsonApiResource |
| 14 | +{ |
| 15 | + /** |
| 16 | + * @param class-string<JsonApiResource> $class |
| 17 | + */ |
| 18 | + public function __construct(protected string $class) |
| 19 | + { |
| 20 | + } |
| 21 | + |
| 22 | + public function assert(): void |
| 23 | + { |
| 24 | + $this->itCanGenerateSchema(); |
| 25 | + $this->allAttributesAreLazySet(); |
| 26 | + } |
| 27 | + |
| 28 | + private function itCanGenerateSchema(): void |
| 29 | + { |
| 30 | + try { |
| 31 | + $this->class::schema(); |
| 32 | + } catch (\Throwable $throwable) { |
| 33 | + throw new FailGenerateSchema($this->class, $throwable); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private function allAttributesAreLazySet(): void |
| 38 | + { |
| 39 | + $reflection = new ReflectionClass($this->class); |
| 40 | + $instance = $reflection->newInstanceWithoutConstructor(); |
| 41 | + $instance->resource = new FakeModel; |
| 42 | + |
| 43 | + $method = $reflection->getMethod('toAttributes'); |
| 44 | + $method->setAccessible(true); |
| 45 | + /** @var iterable<array-key, mixed> $attributes */ |
| 46 | + $attributes = $method->invoke($instance, new Request()); |
| 47 | + $attributes = Values::mergeValues($attributes); |
| 48 | + |
| 49 | + foreach ($attributes as $key => $attribute) { |
| 50 | + if (!($attribute instanceof \Closure || $attribute instanceof MissingValue || $attribute instanceof Value)) { |
| 51 | + throw new EagerSetAttribute($this->class, $key); |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments