-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSet.php
More file actions
106 lines (79 loc) · 2.13 KB
/
Set.php
File metadata and controls
106 lines (79 loc) · 2.13 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace Equip\Structure;
use Equip\Structure\Traits\CanStructure;
class Set implements SetInterface
{
use CanStructure;
public function hasValue($value)
{
return in_array($value, $this->values, true);
}
public function withValues(array $values)
{
$this->assertValid($values);
$copy = clone $this;
$copy->values = array_unique($values, SORT_REGULAR);
return $copy;
}
public function withValue($value)
{
if ($this->hasValue($value)) {
return $this;
}
$this->assertValid([$value]);
$copy = clone $this;
$copy->values[] = $value;
return $copy;
}
public function withoutValue($value)
{
$key = array_search($value, $this->values, true);
if ($key === false) {
return $this;
}
$copy = clone $this;
unset($copy->values[$key]);
return $copy;
}
public function withValueAfter($value, $search)
{
if ($this->hasValue($value)) {
return $this;
}
$this->assertValid([$value]);
$copy = clone $this;
$key = array_search($search, $this->values);
if ($key === false) {
array_push($copy->values, $value);
} else {
array_splice($copy->values, $key + 1, 0, $value);
}
return $copy;
}
public function withValueBefore($value, $search)
{
if ($this->hasValue($value)) {
return $this;
}
$this->assertValid([$value]);
$copy = clone $this;
$key = array_search($search, $this->values);
if ($key === false) {
array_unshift($copy->values, $value);
} else {
array_splice($copy->values, $key, 0, $value);
}
return $copy;
}
protected function assertValid(array $values)
{
if (empty($values)) {
return;
}
if ($values !== array_values($values)) {
throw ValidationException::invalid(
'Set structures cannot have distinct keys'
);
}
}
}