1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/* (c) Anton Medvedev <[email protected]> |
3
|
|
|
* |
4
|
|
|
* For the full copyright and license information, please view the LICENSE |
5
|
|
|
* file that was distributed with this source code. |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Deployer\Selector; |
9
|
|
|
|
10
|
|
|
use Deployer\Host\Host; |
11
|
|
|
use Deployer\Host\HostCollection; |
12
|
|
|
use function Deployer\Support\array_all; |
13
|
|
|
|
14
|
|
|
class Selector |
15
|
|
|
{ |
16
|
|
|
private $hosts; |
17
|
|
|
|
18
|
1 |
|
public function __construct(HostCollection $hosts) |
19
|
|
|
{ |
20
|
1 |
|
$this->hosts = $hosts; |
21
|
1 |
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $selectExpression |
25
|
|
|
* @return Host[] |
26
|
|
|
*/ |
27
|
1 |
|
public function selectHosts(string $selectExpression) |
28
|
|
|
{ |
29
|
1 |
|
$selector = self::parse($selectExpression); |
30
|
|
|
|
31
|
1 |
|
$hosts = []; |
32
|
1 |
|
foreach ($this->hosts as $host) { |
33
|
1 |
|
if (self::apply($selector, $host)) { |
34
|
1 |
|
$hosts[] = $host; |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
return $hosts; |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
public static function apply($selector, Host $host) |
42
|
|
|
{ |
43
|
1 |
|
$labels = $host->get('labels', []); |
44
|
|
|
|
45
|
1 |
|
$ok = []; |
46
|
1 |
|
foreach ($selector as list($op, $var, $value)) { |
47
|
1 |
|
if ($op === 'all') { |
48
|
1 |
|
$ok[] = true; |
49
|
1 |
|
continue; |
50
|
|
|
} |
51
|
1 |
|
if ($var === 'host') { |
52
|
|
|
$ok[] = self::compare($op, $host->alias(), $value); |
53
|
|
|
} else { |
54
|
1 |
|
$ok[] = self::compare($op, $labels[$var] ?? null, $value); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return count($ok) > 0 && array_all($ok, function ($value) { |
59
|
1 |
|
return $value; |
60
|
1 |
|
}); |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
private static function compare(string $op, $a, $b): bool |
64
|
|
|
{ |
65
|
1 |
|
if ($op === '=') { |
66
|
1 |
|
return $a === $b; |
67
|
|
|
} |
68
|
1 |
|
if ($op === '!=') { |
69
|
1 |
|
return $a !== $b; |
70
|
|
|
} |
71
|
|
|
return false; |
72
|
|
|
} |
73
|
|
|
|
74
|
1 |
|
public static function parse(string $selectExpression) |
75
|
|
|
{ |
76
|
1 |
|
$actions = []; |
77
|
|
|
// TODO: Implement correct parser and maybe add extra features. |
78
|
1 |
|
$parts = explode(',', $selectExpression); |
79
|
1 |
|
foreach ($parts as $part) { |
80
|
1 |
|
$part = trim($part); |
81
|
1 |
|
if ($part === 'all') { |
82
|
1 |
|
$actions[] = ['all', null, null]; |
83
|
1 |
|
continue; |
84
|
|
|
} |
85
|
1 |
|
if (preg_match('/(?<var>.+?)(?<op>!?=)(?<value>.+)/', $part, $match)) { |
86
|
1 |
|
$actions[] = [$match['op'], trim($match['var']), trim($match['value'])]; |
87
|
|
|
} else { |
88
|
|
|
throw new \InvalidArgumentException("Invalid selector \"$part\"."); |
89
|
|
|
} |
90
|
|
|
} |
91
|
1 |
|
return $actions; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|