1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Lamoda\MultiEnv\HostDetector; |
6
|
|
|
|
7
|
|
|
use GetOpt\GetOpt; |
8
|
|
|
use Lamoda\MultiEnv\HostDetector\Exception\HostDetectorException; |
9
|
|
|
use Lamoda\MultiEnv\Model\HostId; |
10
|
|
|
|
11
|
|
|
final class CliArgsBasedHostDetector implements HostDetectorInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string $needle |
15
|
|
|
*/ |
16
|
|
|
private $needle; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var GetOpt $getOptAdapter |
20
|
|
|
*/ |
21
|
|
|
private $getOptAdapter; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var bool $isCliArgumentsParsed |
25
|
|
|
*/ |
26
|
|
|
private $isCliArgumentsParsed = false; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $needle |
30
|
|
|
* @param GetOpt $getOptAdapter |
31
|
|
|
* @throws HostDetectorException |
32
|
|
|
*/ |
33
|
17 |
|
public function __construct(string $needle, GetOpt $getOptAdapter) |
34
|
|
|
{ |
35
|
17 |
|
$needle = trim($needle); |
36
|
17 |
|
$this->validateInitialParams($needle, $getOptAdapter); |
37
|
|
|
|
38
|
13 |
|
$this->getOptAdapter = $getOptAdapter; |
39
|
13 |
|
$this->needle = $needle; |
40
|
13 |
|
} |
41
|
|
|
|
42
|
23 |
|
public function getCurrentHost(): HostId |
43
|
|
|
{ |
44
|
23 |
|
if (!$this->isCliArgumentsParsed) { |
45
|
23 |
|
$this->getOptAdapter->process(); |
46
|
23 |
|
$this->isCliArgumentsParsed = true; |
47
|
|
|
} |
48
|
|
|
|
49
|
23 |
|
$hostId = (string)$this->getOptAdapter->getOption($this->needle); |
50
|
23 |
|
$hostId = trim($hostId, '='); |
51
|
|
|
|
52
|
23 |
|
return new HostId($hostId); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param string $needle |
57
|
|
|
* @param GetOpt $getOptAdapter |
58
|
|
|
* @throws HostDetectorException |
59
|
|
|
*/ |
60
|
17 |
|
private function validateInitialParams(string $needle, GetOpt $getOptAdapter): void |
61
|
|
|
{ |
62
|
17 |
|
if (empty($needle)) { |
63
|
3 |
|
throw HostDetectorException::becauseEmptyNeedlePassed(self::class); |
64
|
|
|
} |
65
|
|
|
|
66
|
14 |
|
if ((bool)$getOptAdapter->get(GetOpt::SETTING_STRICT_OPTIONS) !== false) { |
67
|
1 |
|
throw HostDetectorException::becauseGetOptAdapterConfiguredIncorrect( |
68
|
1 |
|
GetOpt::class, |
69
|
1 |
|
GetOpt::SETTING_STRICT_OPTIONS, |
70
|
1 |
|
'false' |
71
|
|
|
); |
72
|
|
|
} |
73
|
13 |
|
} |
74
|
|
|
} |
75
|
|
|
|