BaseDTOCollection.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. namespace Knuckles\Camel;
  3. use ArrayIterator;
  4. use Illuminate\Contracts\Support\Arrayable;
  5. use Illuminate\Support\Arr;
  6. use Illuminate\Support\Collection;
  7. use Spatie\DataTransferObject\DataTransferObjectCollection;
  8. /**
  9. * @template T of \Spatie\DataTransferObject\DataTransferObject
  10. */
  11. class BaseDTOCollection extends Collection
  12. {
  13. /**
  14. * @var string The name of the base DTO class.
  15. */
  16. public static string $base = '';
  17. public function __construct($items = [])
  18. {
  19. // Manually cast nested arrays
  20. $items = array_map(
  21. fn($item) => is_array($item) ? new static::$base($item) : $item,
  22. $items instanceof Collection ? $items->toArray() : $items
  23. );
  24. parent::__construct($items);
  25. }
  26. /**
  27. * Append items to the collection, mutating it.
  28. *
  29. * @param T[]|array[] $items
  30. */
  31. public function concat($items)
  32. {
  33. foreach ($items as $item) {
  34. $this->push(is_array($item) ? new static::$base($item) : $item);
  35. }
  36. return $this;
  37. }
  38. public function toArray(): array
  39. {
  40. return array_map(
  41. fn($item) => $item instanceof Arrayable ? $item->toArray() : $item,
  42. $this->items
  43. );
  44. }
  45. }