BaseDTOCollection.php 1.2 KB

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