51 lines
1.4 KiB
PHP
51 lines
1.4 KiB
PHP
<?php
|
|
|
|
readonly class argvParser
|
|
{
|
|
/**
|
|
* @param array<string, string> $options
|
|
* @param array<string, string> $arguments
|
|
*/
|
|
public function __construct(
|
|
private array $options = [],
|
|
private array $arguments = [],
|
|
) {}
|
|
|
|
public function getOptionsHelp(): string
|
|
{
|
|
$line = '';
|
|
foreach ($this->options as $option => $description) {
|
|
$line .= sprintf('[-%s (%s)] ', $option, $description);
|
|
}
|
|
foreach ($this->arguments as $argument => $description) {
|
|
$line .= sprintf('<%s (%s)> ', $argument, $description);
|
|
}
|
|
return $line;
|
|
}
|
|
|
|
public function parseArgv(array $argv): false|array
|
|
{
|
|
array_shift($argv); // shift the script name
|
|
if (count($argv) === 0) {
|
|
return false;
|
|
}
|
|
|
|
$parsed = array_map(fn() => false, $this->options);
|
|
while (str_starts_with($argv[0], '-')) {
|
|
$option = substr($argv[0], 1);
|
|
if ($this->options[$option]) {
|
|
$parsed[$option] = true;
|
|
}
|
|
array_shift($argv);
|
|
}
|
|
if (count($argv) !== count($this->arguments)) {
|
|
return false;
|
|
}
|
|
foreach ($this->arguments as $arg => $description) {
|
|
$parsed[$arg] = array_shift($argv);
|
|
}
|
|
|
|
return $parsed;
|
|
}
|
|
}
|