aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/cli/CliOptionsParser.php
blob: be325bd91ebf1406fa1b285a090a5e11732042c2 (plain) (blame)
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
<?php
declare(strict_types=1);

abstract class CliOptionsParser {
	/** @var array<string,CliOption> */
	private array $options = [];
	/** @var array<string,array{defaultInput:?string[],required:?bool,aliasUsed:?string,values:?string[]}> */
	private array $inputs = [];
	/** @var array<string,string> $errors */
	public array $errors = [];
	public string $usage = '';

	public function __construct() {
		global $argv;

		$this->usage = $this->getUsageMessage($argv[0]);

		$this->parseInput();
		$this->appendUnknownAliases($argv);
		$this->appendInvalidValues();
		$this->appendTypedValidValues();
	}

	private function parseInput(): void {
		$getoptInputs = $this->getGetoptInputs();
		$this->getoptOutputTransformer(getopt($getoptInputs['short'], $getoptInputs['long']));
		$this->checkForDeprecatedAliasUse();
	}

	/** Adds an option that produces an error message if not set. */
	protected function addRequiredOption(string $name, CliOption $option): void {
		$this->inputs[$name] = [
			'defaultInput' => null,
			'required' => true,
			'aliasUsed' => null,
			'values' => null,
		];
		$this->options[$name] = $option;
	}

	/**
	 * Adds an optional option.
	 * @param string $defaultInput If not null this value is received as input in all cases where no
	 *  user input is present. e.g. set this if you want an option to always return a value.
	 */
	protected function addOption(string $name, CliOption $option, string $defaultInput = null): void {
		$this->inputs[$name] = [
			'defaultInput' => is_string($defaultInput) ? [$defaultInput] : $defaultInput,
			'required' => null,
			'aliasUsed' => null,
			'values' => null,
		];
		$this->options[$name] = $option;
	}

	private function appendInvalidValues(): void {
		foreach ($this->options as $name => $option) {
			if ($this->inputs[$name]['required'] && $this->inputs[$name]['values'] === null) {
				$this->errors[$name] = 'invalid input: ' . $option->getLongAlias() . ' cannot be empty';
			}
		}

		foreach ($this->inputs as $name => $input) {
			foreach ($input['values'] ?? $input['defaultInput'] ?? [] as $value) {
				switch ($this->options[$name]->getTypes()['type']) {
					case 'int':
						if (!ctype_digit($value)) {
							$this->errors[$name] = 'invalid input: ' . $input['aliasUsed'] . ' must be an integer';
						}
						break;
					case 'bool':
						if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === null) {
							$this->errors[$name] = 'invalid input: ' . $input['aliasUsed'] . ' must be a boolean';
						}
						break;
				}
			}
		}
	}

	private function appendTypedValidValues(): void {
		foreach ($this->inputs as $name => $input) {
			$values = $input['values'] ?? $input['defaultInput'] ?? null;
			$types = $this->options[$name]->getTypes();
			if ($values) {
				$validValues = [];
				$typedValues = [];

				switch ($types['type']) {
					case 'string':
						$typedValues = $values;
						break;
					case 'int':
						$validValues = array_filter($values, static fn($value) => ctype_digit($value));
						$typedValues = array_map(static fn($value) => (int) $value, $validValues);
						break;
					case 'bool':
						$validValues = array_filter($values, static fn($value) => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null);
						$typedValues = array_map(static fn($value) => (bool) filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), $validValues);
						break;
				}

				if (!empty($typedValues)) {
					// @phpstan-ignore-next-line (change to `@phpstan-ignore property.dynamicName` when upgrading to PHPStan 1.11+)
					$this->$name = $types['isArray'] ? $typedValues : array_pop($typedValues);
				}
			}
		}
	}

	/** @param array<string,string|false>|false $getoptOutput */
	private function getoptOutputTransformer($getoptOutput): void {
		$getoptOutput = is_array($getoptOutput) ? $getoptOutput : [];

		foreach ($getoptOutput as $alias => $value) {
			foreach ($this->options as $name => $data) {
				if (in_array($alias, $data->getAliases(), true)) {
					$this->inputs[$name]['aliasUsed'] = $alias;
					$this->inputs[$name]['values'] = $value === false
						? [$data->getOptionalValueDefault()]
						: (is_array($value)
							? $value
							: [$value]);
				}
			}
		}
	}

	/**
	 * @param array<string> $userInputs
	 * @return array<string>
	 */
	private function getAliasesUsed(array $userInputs, string $regex): array {
		$foundAliases = [];

		foreach ($userInputs as $input) {
			preg_match($regex, $input, $matches);

			if(!empty($matches['short'])) {
				$foundAliases = array_merge($foundAliases, str_split($matches['short']));
			}
			if(!empty($matches['long'])) {
				$foundAliases[] = $matches['long'];
			}
		}

		return $foundAliases;
	}

	/**
	 * @param array<string> $input List of user command-line inputs.
	 */
	private function appendUnknownAliases(array $input): void {
		$valid = [];
		foreach ($this->options as $option) {
			$valid = array_merge($valid, $option->getAliases());
		}

		$sanitizeInput = $this->getAliasesUsed($input, $this->makeInputRegex());
		$unknownAliases = array_diff($sanitizeInput, $valid);
		if (empty($unknownAliases)) {
			return;
		}

		foreach ($unknownAliases as $unknownAlias) {
			$this->errors[$unknownAlias] = 'unknown option: ' . $unknownAlias;
		}
	}

	/**
	 * Checks for presence of deprecated aliases.
	 * @return bool Returns TRUE and generates a deprecation warning if deprecated aliases are present, FALSE otherwise.
	 */
	private function checkForDeprecatedAliasUse(): bool {
		$deprecated = [];
		$replacements = [];

		foreach ($this->inputs as $name => $data) {
			if ($data['aliasUsed'] !== null && $data['aliasUsed'] === $this->options[$name]->getDeprecatedAlias()) {
				$deprecated[] = $this->options[$name]->getDeprecatedAlias();
				$replacements[] = $this->options[$name]->getLongAlias();
			}
		}

		if (empty($deprecated)) {
			return false;
		}

		fwrite(STDERR, "FreshRSS deprecation warning: the CLI option(s): " . implode(', ', $deprecated) .
			" are deprecated and will be removed in a future release. Use: " . implode(', ', $replacements) .
			" instead\n");
		return true;
	}

	/** @return array{long:array<string>,short:string}*/
	private function getGetoptInputs(): array {
		$getoptNotation = [
			'none' => '',
			'required' => ':',
			'optional' => '::',
		];

		$long = [];
		$short = '';

		foreach ($this->options as $option) {
			$long[] = $option->getLongAlias() . $getoptNotation[$option->getValueTaken()];
			$long[] = $option->getDeprecatedAlias() ? $option->getDeprecatedAlias() . $getoptNotation[$option->getValueTaken()] : '';
			$short .= $option->getShortAlias() ? $option->getShortAlias() . $getoptNotation[$option->getValueTaken()] : '';
		}

		return [
			'long' => array_filter($long),
			'short' => $short
		];
	}

	private function getUsageMessage(string $command): string {
		$required = ['Usage: ' . basename($command)];
		$optional = [];

		foreach ($this->options as $name => $option) {
			$shortAlias = $option->getShortAlias() ? '-' . $option->getShortAlias() . ' ' : '';
			$longAlias = '--' . $option->getLongAlias() . ($option->getValueTaken() === 'required' ? '=<' . strtolower($name) . '>' : '');
			if ($this->inputs[$name]['required']) {
				$required[] = $shortAlias . $longAlias;
			} else {
				$optional[] = '[' . $shortAlias . $longAlias . ']';
			}
		}

		return implode(' ', $required) . ' ' . implode(' ', $optional);
	}

	private function makeInputRegex() : string {
		$shortWithValues = '';
		foreach ($this->options as $option) {
			if (($option->getValueTaken() === 'required' || $option->getValueTaken() === 'optional') && $option->getShortAlias()) {
				$shortWithValues .= $option->getShortAlias();
			}
		}

		return $shortWithValues === ''
			? "/^--(?'long'[^=]+)|^-(?<short>\w+)/"
			: "/^--(?'long'[^=]+)|^-(?<short>(?(?=\w*[$shortWithValues])[^$shortWithValues]*[$shortWithValues]|\w+))/";
	}
}