-
Notifications
You must be signed in to change notification settings - Fork 0
/
ALDVersionSwitch.php
64 lines (56 loc) · 2.13 KB
/
ALDVersionSwitch.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
<?php
require_once dirname(__FILE__) . '/lib/exceptions.php';
class ALDVersionSwitch {
private $data;
public function __construct($data) {
$this->validate($data);
$this->data = $data;
}
public function matches($value) {
if (isset($this->data['version']) && $this->compare($this->data['version'], $value) == 0) {
return true;
} else if (isset($this->data['version-range'])
&& $this->compare($this->data['version-range']['min'], $value) <= 0
&& $this->compare($this->data['version-range']['max'], $value) >= 0) {
return true;
} else if (isset($this->data['version-list'])) {
foreach ($this->data['version-list'] AS $version) {
if ($this->compare($version, $value) == 0) {
return true;
}
}
}
return false;
}
protected function compare($a, $b) {
return strnatcasecmp($a, $b);
}
protected function validate($data) {
if (!is_array($data) || count($data) != 1) {
throw new InvalidVersionSwitchException('Invalid switch data');
}
if (array_key_exists('version-range', $data)) {
if (!is_array($data['version-range'])
|| count($data['version-range']) != 2
|| !isset($data['version-range']['min'])
|| !isset($data['version-range']['max'])) {
throw new InvalidVersionSwitchException('Invalid version range: incorrect data');
}
if ($this->compare($data['version-range']['min'], $data['version-range']['max']) > 0) {
throw new InvalidVersionSwitchException('Invalid version range: min > max');
}
} else if (array_key_exists('version-list', $data)) {
if (!is_array($data['version-list'])) {
throw new InvalidVersionSwitchException('Invalid version list: not an array');
}
if (array_keys($data['version-list']) !== array_keys(array_keys($data['version-list']))) { # not only continous numeric keys
throw new InvalidVersionSwitchException('Invalid version list: not a continous zero-based array');
}
} else if (!array_key_exists('version', $data)) {
throw new InvalidVersionSwitchException('Invalid switch data: unsupported fields');
} else if ($data['version'] === NULL) {
throw new InvalidVersionSwitchException('Invalid version: must not be NULL');
}
}
}
?>