CliOptionsParser.php 7.7 KB

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