Add a path parser

master 1.3.0
Julien Rosset 6 years ago
parent 9298f862be
commit dcb5b5c410

@ -2,8 +2,8 @@
# PHPCommandLine # PHPCommandLine
__Command line management library in PHP (CLI)__ __Command line management library in PHP (CLI)__
![last release](https://badgen.net/github/release/darkelfe14728/PhpCommandLine) ![nb releases](https://badgen.net/github/tags/darkelfe14728/PhpCommandLine?label=Nb%20releases)
![nb releases](https://badgen.net/github/releases/darkelfe14728/PhpCommandLine) ![last release](https://badgen.net/github/tag/darkelfe14728/PhpCommandLine?label=Last%20release&color=yellow)
![licence](https://badgen.net/badge/license/CC%20BY%204.0/red) ![licence](https://badgen.net/badge/license/CC%20BY%204.0/red)
A command-line options parser with configurable expects and help auto generation. A command-line options parser with configurable expects and help auto generation.

@ -5,7 +5,7 @@ require_once '../vendor/autoload.php';
use CommandLine\Argument\Option\Flag; use CommandLine\Argument\Option\Flag;
use CommandLine\Argument\Option\Value; use CommandLine\Argument\Option\Value;
use CommandLine\Argument\Parser\IntegerParser; use CommandLine\Argument\Parser\IntegerParser;
use CommandLine\Argument\Parser\StringParser; use CommandLine\Argument\Parser\PathParser;
use CommandLine\CommandLine; use CommandLine\CommandLine;
$cmdline = new CommandLine('Test', 'Programme de test', 'php test.php'); $cmdline = new CommandLine('Test', 'Programme de test', 'php test.php');
@ -13,10 +13,11 @@ $cmdline->addDefaultArguments();
$cmdline->addOption(new Flag('array_form', false, 'Sous la forme d\'un tableau ?'."\n".'Ou pas')); $cmdline->addOption(new Flag('array_form', false, 'Sous la forme d\'un tableau ?'."\n".'Ou pas'));
$cmdline->addOption((new Value('days', 'Nombre jour', new IntegerParser(0, 365)))->setDefault(3)); $cmdline->addOption((new Value('days', 'Nombre jour', new IntegerParser(0, 365)))->setDefault(3));
$cmdline->addOption((new Value('years', 'Nombre d\'années', new IntegerParser(0)))->setDefault(5)); $cmdline->addOption((new Value('years', 'Nombre d\'années', new IntegerParser(0)))->setDefault(5));
$cmdline->addValue((new \CommandLine\Argument\Value\Value('path', 'Chemin sauvegarde images', new StringParser(), true))); $cmdline->addValue((new \CommandLine\Argument\Value\Value('path', 'Chemin sauvegarde images', new PathParser(), true)));
$args = $cmdline->parseExplicit(array('--help')); $args = $cmdline->parse();
$cmdline->treatDefaultArguments($args, false); $cmdline->treatDefaultArguments($args, false);
echo "\n"; echo "\n";
var_dump($args); var_dump($args);
var_dump((string)$args->path);

@ -0,0 +1,104 @@
<?php
/**
* Déclaration de la classe CommandLine\Argument\Parser\PathParser
*/
namespace CommandLine\Argument\Parser;
use InvalidArgumentException;
use UnexpectedValueException;
/**
* Parseur d'un chemin (fichier ou répertoire)
*
* Renvoie un {@see stdStringClass} avec les attributs suivants :
* - *fullpath* : chemin complet
* - directory : chemin du répertoire contenant
* - filename : nom du fichier (extension inclue)
* - basename : nom du fichier, sans l'extension
* - extension : extension du fichier
*
* @package CommandLine\Argument\Parser
*/
class PathParser implements IValueParser {
/**
* @var string[] Les expressions régulières pour identifier un chemin
*/
const REGEX_PATH = array(
'unix' => /** @lang PhpRegExp */ '@^(?<directory>/*(?:[^/\n]+(?:/+[^/\n]+)*/+)?)(?<filename>(?<basename>[^/\n]+?)(?:(?:\.(?<extension>[a-zA-Z0-9_]+))|(?:/+))?)$@',
'windows' => /** @lang PhpRegExp */ '@^(?<directory>(?:(?:(?:(?:[a-zA-Z]:)|[\\\\/])[\\\\/])|(?![\\\\/]))(?:[^<>:"/\\\\|?*]+(?:[\\\\/][^<>:"/\\\\|?*]+)*[\\\\/]+)?)(?<filename>(?<basename>[^<>:"/\\\\|?*]+?)(?:(?:\.(?<extension>[a-zA-Z0-9_]+))|(?:[\\\\/]))?)$@',
);
/**
* @var bool Est-ce que le fichier doit exister ?
*/
protected $_mustExist;
/**
* Crée un nouveau parseur
*
* @param bool $mustExists Est-ce que le chemin doit exister ?
*/
public function __construct ($mustExists = false) {
$this->setMustExists($mustExists);
}
/**
* Spécifie si le chemin doit exister ou non
*
* @param bool $mustExists True si le chemin doit exister, sinon False
*
* @return $this
*
* @see $_mustExists
*/
public function setMustExists ($mustExists = false) {
if (!is_bool($mustExists)) {
throw new InvalidArgumentException('Le contrôle si le chemin doit exister ou non n\'est pas booléen : ' . $mustExists);
}
$this->_mustExist = $mustExists;
return $this;
}
/**
* @inheritDoc
*/
public function parseValue ($arg) {
foreach (self::REGEX_PATH as $regex) {
if (preg_match($regex, $arg, $matches, PREG_UNMATCHED_AS_NULL)) {
if ($this->_mustExist && !file_exists($matches[0])) {
throw new UnexpectedValueException('Le chemin n\'existe pas : ' . $arg);
}
$out = new stdStringClass('fullpath');
$out->fullpath = $matches[0];
$out->directory = $matches['directory'] ?? '';
$out->filename = $matches['filename'] ?? '';
$out->basename = $matches['basename'] ?? '';
$out->extension = $matches['extension'] ?? '';
return $out;
}
}
throw new UnexpectedValueException('La valeur n\'est pas un chemin valide : ' . $arg);
}
/**
* @inheritDoc
*/
public function getValueDescription () {
return 'path';
}
/**
* Est-ce que le chemin doit exister ?
*
* @return bool True si le chemin doit exister, sinon False
*
* @see $_mustExists
*/
public function getMustExist () {
return $this->_mustExist;
}
}

@ -0,0 +1,37 @@
<?php
/**
* Déclaration de la classe CommandLine\Argument\Parser\stdStringClass
*/
namespace CommandLine\Argument\Parser;
use stdClass;
/**
* Une stdClass habituelle, mais avec un possibilite d'être traité comme une chaine de caractère
*
* L'un des attributs de la classe doit être choisi pour être utilisé comme valeur lors de la conversion en chaine de caractères
*/
class stdStringClass extends stdClass {
/**
* @var string Le nom de la propriété
*/
private $_property;
/**
* Crée une nouvelle instance
*
* @param string $property Le nom de la propriété
*/
public function __construct ($property) {
$this->_property = $property;
}
/**
* Converti l'instance en chaine de caractère
*
* @return string La valeur de l'attribut choisi (convertion forcé en chaine de caractères)
*/
public function __toString () {
return (string)$this->{$this->_property};
}
}
Loading…
Cancel
Save