-
Notifications
You must be signed in to change notification settings - Fork 0
/
AssocArray.php
85 lines (53 loc) · 1.54 KB
/
AssocArray.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
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
<?php
abstract class AssocArray {
public $pairs = [];
public $required, $values;
function __construct (array $data = []) {
$this->required = $this->getRequiredPairs ();
$this->values = $this->getRequiredValues ();
foreach ($this->getPairs () as $key => $value)
$this->set ($key, $value);
foreach ($data as $key => $value)
$this->set ($key, $value);
}
function getPairs (): array {
return [];
}
function getRequiredPairs (): array {
return [];
}
function getRequiredValues (): array {
return [];
}
function set ($key, $value) {
if (in_array ($key, array_keys ($this->values)) and !in_array ($value, $this->values[$key]))
throw new \Exception ($key.' value must be '.implode (', ', $this->values[$key]));
else
$this->pairs[$key] = $value;
return $this;
}
function get ($key) {
if (isset ($this->pairs[$key]))
return $this->pairs[$key];
else
return null;
}
function validate (): AssocArray {
if ($missed = $this->diff (array_keys ($this->pairs), $this->required))
throw new \Exception ('Required keys missed: '.implode (', ', $missed));
return $this;
}
protected function diff (...$arrays) {
$diff = [];
$arr = $arrays[0];
foreach ($arrays as $key => $value) {
foreach ($value as $value)
if (!in_array ($value, $arr))
$diff[] = $value;
}
return $diff;
}
function __toString () {
return json_encode ($this->pairs);
}
}