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