| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- <?php
- namespace App\DTO;
- use ReflectionClass;
- use JsonSerializable;
- use Illuminate\Contracts\Support\Arrayable;
- readonly class BaseDTO implements Arrayable, JsonSerializable
- {
- /**
- * Create a new DTO from an array of data.
- */
- public static function fromArray(array $data): static
- {
- $reflection = new ReflectionClass(static::class);
- $constructor = $reflection->getConstructor();
- if (!$constructor) {
- throw new \RuntimeException('DTO must have a constructor');
- }
- $properties = [];
- foreach ($constructor->getParameters() as $parameter) {
- $properties[$parameter->getName()] = $data[$parameter->getName()]
- ?? ($parameter->isOptional() ? $parameter->getDefaultValue() : null);
- }
- return new static(...$properties);
- }
- /**
- * Convert the DTO to an array.
- */
- public function toArray(): array
- {
- return get_object_vars($this);
- }
- /**
- * Convert the DTO to JSON.
- */
- public function jsonSerialize(): array
- {
- return $this->toArray();
- }
- }
|