Implement stow config file and folder unwrapping
Move includes to their own folder, config.php will otherwise be included and cleans up nicely
This commit is contained in:
85
php/includes/argvParser.php
Normal file
85
php/includes/argvParser.php
Normal file
@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
class argParsed
|
||||
{
|
||||
public function __construct(
|
||||
private array $parsed = [],
|
||||
) {}
|
||||
|
||||
public function initOptions(array $options, mixed $default = false): self
|
||||
{
|
||||
foreach (array_keys($options) as $name) {
|
||||
$this->set($name, $default);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
return $this->parsed[$key] ?? $default;
|
||||
}
|
||||
|
||||
public function set(string $key, mixed $value): self
|
||||
{
|
||||
$this->parsed[$key] = $value;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getRest(): string
|
||||
{
|
||||
return $this->get('rest', '');
|
||||
}
|
||||
}
|
||||
|
||||
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): argParsed|false
|
||||
{
|
||||
array_shift($argv); // shift the script name
|
||||
|
||||
$parsed = (new argParsed())->initOptions($this->options);
|
||||
while (str_starts_with($argv[0] ?? '', '-')) {
|
||||
$option = substr($argv[0], 1, 1);
|
||||
if (substr($argv[0], 2, 1) === ':') {
|
||||
$data = substr($argv[0], 3);
|
||||
} else {
|
||||
$data = true;
|
||||
}
|
||||
if ($this->options[$option]) {
|
||||
$parsed->set($option, $data);
|
||||
}
|
||||
array_shift($argv);
|
||||
}
|
||||
if (count($argv) < count($this->arguments)) {
|
||||
return false;
|
||||
}
|
||||
foreach ($this->arguments as $arg => $description) {
|
||||
$parsed->set($arg, array_shift($argv));
|
||||
}
|
||||
$parsed->set('rest', implode(' ', $argv));
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user