BaseDTO.php 760 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\DTO;
  3. abstract readonly class BaseDTO implements \JsonSerializable
  4. {
  5. public function toArray(): array
  6. {
  7. $result = [];
  8. foreach (get_object_vars($this) as $key => $value) {
  9. $result[$key] = $this->normalizeValue($value);
  10. }
  11. return $result;
  12. }
  13. protected function normalizeValue(mixed $value): mixed
  14. {
  15. if ($value instanceof self) {
  16. return $value->toArray();
  17. }
  18. if (is_array($value)) {
  19. return array_map(
  20. fn($item) => $this->normalizeValue($item),
  21. $value
  22. );
  23. }
  24. return $value;
  25. }
  26. public function jsonSerialize(): array
  27. {
  28. return $this->toArray();
  29. }
  30. }