-
-
Notifications
You must be signed in to change notification settings - Fork 767
Expand file tree
/
Copy pathCollection.php
More file actions
82 lines (67 loc) · 1.69 KB
/
Collection.php
File metadata and controls
82 lines (67 loc) · 1.69 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
<?php
namespace Overtrue\Pinyin;
use ArrayAccess;
use JsonException;
use JsonSerializable;
use Stringable;
use function array_map;
use function implode;
use function is_array;
class Collection implements ArrayAccess, JsonSerializable, Stringable
{
public function __construct(protected $items = []) {}
public function join(string $separator = ' '): string
{
return implode($separator, array_map(
fn ($item) => is_array($item) ? '['.implode(', ', $item).']' : $item,
$this->items
));
}
public function map(callable $callback): Collection
{
return new static(array_map($callback, $this->all()));
}
public function all(): array
{
return $this->items;
}
public function toArray(): array
{
return $this->all();
}
/**
* @throws JsonException
*/
public function toJson(int $options = 0): string
{
return json_encode($this->all(), $options | JSON_THROW_ON_ERROR);
}
public function __toString(): string
{
return $this->join();
}
public function offsetExists(mixed $offset): bool
{
return isset($this->items[$offset]);
}
public function offsetGet(mixed $offset): mixed
{
return $this->items[$offset] ?? null;
}
public function offsetSet(mixed $offset, mixed $value): void
{
if ($offset === null) {
$this->items[] = $value;
} else {
$this->items[$offset] = $value;
}
}
public function offsetUnset(mixed $offset): void
{
unset($this->items[$offset]);
}
public function jsonSerialize(): array
{
return $this->items;
}
}