1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the skeleton package. |
7
|
|
|
* |
8
|
|
|
* (c) Gennady Knyazkin <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Gennadyx\Skeleton\VarSource; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Class Env |
18
|
|
|
* |
19
|
|
|
* @author Gennady Knyazkin <[email protected]> |
20
|
|
|
*/ |
21
|
|
|
class Env extends AbstractSource |
22
|
|
|
{ |
23
|
|
|
/** |
24
|
|
|
* Template for sprintf |
25
|
|
|
*/ |
26
|
|
|
const TEMPLATE = 'COMPOSER_DEFAULT_%s'; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var array |
30
|
|
|
*/ |
31
|
|
|
private $customEnv; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Env constructor. |
35
|
|
|
* |
36
|
|
|
*/ |
37
|
2 |
|
public function __construct() |
38
|
|
|
{ |
39
|
2 |
|
$this->customEnv = self::getCustomEnv(); |
40
|
2 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* {@inheritdoc} |
44
|
|
|
*/ |
45
|
2 |
|
protected function find(string $name) |
46
|
|
|
{ |
47
|
2 |
|
$value = $this->getEnv(sprintf(self::TEMPLATE, strtoupper($name))); |
48
|
|
|
|
49
|
2 |
|
if (null === $value && isset($this->customEnv[$name])) { |
50
|
|
|
$value = $this->getEnv($this->customEnv[$name]); |
51
|
|
|
} |
52
|
|
|
|
53
|
2 |
|
return $value; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @param string $env |
58
|
|
|
* |
59
|
|
|
* @return string|null |
60
|
|
|
*/ |
61
|
2 |
|
private function getEnv(string $env) |
62
|
|
|
{ |
63
|
2 |
|
$value = getenv($env); |
64
|
|
|
|
65
|
2 |
|
if ($this->checkString($value)) { |
66
|
2 |
|
return $value; |
67
|
2 |
|
} elseif ($this->checkArray($value)) { |
68
|
|
|
return array_shift($value); |
69
|
|
|
} |
70
|
|
|
|
71
|
2 |
|
return null; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Check is valid string |
76
|
|
|
* |
77
|
|
|
* @param mixed $value |
78
|
|
|
* |
79
|
|
|
* @return bool |
80
|
|
|
*/ |
81
|
2 |
|
private function checkString($value): bool |
82
|
|
|
{ |
83
|
2 |
|
return is_string($value) && !empty($value); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* Check is valid array |
88
|
|
|
* |
89
|
|
|
* @param $value |
90
|
|
|
* |
91
|
|
|
* @return bool |
92
|
|
|
*/ |
93
|
2 |
|
private function checkArray($value): bool |
94
|
|
|
{ |
95
|
2 |
|
if (!is_array($value)) { |
96
|
2 |
|
return false; |
97
|
|
|
} |
98
|
|
|
|
99
|
|
|
$first = array_shift($value); |
100
|
|
|
|
101
|
|
|
return $this->checkString($first); |
102
|
|
|
} |
103
|
|
|
|
104
|
|
|
/** |
105
|
|
|
* @return array |
106
|
|
|
*/ |
107
|
2 |
|
private static function getCustomEnv(): array |
108
|
|
|
{ |
109
|
|
|
return [ |
110
|
2 |
|
'vendor' => strpos(PHP_OS, 'WIN') === 0 ? 'USERNAME' : 'USER', |
111
|
|
|
]; |
112
|
|
|
} |
113
|
|
|
} |
114
|
|
|
|