BaseDTO.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace Knuckles\Camel;
  3. use Illuminate\Contracts\Support\Arrayable;
  4. use Spatie\DataTransferObject\DataTransferObject;
  5. class BaseDTO extends DataTransferObject implements Arrayable, \ArrayAccess
  6. {
  7. /**
  8. * @var array $custom
  9. * Added so end-users can dynamically add additional properties for their own use.
  10. */
  11. public array $custom = [];
  12. public static function create(BaseDTO|array $data, BaseDTO|array $inheritFrom = []): static
  13. {
  14. if ($data instanceof static) {
  15. return $data;
  16. }
  17. $mergedData = $inheritFrom instanceof static ? $inheritFrom->toArray() : $inheritFrom;
  18. foreach ($data as $property => $value) {
  19. $mergedData[$property] = $value;
  20. }
  21. return new static($mergedData);
  22. }
  23. protected function parseArray(array $array): array
  24. {
  25. // Reimplementing here so our DTOCollection items can be recursively toArray'ed
  26. foreach ($array as $key => $value) {
  27. if ($value instanceof Arrayable) {
  28. $array[$key] = $value->toArray();
  29. continue;
  30. }
  31. if (! is_array($value)) {
  32. continue;
  33. }
  34. $array[$key] = $this->parseArray($value);
  35. }
  36. return $array;
  37. }
  38. public static function make(array|self $data): static
  39. {
  40. return $data instanceof static ? $data : new static($data);
  41. }
  42. public function offsetExists(mixed $offset): bool
  43. {
  44. return isset($this->$offset);
  45. }
  46. public function offsetGet(mixed $offset): mixed
  47. {
  48. return $this->$offset;
  49. }
  50. public function offsetSet(mixed $offset, mixed $value): void
  51. {
  52. $this->$offset = $value;
  53. }
  54. public function offsetUnset(mixed $offset): void
  55. {
  56. unset($this->$offset);
  57. }
  58. }