Create seperate argv parser
This commit is contained in:
50
includes/argvParser.php
Normal file
50
includes/argvParser.php
Normal file
@ -0,0 +1,50 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user