Repository navigation
Expand file tree
/
Copy pathGlobalOptionsParser.php
More file actions
127 lines (97 loc) · 2.91 KB
/
Copy pathGlobalOptionsParser.php
File metadata and controls
127 lines (97 loc) · 2.91 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Cli;
/**
* @internal
*/
final class GlobalOptionsParser
{
/**
* @param array<int, string> $args
*/
public function parse(array $args): ParsedGlobalOptions
{
$quiet = false;
$ansi = null;
$help = false;
$visuals = true;
$phpVersion = null;
$pcreVersion = null;
$error = null;
$remaining = [];
for ($i = 0; $i < \count($args); $i++) {
$arg = $args[$i];
if ($this->isQuietOption($arg)) {
$quiet = true;
continue;
}
if ($this->isAnsiOption($arg)) {
$ansi = '--ansi' === $arg;
continue;
}
if ($this->isHelpOption($arg)) {
$help = true;
continue;
}
if ($this->isVisualsOption($arg)) {
$visuals = false;
continue;
}
if ($this->isValuedOption('--pcre-version', $arg, $args, $i, $pcreVersion, $error)
|| $this->isValuedOption('--php-version', $arg, $args, $i, $phpVersion, $error)) {
if (null !== $error) {
break;
}
continue;
}
$remaining[] = $arg;
}
$options = new GlobalOptions($quiet, $ansi, $help, $visuals, $phpVersion, $error, $pcreVersion);
return new ParsedGlobalOptions($options, $remaining);
}
private function isQuietOption(string $arg): bool
{
return '-q' === $arg || '--quiet' === $arg || '--silent' === $arg;
}
private function isAnsiOption(string $arg): bool
{
return '--ansi' === $arg || '--no-ansi' === $arg;
}
private function isHelpOption(string $arg): bool
{
return '--help' === $arg || '-h' === $arg;
}
private function isVisualsOption(string $arg): bool
{
return '--no-visuals' === $arg || '--no-art' === $arg || '--no-splash' === $arg;
}
/**
* @param array<int, string> $args
*/
private function isValuedOption(string $name, string $arg, array $args, int &$i, ?string &$value, ?string &$error): bool
{
if (str_starts_with($arg, $name.'=')) {
$value = substr($arg, \strlen($name) + 1);
return true;
}
if ($name !== $arg) {
return false;
}
$next = $args[$i + 1] ?? '';
if ('' === $next || str_starts_with($next, '-')) {
$error = \sprintf('Missing value for %s.', $name);
return true;
}
$value = $next;
$i++;
return true;
}
}