CliOptionsParser.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. declare(strict_types=1);
  3. abstract class CliOptionsParser {
  4. /** @var array<string,CliOption> */
  5. private array $options = [];
  6. /** @var array<string,array{defaultInput:?string[],required:?bool,aliasUsed:?string,values:?string[]}> */
  7. private array $inputs = [];
  8. /** @var array<string,string> $errors */
  9. public array $errors = [];
  10. public string $usage = '';
  11. public function __construct() {
  12. /** @var array<string> $argv */
  13. global $argv;
  14. $this->usage = $this->getUsageMessage($argv[0]);
  15. $this->parseInput();
  16. $this->appendUnknownAliases($argv);
  17. $this->appendInvalidValues();
  18. $this->appendTypedValidValues();
  19. }
  20. private function parseInput(): void {
  21. $getoptInputs = $this->getGetoptInputs();
  22. $this->getoptOutputTransformer(getopt($getoptInputs['short'], $getoptInputs['long']));
  23. $this->checkForDeprecatedAliasUse();
  24. }
  25. /** Adds an option that produces an error message if not set. */
  26. protected function addRequiredOption(string $name, CliOption $option): void {
  27. $this->inputs[$name] = [
  28. 'defaultInput' => null,
  29. 'required' => true,
  30. 'aliasUsed' => null,
  31. 'values' => null,
  32. ];
  33. $this->options[$name] = $option;
  34. }
  35. /**
  36. * Adds an optional option.
  37. * @param string $defaultInput If not null this value is received as input in all cases where no
  38. * user input is present. e.g. set this if you want an option to always return a value.
  39. */
  40. protected function addOption(string $name, CliOption $option, ?string $defaultInput = null): void {
  41. $this->inputs[$name] = [
  42. 'defaultInput' => is_string($defaultInput) ? [$defaultInput] : $defaultInput,
  43. 'required' => null,
  44. 'aliasUsed' => null,
  45. 'values' => null,
  46. ];
  47. $this->options[$name] = $option;
  48. }
  49. private function appendInvalidValues(): void {
  50. foreach ($this->options as $name => $option) {
  51. if ($this->inputs[$name]['required'] && $this->inputs[$name]['values'] === null) {
  52. $this->errors[$name] = 'invalid input: ' . $option->getLongAlias() . ' cannot be empty';
  53. }
  54. }
  55. foreach ($this->inputs as $name => $input) {
  56. foreach ($input['values'] ?? $input['defaultInput'] ?? [] as $value) {
  57. switch ($this->options[$name]->getTypes()['type']) {
  58. case 'int':
  59. if (!ctype_digit($value)) {
  60. $this->errors[$name] = 'invalid input: ' . $input['aliasUsed'] . ' must be an integer';
  61. }
  62. break;
  63. case 'bool':
  64. if (filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === null) {
  65. $this->errors[$name] = 'invalid input: ' . $input['aliasUsed'] . ' must be a boolean';
  66. }
  67. break;
  68. }
  69. }
  70. }
  71. }
  72. private function appendTypedValidValues(): void {
  73. foreach ($this->inputs as $name => $input) {
  74. $values = $input['values'] ?? $input['defaultInput'] ?? null;
  75. $types = $this->options[$name]->getTypes();
  76. if (!empty($values)) {
  77. $validValues = [];
  78. $typedValues = [];
  79. switch ($types['type']) {
  80. case 'string':
  81. $typedValues = $values;
  82. break;
  83. case 'int':
  84. $validValues = array_filter($values, static fn($value) => ctype_digit($value));
  85. $typedValues = array_map(static fn($value) => (int)$value, $validValues);
  86. break;
  87. case 'bool':
  88. $validValues = array_filter($values, static fn($value) => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) !== null);
  89. $typedValues = array_map(static fn($value) => (bool)filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE), $validValues);
  90. break;
  91. }
  92. if (!empty($typedValues)) {
  93. // @phpstan-ignore property.dynamicName
  94. $this->$name = $types['isArray'] ? $typedValues : array_pop($typedValues);
  95. }
  96. }
  97. }
  98. }
  99. /** @param array<string,string|false>|false $getoptOutput */
  100. private function getoptOutputTransformer($getoptOutput): void {
  101. $getoptOutput = is_array($getoptOutput) ? $getoptOutput : [];
  102. foreach ($getoptOutput as $alias => $value) {
  103. foreach ($this->options as $name => $data) {
  104. if (in_array($alias, $data->getAliases(), true)) {
  105. $this->inputs[$name]['aliasUsed'] = $alias;
  106. $this->inputs[$name]['values'] = $value === false
  107. ? [$data->getOptionalValueDefault()]
  108. : (is_array($value)
  109. ? $value
  110. : [$value]);
  111. }
  112. }
  113. }
  114. }
  115. /**
  116. * @param array<string> $userInputs
  117. * @return array<string>
  118. */
  119. private function getAliasesUsed(array $userInputs, string $regex): array {
  120. $foundAliases = [];
  121. foreach ($userInputs as $input) {
  122. preg_match($regex, $input, $matches);
  123. if (!empty($matches['short'])) {
  124. $foundAliases = array_merge($foundAliases, str_split($matches['short']));
  125. }
  126. if (!empty($matches['long'])) {
  127. $foundAliases[] = $matches['long'];
  128. }
  129. }
  130. return $foundAliases;
  131. }
  132. /**
  133. * @param array<string> $input List of user command-line inputs.
  134. */
  135. private function appendUnknownAliases(array $input): void {
  136. $valid = [];
  137. foreach ($this->options as $option) {
  138. $valid = array_merge($valid, $option->getAliases());
  139. }
  140. $sanitizeInput = $this->getAliasesUsed($input, $this->makeInputRegex());
  141. $unknownAliases = array_diff($sanitizeInput, $valid);
  142. if (empty($unknownAliases)) {
  143. return;
  144. }
  145. foreach ($unknownAliases as $unknownAlias) {
  146. $this->errors[$unknownAlias] = 'unknown option: ' . $unknownAlias;
  147. }
  148. }
  149. /**
  150. * Checks for presence of deprecated aliases.
  151. * @return bool Returns TRUE and generates a deprecation warning if deprecated aliases are present, FALSE otherwise.
  152. */
  153. private function checkForDeprecatedAliasUse(): bool {
  154. $deprecated = [];
  155. $replacements = [];
  156. foreach ($this->inputs as $name => $data) {
  157. if ($data['aliasUsed'] !== null && $data['aliasUsed'] === $this->options[$name]->getDeprecatedAlias()) {
  158. $deprecated[] = $this->options[$name]->getDeprecatedAlias();
  159. $replacements[] = $this->options[$name]->getLongAlias();
  160. }
  161. }
  162. if (empty($deprecated)) {
  163. return false;
  164. }
  165. fwrite(STDERR, "FreshRSS deprecation warning: the CLI option(s): " . implode(', ', $deprecated) .
  166. " are deprecated and will be removed in a future release. Use: " . implode(', ', $replacements) .
  167. " instead\n");
  168. return true;
  169. }
  170. /** @return array{long:array<string>,short:string}*/
  171. private function getGetoptInputs(): array {
  172. $getoptNotation = [
  173. 'none' => '',
  174. 'required' => ':',
  175. 'optional' => '::',
  176. ];
  177. $long = [];
  178. $short = '';
  179. foreach ($this->options as $option) {
  180. $long[] = $option->getLongAlias() . $getoptNotation[$option->getValueTaken()];
  181. $long[] = $option->getDeprecatedAlias() != null ? $option->getDeprecatedAlias() . $getoptNotation[$option->getValueTaken()] : '';
  182. $short .= $option->getShortAlias() != null ? $option->getShortAlias() . $getoptNotation[$option->getValueTaken()] : '';
  183. }
  184. return [
  185. 'long' => array_filter($long),
  186. 'short' => $short
  187. ];
  188. }
  189. private function getUsageMessage(string $command): string {
  190. $required = ['Usage: ' . basename($command)];
  191. $optional = [];
  192. foreach ($this->options as $name => $option) {
  193. $shortAlias = $option->getShortAlias() != null ? '-' . $option->getShortAlias() . ' ' : '';
  194. $longAlias = '--' . $option->getLongAlias() . ($option->getValueTaken() === 'required' ? '=<' . strtolower($name) . '>' : '');
  195. if ($this->inputs[$name]['required']) {
  196. $required[] = $shortAlias . $longAlias;
  197. } else {
  198. $optional[] = '[' . $shortAlias . $longAlias . ']';
  199. }
  200. }
  201. return implode(' ', $required) . ' ' . implode(' ', $optional);
  202. }
  203. private function makeInputRegex(): string {
  204. $shortWithValues = '';
  205. foreach ($this->options as $option) {
  206. if (($option->getValueTaken() === 'required' || $option->getValueTaken() === 'optional') && $option->getShortAlias() != null) {
  207. $shortWithValues .= $option->getShortAlias();
  208. }
  209. }
  210. return $shortWithValues === ''
  211. ? "/^--(?'long'[^=]+)|^-(?<short>\w+)/"
  212. : "/^--(?'long'[^=]+)|^-(?<short>(?(?=\w*[$shortWithValues])[^$shortWithValues]*[$shortWithValues]|\w+))/";
  213. }
  214. }