1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* this file is part of pipelines */ |
4
|
|
|
|
5
|
|
|
namespace Ktomk\Pipelines\Value\Env; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* -e, --env <value> |
9
|
|
|
*/ |
10
|
|
|
class EnvVar |
11
|
|
|
{ |
12
|
|
|
const PATTERN = '~^([^\\x0-\\x20$={}\\x7f-\\xff-]+)(?:=([^\\0]*))?$~'; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
private $expression; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @param string $env |
21
|
|
|
*/ |
22
|
14 |
|
public function __construct($env) |
23
|
|
|
{ |
24
|
14 |
|
$this->parseDefinition((string)$env); |
25
|
|
|
} |
26
|
|
|
|
27
|
3 |
|
public function __toString() |
28
|
|
|
{ |
29
|
3 |
|
list($name, $value) = $this->expression; |
30
|
|
|
|
31
|
3 |
|
return $name . (isset($value) ? '=' . $value : ''); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
1 |
|
public function getName() |
38
|
|
|
{ |
39
|
1 |
|
return $this->expression[0]; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @return null|string |
44
|
|
|
*/ |
45
|
1 |
|
public function tryValue() |
46
|
|
|
{ |
47
|
1 |
|
return $this->expression[1]; |
48
|
|
|
} |
49
|
|
|
|
50
|
2 |
|
public function getValue() |
51
|
|
|
{ |
52
|
2 |
|
$value = $this->expression[1]; |
53
|
2 |
|
if (null === $value) { |
54
|
1 |
|
throw new \BadFunctionCallException( |
55
|
1 |
|
sprintf('Environment variable %s has no value', $this->expression[0]) |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
return $value; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return array{string, string|null} |
|
|
|
|
64
|
|
|
*/ |
65
|
3 |
|
public function getPair() |
66
|
|
|
{ |
67
|
3 |
|
return $this->expression; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @param string $definition |
72
|
|
|
* |
73
|
|
|
* @return void |
74
|
|
|
*/ |
75
|
14 |
|
private function parseDefinition($definition) |
76
|
|
|
{ |
77
|
14 |
|
$result = preg_match(self::PATTERN, $definition, $matches); |
78
|
14 |
|
if (0 === $result) { |
79
|
4 |
|
throw new \InvalidArgumentException(sprintf( |
80
|
|
|
'Environment variable error: %s', |
81
|
4 |
|
addcslashes($definition, "\0..\40\\\177..\377") |
82
|
|
|
)); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
/** @var array{0: string, 1: string, 2: null|string} $matches */ |
86
|
|
|
|
87
|
10 |
|
list(, $name, $value) = $matches + array(2 => null); |
88
|
|
|
|
89
|
10 |
|
$this->expression = array($name, $value); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|