BaseDTO.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace App\DTO;
  3. use ReflectionClass;
  4. use JsonSerializable;
  5. use Illuminate\Contracts\Support\Arrayable;
  6. readonly class BaseDTO implements Arrayable, JsonSerializable
  7. {
  8. /**
  9. * Create a new DTO from an array of data.
  10. */
  11. public static function fromArray(array $data): static
  12. {
  13. $reflection = new ReflectionClass(static::class);
  14. $constructor = $reflection->getConstructor();
  15. if (!$constructor) {
  16. throw new \RuntimeException('DTO must have a constructor');
  17. }
  18. $properties = [];
  19. foreach ($constructor->getParameters() as $parameter) {
  20. $properties[$parameter->getName()] = $data[$parameter->getName()]
  21. ?? ($parameter->isOptional() ? $parameter->getDefaultValue() : null);
  22. }
  23. return new static(...$properties);
  24. }
  25. /**
  26. * Convert the DTO to an array.
  27. */
  28. public function toArray(): array
  29. {
  30. return get_object_vars($this);
  31. }
  32. /**
  33. * Convert the DTO to JSON.
  34. */
  35. public function jsonSerialize(): array
  36. {
  37. return $this->toArray();
  38. }
  39. }