BaseDTOCollection.php 1.2 KB

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