BaseDTOCollection.php 1.2 KB

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