-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConversion.php
More file actions
92 lines (77 loc) · 2.42 KB
/
Copy pathConversion.php
File metadata and controls
92 lines (77 loc) · 2.42 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
declare(strict_types=1);
namespace Zero\Lib\Support\Concerns\Collection;
use ArrayIterator;
use JsonSerializable;
use Traversable;
trait Conversion
{
public function all(): array
{
return $this->items;
}
public function toArray(): array
{
return array_map(static function ($value) {
if ($value instanceof self) {
return $value->toArray();
}
if ($value instanceof JsonSerializable) {
return $value->jsonSerialize();
}
return $value;
}, $this->items);
}
public function toJson(int $flags = 0): string
{
return json_encode($this->jsonSerialize(), $flags);
}
public function jsonSerialize(): array
{
return array_map(static function ($value) {
if ($value instanceof JsonSerializable) {
return $value->jsonSerialize();
}
if ($value instanceof self) {
return $value->jsonSerialize();
}
return $value;
}, $this->items);
}
public function count(): int
{
return count($this->items);
}
public function isEmpty(): bool
{
return $this->items === [];
}
public function isNotEmpty(): bool
{
return $this->items !== [];
}
public function keys(): static
{
return new static(array_keys($this->items));
}
public function values(): static
{
return new static(array_values($this->items));
}
public function offsetExists(mixed $offset): bool { return isset($this->items[$offset]); }
public function offsetGet(mixed $offset): mixed { return $this->items[$offset]; }
public function offsetSet(mixed $offset, mixed $value): void { $offset === null ? $this->items[] = $value : $this->items[$offset] = $value; }
public function offsetUnset(mixed $offset): void { unset($this->items[$offset]); }
public function getIterator(): Traversable
{
return new ArrayIterator($this->items);
}
protected static function getArrayableItems(mixed $items): array
{
if (is_array($items)) return $items;
if ($items instanceof self) return $items->all();
if ($items instanceof JsonSerializable) return (array) $items->jsonSerialize();
if ($items instanceof Traversable) return iterator_to_array($items);
return (array) $items;
}
}