First Commit
This commit is contained in:
+402
@@ -0,0 +1,402 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\RuntimeException;
|
||||
|
||||
/**
|
||||
* ArgvInput represents an input coming from the CLI arguments.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* $input = new ArgvInput();
|
||||
*
|
||||
* By default, the `$_SERVER['argv']` array is used for the input values.
|
||||
*
|
||||
* This can be overridden by explicitly passing the input values in the constructor:
|
||||
*
|
||||
* $input = new ArgvInput($_SERVER['argv']);
|
||||
*
|
||||
* If you pass it yourself, don't forget that the first element of the array
|
||||
* is the name of the running application.
|
||||
*
|
||||
* When passing an argument to the constructor, be sure that it respects
|
||||
* the same rules as the argv one. It's almost always better to use the
|
||||
* `StringInput` when you want to provide your own input.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* @see http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
* @see http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02
|
||||
*/
|
||||
class ArgvInput extends Input
|
||||
{
|
||||
/** @var list<string> */
|
||||
private array $tokens;
|
||||
private array $parsed;
|
||||
|
||||
/** @param list<string>|null $argv */
|
||||
public function __construct(?array $argv = null, ?InputDefinition $definition = null)
|
||||
{
|
||||
$argv ??= $_SERVER['argv'] ?? [];
|
||||
|
||||
foreach ($argv as $arg) {
|
||||
if (!\is_scalar($arg) && !$arg instanceof \Stringable) {
|
||||
throw new RuntimeException(\sprintf('Argument values expected to be all scalars, got "%s".', get_debug_type($arg)));
|
||||
}
|
||||
}
|
||||
|
||||
// strip the application name
|
||||
array_shift($argv);
|
||||
|
||||
$this->tokens = $argv;
|
||||
|
||||
parent::__construct($definition);
|
||||
}
|
||||
|
||||
/** @param list<string> $tokens */
|
||||
protected function setTokens(array $tokens): void
|
||||
{
|
||||
$this->tokens = $tokens;
|
||||
}
|
||||
|
||||
protected function parse(): void
|
||||
{
|
||||
$parseOptions = true;
|
||||
$this->parsed = $this->tokens;
|
||||
while (null !== $token = array_shift($this->parsed)) {
|
||||
$parseOptions = $this->parseToken($token, $parseOptions);
|
||||
}
|
||||
}
|
||||
|
||||
protected function parseToken(string $token, bool $parseOptions): bool
|
||||
{
|
||||
if ($parseOptions && '' == $token) {
|
||||
$this->parseArgument($token);
|
||||
} elseif ($parseOptions && '--' == $token) {
|
||||
return false;
|
||||
} elseif ($parseOptions && str_starts_with($token, '--')) {
|
||||
$this->parseLongOption($token);
|
||||
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
|
||||
$this->parseShortOption($token);
|
||||
} else {
|
||||
$this->parseArgument($token);
|
||||
}
|
||||
|
||||
return $parseOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a short option.
|
||||
*/
|
||||
private function parseShortOption(string $token): void
|
||||
{
|
||||
$name = substr($token, 1);
|
||||
|
||||
if (\strlen($name) > 1) {
|
||||
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
|
||||
// an option with a value (with no space)
|
||||
$this->addShortOption($name[0], substr($name, 1));
|
||||
} else {
|
||||
$this->parseShortOptionSet($name);
|
||||
}
|
||||
} else {
|
||||
$this->addShortOption($name, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a short option set.
|
||||
*
|
||||
* @throws RuntimeException When option given doesn't exist
|
||||
*/
|
||||
private function parseShortOptionSet(string $name): void
|
||||
{
|
||||
$len = \strlen($name);
|
||||
for ($i = 0; $i < $len; ++$i) {
|
||||
if (!$this->definition->hasShortcut($name[$i])) {
|
||||
$encoding = mb_detect_encoding($name, null, true);
|
||||
throw new RuntimeException(\sprintf('The "-%s" option does not exist.', false === $encoding ? $name[$i] : mb_substr($name, $i, 1, $encoding)));
|
||||
}
|
||||
|
||||
$option = $this->definition->getOptionForShortcut($name[$i]);
|
||||
if ($option->acceptValue()) {
|
||||
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$this->addLongOption($option->getName(), null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a long option.
|
||||
*/
|
||||
private function parseLongOption(string $token): void
|
||||
{
|
||||
$name = substr($token, 2);
|
||||
|
||||
if (false !== $pos = strpos($name, '=')) {
|
||||
if ('' === $value = substr($name, $pos + 1)) {
|
||||
array_unshift($this->parsed, $value);
|
||||
}
|
||||
$this->addLongOption(substr($name, 0, $pos), $value);
|
||||
} else {
|
||||
$this->addLongOption($name, null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an argument.
|
||||
*
|
||||
* @throws RuntimeException When too many arguments are given
|
||||
*/
|
||||
private function parseArgument(string $token): void
|
||||
{
|
||||
$c = \count($this->arguments);
|
||||
|
||||
// if input is expecting another argument, add it
|
||||
if ($this->definition->hasArgument($c)) {
|
||||
$arg = $this->definition->getArgument($c);
|
||||
$this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
|
||||
|
||||
// if last argument isArray(), append token to last argument
|
||||
} elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
|
||||
$arg = $this->definition->getArgument($c - 1);
|
||||
$this->arguments[$arg->getName()][] = $token;
|
||||
|
||||
// unexpected argument
|
||||
} else {
|
||||
$all = $this->definition->getArguments();
|
||||
$symfonyCommandName = null;
|
||||
if (($inputArgument = $all[$key = array_key_first($all) ?? ''] ?? null) && 'command' === $inputArgument->getName()) {
|
||||
$symfonyCommandName = $this->arguments['command'] ?? null;
|
||||
unset($all[$key]);
|
||||
}
|
||||
|
||||
if (\count($all)) {
|
||||
if ($symfonyCommandName) {
|
||||
$message = \sprintf('Too many arguments to "%s" command, expected arguments "%s".', $symfonyCommandName, implode('" "', array_keys($all)));
|
||||
} else {
|
||||
$message = \sprintf('Too many arguments, expected arguments "%s".', implode('" "', array_keys($all)));
|
||||
}
|
||||
} elseif ($symfonyCommandName) {
|
||||
$message = \sprintf('No arguments expected for "%s" command, got "%s".', $symfonyCommandName, $token);
|
||||
} else {
|
||||
$message = \sprintf('No arguments expected, got "%s".', $token);
|
||||
}
|
||||
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a short option value.
|
||||
*
|
||||
* @throws RuntimeException When option given doesn't exist
|
||||
*/
|
||||
private function addShortOption(string $shortcut, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasShortcut($shortcut)) {
|
||||
throw new RuntimeException(\sprintf('The "-%s" option does not exist.', $shortcut));
|
||||
}
|
||||
|
||||
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a long option value.
|
||||
*
|
||||
* @throws RuntimeException When option given doesn't exist
|
||||
*/
|
||||
private function addLongOption(string $name, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasOption($name)) {
|
||||
if (!$this->definition->hasNegation($name)) {
|
||||
throw new RuntimeException(\sprintf('The "--%s" option does not exist.', $name));
|
||||
}
|
||||
|
||||
$optionName = $this->definition->negationToName($name);
|
||||
if (null !== $value) {
|
||||
throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
|
||||
}
|
||||
$this->options[$optionName] = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$option = $this->definition->getOption($name);
|
||||
|
||||
if (null !== $value && !$option->acceptValue()) {
|
||||
throw new RuntimeException(\sprintf('The "--%s" option does not accept a value.', $name));
|
||||
}
|
||||
|
||||
if (\in_array($value, ['', null], true) && $option->acceptValue() && \count($this->parsed)) {
|
||||
// if option accepts an optional or mandatory argument
|
||||
// let's see if there is one provided
|
||||
$next = array_shift($this->parsed);
|
||||
if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
|
||||
$value = $next;
|
||||
} else {
|
||||
array_unshift($this->parsed, $next);
|
||||
}
|
||||
}
|
||||
|
||||
if (null === $value) {
|
||||
if ($option->isValueRequired()) {
|
||||
throw new RuntimeException(\sprintf('The "--%s" option requires a value.', $name));
|
||||
}
|
||||
|
||||
if (!$option->isArray() && !$option->isValueOptional()) {
|
||||
$value = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($option->isArray()) {
|
||||
$this->options[$name][] = $value;
|
||||
} else {
|
||||
$this->options[$name] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
public function getFirstArgument(): ?string
|
||||
{
|
||||
$isOption = false;
|
||||
foreach ($this->tokens as $i => $token) {
|
||||
if ($token && '-' === $token[0]) {
|
||||
if (str_contains($token, '=') || !isset($this->tokens[$i + 1])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If it's a long option, consider that everything after "--" is the option name.
|
||||
// Otherwise, use the last char (if it's a short option set, only the last one can take a value with space separator)
|
||||
$name = '-' === $token[1] ? substr($token, 2) : substr($token, -1);
|
||||
if (!isset($this->options[$name]) && !$this->definition->hasShortcut($name)) {
|
||||
// noop
|
||||
} elseif ((isset($this->options[$name]) || isset($this->options[$name = $this->definition->shortcutToName($name)])) && $this->tokens[$i + 1] === $this->options[$name]) {
|
||||
$isOption = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($isOption) {
|
||||
$isOption = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
return $token;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function hasParameterOption(string|array $values, bool $onlyParams = false): bool
|
||||
{
|
||||
$values = (array) $values;
|
||||
|
||||
foreach ($this->tokens as $token) {
|
||||
if ($onlyParams && '--' === $token) {
|
||||
return false;
|
||||
}
|
||||
foreach ($values as $value) {
|
||||
// Options with values:
|
||||
// For long options, test for '--option=' at beginning
|
||||
// For short options, test for '-o' at beginning
|
||||
$leading = str_starts_with($value, '--') ? $value.'=' : $value;
|
||||
if ($token === $value || '' !== $leading && str_starts_with($token, $leading)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed
|
||||
{
|
||||
$values = (array) $values;
|
||||
$tokens = $this->tokens;
|
||||
|
||||
while (0 < \count($tokens)) {
|
||||
$token = array_shift($tokens);
|
||||
if ($onlyParams && '--' === $token) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
foreach ($values as $value) {
|
||||
if ($token === $value) {
|
||||
return array_shift($tokens);
|
||||
}
|
||||
// Options with values:
|
||||
// For long options, test for '--option=' at beginning
|
||||
// For short options, test for '-o' at beginning
|
||||
$leading = str_starts_with($value, '--') ? $value.'=' : $value;
|
||||
if ('' !== $leading && str_starts_with($token, $leading)) {
|
||||
return substr($token, \strlen($leading));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns un-parsed and not validated tokens.
|
||||
*
|
||||
* @param bool $strip Whether to return the raw parameters (false) or the values after the command name (true)
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function getRawTokens(bool $strip = false): array
|
||||
{
|
||||
if (!$strip) {
|
||||
return $this->tokens;
|
||||
}
|
||||
|
||||
$parameters = [];
|
||||
$keep = false;
|
||||
foreach ($this->tokens as $value) {
|
||||
if (!$keep && $value === $this->getFirstArgument()) {
|
||||
$keep = true;
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($keep) {
|
||||
$parameters[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a stringified representation of the args passed to the command.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
$tokens = array_map(function ($token) {
|
||||
if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
|
||||
return $match[1].$this->escapeToken($match[2]);
|
||||
}
|
||||
|
||||
if ($token && '-' !== $token[0]) {
|
||||
return $this->escapeToken($token);
|
||||
}
|
||||
|
||||
return $token;
|
||||
}, $this->tokens);
|
||||
|
||||
return implode(' ', $tokens);
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\InvalidOptionException;
|
||||
|
||||
/**
|
||||
* ArrayInput represents an input provided as an array.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* $input = new ArrayInput(['command' => 'foo:bar', 'foo' => 'bar', '--bar' => 'foobar']);
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class ArrayInput extends Input
|
||||
{
|
||||
public function __construct(
|
||||
private array $parameters,
|
||||
?InputDefinition $definition = null,
|
||||
) {
|
||||
parent::__construct($definition);
|
||||
}
|
||||
|
||||
public function getFirstArgument(): ?string
|
||||
{
|
||||
foreach ($this->parameters as $param => $value) {
|
||||
if ($param && \is_string($param) && '-' === $param[0]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function hasParameterOption(string|array $values, bool $onlyParams = false): bool
|
||||
{
|
||||
$values = (array) $values;
|
||||
|
||||
foreach ($this->parameters as $k => $v) {
|
||||
if (!\is_int($k)) {
|
||||
$v = $k;
|
||||
}
|
||||
|
||||
if ($onlyParams && '--' === $v) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (\in_array($v, $values)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed
|
||||
{
|
||||
$values = (array) $values;
|
||||
|
||||
foreach ($this->parameters as $k => $v) {
|
||||
if ($onlyParams && ('--' === $k || (\is_int($k) && '--' === $v))) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
if (\is_int($k)) {
|
||||
if (\in_array($v, $values)) {
|
||||
return true;
|
||||
}
|
||||
} elseif (\in_array($k, $values)) {
|
||||
return $v;
|
||||
}
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a stringified representation of the args passed to the command.
|
||||
*/
|
||||
public function __toString(): string
|
||||
{
|
||||
$params = [];
|
||||
foreach ($this->parameters as $param => $val) {
|
||||
if ($param && \is_string($param) && '-' === $param[0]) {
|
||||
$glue = ('-' === $param[1]) ? '=' : ' ';
|
||||
if (\is_array($val)) {
|
||||
foreach ($val as $v) {
|
||||
$params[] = $param.('' != $v ? $glue.$this->escapeToken($v) : '');
|
||||
}
|
||||
} else {
|
||||
$params[] = $param.('' != $val ? $glue.$this->escapeToken($val) : '');
|
||||
}
|
||||
} else {
|
||||
$params[] = \is_array($val) ? implode(' ', array_map($this->escapeToken(...), $val)) : $this->escapeToken($val);
|
||||
}
|
||||
}
|
||||
|
||||
return implode(' ', $params);
|
||||
}
|
||||
|
||||
protected function parse(): void
|
||||
{
|
||||
foreach ($this->parameters as $key => $value) {
|
||||
if ('--' === $key) {
|
||||
return;
|
||||
}
|
||||
if (str_starts_with($key, '--')) {
|
||||
$this->addLongOption(substr($key, 2), $value);
|
||||
} elseif (str_starts_with($key, '-')) {
|
||||
$this->addShortOption(substr($key, 1), $value);
|
||||
} else {
|
||||
$this->addArgument($key, $value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a short option value.
|
||||
*
|
||||
* @throws InvalidOptionException When option given doesn't exist
|
||||
*/
|
||||
private function addShortOption(string $shortcut, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasShortcut($shortcut)) {
|
||||
throw new InvalidOptionException(\sprintf('The "-%s" option does not exist.', $shortcut));
|
||||
}
|
||||
|
||||
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a long option value.
|
||||
*
|
||||
* @throws InvalidOptionException When option given doesn't exist
|
||||
* @throws InvalidOptionException When a required value is missing
|
||||
*/
|
||||
private function addLongOption(string $name, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasOption($name)) {
|
||||
if (!$this->definition->hasNegation($name)) {
|
||||
throw new InvalidOptionException(\sprintf('The "--%s" option does not exist.', $name));
|
||||
}
|
||||
|
||||
$optionName = $this->definition->negationToName($name);
|
||||
$this->options[$optionName] = false;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$option = $this->definition->getOption($name);
|
||||
|
||||
if (null === $value) {
|
||||
if ($option->isValueRequired()) {
|
||||
throw new InvalidOptionException(\sprintf('The "--%s" option requires a value.', $name));
|
||||
}
|
||||
|
||||
if (!$option->isValueOptional()) {
|
||||
$value = true;
|
||||
}
|
||||
}
|
||||
|
||||
$this->options[$name] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an argument value.
|
||||
*
|
||||
* @throws InvalidArgumentException When argument given doesn't exist
|
||||
*/
|
||||
private function addArgument(string|int $name, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasArgument($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" argument does not exist.', $name));
|
||||
}
|
||||
|
||||
$this->arguments[$name] = $value;
|
||||
}
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input\File;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidFileException;
|
||||
use Symfony\Component\Mime\MimeTypes;
|
||||
|
||||
/**
|
||||
* Represents a file provided through console input.
|
||||
*
|
||||
* Inspired by HttpFoundation's UploadedFile, this class wraps a file provided
|
||||
* through console input (either pasted via terminal image protocols or typed as a path).
|
||||
*
|
||||
* @author Robin Chalas <robin.chalas@gmail.com>
|
||||
*/
|
||||
final class InputFile extends \SplFileInfo
|
||||
{
|
||||
/** @var string[] */
|
||||
private static array $tempFiles = [];
|
||||
private static bool $shutdownRegistered = false;
|
||||
|
||||
private ?string $mimeType = null;
|
||||
private bool $isTempFile;
|
||||
|
||||
public function __construct(
|
||||
string $path,
|
||||
bool $isTempFile = false,
|
||||
?string $mimeType = null,
|
||||
) {
|
||||
parent::__construct($path);
|
||||
|
||||
$this->isTempFile = $isTempFile;
|
||||
$this->mimeType = $mimeType;
|
||||
|
||||
if ($isTempFile) {
|
||||
if (!self::$shutdownRegistered) {
|
||||
register_shutdown_function(self::cleanupAll(...));
|
||||
self::$shutdownRegistered = true;
|
||||
}
|
||||
self::$tempFiles[$path] = $path;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidFileException when the temporary file cannot be created
|
||||
*/
|
||||
public static function fromData(string $data, ?string $format = null): self
|
||||
{
|
||||
$extension = $format ? '.'.$format : '';
|
||||
$tempPath = sys_get_temp_dir().'/symfony_input_'.bin2hex(random_bytes(8)).$extension;
|
||||
|
||||
$previousUmask = umask(0o077);
|
||||
|
||||
try {
|
||||
$handle = @fopen($tempPath, 'x');
|
||||
} finally {
|
||||
umask($previousUmask);
|
||||
}
|
||||
|
||||
if (false === $handle) {
|
||||
throw new InvalidFileException(\sprintf('Failed to create temporary file at "%s".', $tempPath));
|
||||
}
|
||||
|
||||
if (\strlen($data) !== @fwrite($handle, $data) || !@fclose($handle)) {
|
||||
@unlink($tempPath);
|
||||
|
||||
throw new InvalidFileException(\sprintf('Failed to create temporary file at "%s".', $tempPath));
|
||||
}
|
||||
|
||||
return new self($tempPath, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidFileException when the file does not exist
|
||||
*/
|
||||
public static function fromPath(string $path): self
|
||||
{
|
||||
$path = self::normalizePath($path);
|
||||
|
||||
if (!file_exists($path)) {
|
||||
throw new InvalidFileException(\sprintf('File "%s" does not exist.', $path));
|
||||
}
|
||||
|
||||
return new self($path, false);
|
||||
}
|
||||
|
||||
private static function normalizePath(string $path): string
|
||||
{
|
||||
$path = trim($path);
|
||||
|
||||
if (
|
||||
(str_starts_with($path, '"') && str_ends_with($path, '"'))
|
||||
|| (str_starts_with($path, "'") && str_ends_with($path, "'"))
|
||||
) {
|
||||
$path = substr($path, 1, -1);
|
||||
}
|
||||
|
||||
if (str_starts_with($path, 'file://')) {
|
||||
$path = urldecode(substr($path, 7));
|
||||
|
||||
if ('\\' === \DIRECTORY_SEPARATOR && preg_match('#^/[a-zA-Z]:/#', $path)) {
|
||||
$path = substr($path, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove backslash escapes (e.g., "\ " for escaped spaces) on non-Windows systems
|
||||
if ('\\' !== \DIRECTORY_SEPARATOR) {
|
||||
$path = preg_replace('/\\\\(.)/', '$1', $path) ?? $path;
|
||||
}
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function getMimeType(): ?string
|
||||
{
|
||||
if (null !== $this->mimeType) {
|
||||
return $this->mimeType;
|
||||
}
|
||||
|
||||
if (!$this->isValid()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (class_exists(MimeTypes::class)) {
|
||||
return $this->mimeType = MimeTypes::getDefault()->guessMimeType($this->getPathname());
|
||||
}
|
||||
|
||||
$finfo = new \finfo(\FILEINFO_MIME_TYPE);
|
||||
|
||||
return $this->mimeType = $finfo->file($this->getPathname()) ?: null;
|
||||
}
|
||||
|
||||
public function guessExtension(): ?string
|
||||
{
|
||||
$mimeType = $this->getMimeType();
|
||||
|
||||
if (null === $mimeType) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (class_exists(MimeTypes::class)) {
|
||||
$extensions = MimeTypes::getDefault()->getExtensions($mimeType);
|
||||
|
||||
return $extensions[0] ?? null;
|
||||
}
|
||||
|
||||
return match ($mimeType) {
|
||||
'image/png' => 'png',
|
||||
'image/jpeg' => 'jpg',
|
||||
'image/gif' => 'gif',
|
||||
'image/webp' => 'webp',
|
||||
'image/svg+xml' => 'svg',
|
||||
'application/pdf' => 'pdf',
|
||||
'text/plain' => 'txt',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidFileException when the file is invalid or the move/copy operation fails
|
||||
*/
|
||||
public function move(string $directory, ?string $name = null): self
|
||||
{
|
||||
if (!$this->isValid()) {
|
||||
throw new InvalidFileException('Cannot move an invalid file.');
|
||||
}
|
||||
|
||||
$name ??= $this->getFilename();
|
||||
$target = rtrim($directory, '/\\').\DIRECTORY_SEPARATOR.$name;
|
||||
|
||||
if (!is_dir($directory)) {
|
||||
if (false === @mkdir($directory, 0o777, true) && !is_dir($directory)) {
|
||||
throw new InvalidFileException(\sprintf('Unable to create the "%s" directory.', $directory));
|
||||
}
|
||||
} elseif (!is_writable($directory)) {
|
||||
throw new InvalidFileException(\sprintf('Unable to write in the "%s" directory.', $directory));
|
||||
}
|
||||
|
||||
if ($this->isTempFile) {
|
||||
if (!@rename($this->getPathname(), $target)) {
|
||||
throw new InvalidFileException(\sprintf('Could not move the file "%s" to "%s".', $this->getPathname(), $target));
|
||||
}
|
||||
unset(self::$tempFiles[$this->getPathname()]);
|
||||
} else {
|
||||
if (!@copy($this->getPathname(), $target)) {
|
||||
throw new InvalidFileException(\sprintf('Could not copy the file "%s" to "%s".', $this->getPathname(), $target));
|
||||
}
|
||||
}
|
||||
|
||||
@chmod($target, 0o666 & ~umask());
|
||||
|
||||
return new self($target, false, $this->mimeType);
|
||||
}
|
||||
|
||||
public function cleanup(): void
|
||||
{
|
||||
if (!$this->isTempFile) {
|
||||
return;
|
||||
}
|
||||
|
||||
$path = $this->getPathname();
|
||||
|
||||
if (file_exists($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
|
||||
unset(self::$tempFiles[$path]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
public static function cleanupAll(): void
|
||||
{
|
||||
foreach (self::$tempFiles as $path) {
|
||||
if (file_exists($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
}
|
||||
|
||||
self::$tempFiles = [];
|
||||
}
|
||||
|
||||
public function isValid(): bool
|
||||
{
|
||||
return is_file($this->getPathname()) && is_readable($this->getPathname());
|
||||
}
|
||||
|
||||
public function isTempFile(): bool
|
||||
{
|
||||
return $this->isTempFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws InvalidFileException when the file is invalid or cannot be read
|
||||
*/
|
||||
public function getContents(): string
|
||||
{
|
||||
if (!$this->isValid()) {
|
||||
throw new InvalidFileException('Cannot read an invalid file.');
|
||||
}
|
||||
|
||||
$contents = @file_get_contents($this->getPathname());
|
||||
|
||||
if (false === $contents) {
|
||||
throw new InvalidFileException(\sprintf('Could not read file "%s".', $this->getPathname()));
|
||||
}
|
||||
|
||||
return $contents;
|
||||
}
|
||||
|
||||
public function getHumanReadableSize(): string
|
||||
{
|
||||
$size = $this->getSize();
|
||||
$units = ['B', 'KB', 'MB', 'GB'];
|
||||
$power = $size > 0 ? floor(log($size, 1024)) : 0;
|
||||
$power = min($power, \count($units) - 1);
|
||||
|
||||
return \sprintf('%.1f %s', $size / (1024 ** $power), $units[$power]);
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\RuntimeException;
|
||||
|
||||
/**
|
||||
* Input is the base class for all concrete Input classes.
|
||||
*
|
||||
* Three concrete classes are provided by default:
|
||||
*
|
||||
* * `ArgvInput`: The input comes from the CLI arguments (argv)
|
||||
* * `StringInput`: The input is provided as a string
|
||||
* * `ArrayInput`: The input is provided as an array
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
abstract class Input implements RawInputInterface, StreamableInputInterface
|
||||
{
|
||||
protected InputDefinition $definition;
|
||||
/** @var resource */
|
||||
protected $stream;
|
||||
protected array $options = [];
|
||||
protected array $arguments = [];
|
||||
protected bool $interactive = true;
|
||||
|
||||
public function __construct(?InputDefinition $definition = null)
|
||||
{
|
||||
if (null === $definition) {
|
||||
$this->definition = new InputDefinition();
|
||||
} else {
|
||||
$this->bind($definition);
|
||||
$this->validate();
|
||||
}
|
||||
}
|
||||
|
||||
public function bind(InputDefinition $definition): void
|
||||
{
|
||||
$this->arguments = [];
|
||||
$this->options = [];
|
||||
$this->definition = $definition;
|
||||
|
||||
$this->parse();
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes command line arguments.
|
||||
*/
|
||||
abstract protected function parse(): void;
|
||||
|
||||
public function validate(): void
|
||||
{
|
||||
$definition = $this->definition;
|
||||
$givenArguments = $this->arguments;
|
||||
|
||||
$missingArguments = array_filter(array_keys($definition->getArguments()), static fn ($argument) => !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired());
|
||||
|
||||
if (\count($missingArguments) > 0) {
|
||||
throw new RuntimeException(\sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments)));
|
||||
}
|
||||
}
|
||||
|
||||
public function isInteractive(): bool
|
||||
{
|
||||
return $this->interactive;
|
||||
}
|
||||
|
||||
public function setInteractive(bool $interactive): void
|
||||
{
|
||||
$this->interactive = $interactive;
|
||||
}
|
||||
|
||||
public function getArguments(): array
|
||||
{
|
||||
return array_merge($this->definition->getArgumentDefaults(), $this->arguments);
|
||||
}
|
||||
|
||||
public function getArgument(string $name): mixed
|
||||
{
|
||||
if (!$this->definition->hasArgument($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" argument does not exist.', $name));
|
||||
}
|
||||
|
||||
return $this->arguments[$name] ?? $this->definition->getArgument($name)->getDefault();
|
||||
}
|
||||
|
||||
public function setArgument(string $name, mixed $value): void
|
||||
{
|
||||
if (!$this->definition->hasArgument($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" argument does not exist.', $name));
|
||||
}
|
||||
|
||||
$this->arguments[$name] = $value;
|
||||
}
|
||||
|
||||
public function hasArgument(string $name): bool
|
||||
{
|
||||
return $this->definition->hasArgument($name);
|
||||
}
|
||||
|
||||
public function getOptions(): array
|
||||
{
|
||||
return array_merge($this->definition->getOptionDefaults(), $this->options);
|
||||
}
|
||||
|
||||
public function getOption(string $name): mixed
|
||||
{
|
||||
if ($this->definition->hasNegation($name)) {
|
||||
if (null === $value = $this->getOption($this->definition->negationToName($name))) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
return !$value;
|
||||
}
|
||||
|
||||
if (!$this->definition->hasOption($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" option does not exist.', $name));
|
||||
}
|
||||
|
||||
return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();
|
||||
}
|
||||
|
||||
public function setOption(string $name, mixed $value): void
|
||||
{
|
||||
if ($this->definition->hasNegation($name)) {
|
||||
$this->options[$this->definition->negationToName($name)] = !$value;
|
||||
|
||||
return;
|
||||
} elseif (!$this->definition->hasOption($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" option does not exist.', $name));
|
||||
}
|
||||
|
||||
$this->options[$name] = $value;
|
||||
}
|
||||
|
||||
public function hasOption(string $name): bool
|
||||
{
|
||||
return $this->definition->hasOption($name) || $this->definition->hasNegation($name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escapes a token through escapeshellarg if it contains unsafe chars.
|
||||
*/
|
||||
public function escapeToken(string $token): string
|
||||
{
|
||||
return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource $stream
|
||||
*/
|
||||
public function setStream($stream): void
|
||||
{
|
||||
$this->stream = $stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return resource
|
||||
*/
|
||||
public function getStream()
|
||||
{
|
||||
return $this->stream;
|
||||
}
|
||||
|
||||
public function getRawArguments(): array
|
||||
{
|
||||
return $this->arguments;
|
||||
}
|
||||
|
||||
public function getRawOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
public function unparse(?array $optionNames = null): array
|
||||
{
|
||||
$rawOptions = $this->getRawOptions();
|
||||
|
||||
$filteredRawOptions = null === $optionNames
|
||||
? $rawOptions
|
||||
: array_intersect_key($rawOptions, array_fill_keys($optionNames, ''));
|
||||
|
||||
$unparsedOptions = [];
|
||||
|
||||
foreach ($filteredRawOptions as $optionName => $parsedOption) {
|
||||
$option = $this->definition->getOption($optionName);
|
||||
|
||||
$unparsedOptions[] = match (true) {
|
||||
$option->isNegatable() => [\sprintf('--%s%s', $parsedOption ? '' : 'no-', $optionName)],
|
||||
!$option->acceptValue() => [\sprintf('--%s', $optionName)],
|
||||
$option->isArray() => array_map(static fn ($item) => \sprintf('--%s=%s', $optionName, $item), $parsedOption),
|
||||
default => [\sprintf('--%s=%s', $optionName, $parsedOption)],
|
||||
};
|
||||
}
|
||||
|
||||
return array_merge(...$unparsedOptions);
|
||||
}
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Completion\CompletionInput;
|
||||
use Symfony\Component\Console\Completion\CompletionSuggestions;
|
||||
use Symfony\Component\Console\Completion\Suggestion;
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\LogicException;
|
||||
|
||||
/**
|
||||
* Represents a command line argument.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class InputArgument
|
||||
{
|
||||
/**
|
||||
* Providing an argument is required (e.g. just 'app:foo' is not allowed).
|
||||
*/
|
||||
public const REQUIRED = 1;
|
||||
|
||||
/**
|
||||
* Providing an argument is optional (e.g. 'app:foo' and 'app:foo bar' are both allowed). This is the default behavior of arguments.
|
||||
*/
|
||||
public const OPTIONAL = 2;
|
||||
|
||||
/**
|
||||
* The argument accepts multiple values and turn them into an array (e.g. 'app:foo bar baz' will result in value ['bar', 'baz']).
|
||||
*/
|
||||
public const IS_ARRAY = 4;
|
||||
|
||||
private int $mode;
|
||||
private mixed $default;
|
||||
|
||||
/**
|
||||
* @param string $name The argument name
|
||||
* @param int-mask-of<InputArgument::*>|null $mode The argument mode: a bit mask of self::REQUIRED, self::OPTIONAL and self::IS_ARRAY
|
||||
* @param string $description A description text
|
||||
* @param mixed $default The default value (for self::OPTIONAL mode only)
|
||||
* @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
|
||||
*
|
||||
* @throws InvalidArgumentException When argument mode is not valid
|
||||
*/
|
||||
public function __construct(
|
||||
private string $name,
|
||||
?int $mode = null,
|
||||
private string $description = '',
|
||||
mixed $default = null,
|
||||
private \Closure|array $suggestedValues = [],
|
||||
) {
|
||||
// If not explicitly marked as required, we assume the value to be optional
|
||||
$mode = self::REQUIRED === (self::REQUIRED & $mode) ? $mode : (self::OPTIONAL | $mode);
|
||||
if ($mode >= (self::IS_ARRAY << 1) || $mode < 1) {
|
||||
throw new InvalidArgumentException(\sprintf('Argument mode "%s" is not valid.', $mode));
|
||||
}
|
||||
|
||||
if ((self::REQUIRED | self::OPTIONAL) === ((self::REQUIRED | self::OPTIONAL) & $mode)) {
|
||||
trigger_deprecation('symfony/console', '8.1', 'Argument "%s" mode should specify either required or optional.', $name);
|
||||
}
|
||||
|
||||
$this->mode = $mode;
|
||||
|
||||
$this->setDefault($default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the argument name.
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the argument is required.
|
||||
*
|
||||
* @return bool true if parameter mode is self::REQUIRED, false otherwise
|
||||
*/
|
||||
public function isRequired(): bool
|
||||
{
|
||||
return self::REQUIRED === (self::REQUIRED & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the argument can take multiple values.
|
||||
*
|
||||
* @return bool true if mode is self::IS_ARRAY, false otherwise
|
||||
*/
|
||||
public function isArray(): bool
|
||||
{
|
||||
return self::IS_ARRAY === (self::IS_ARRAY & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default value.
|
||||
*/
|
||||
public function setDefault(mixed $default): void
|
||||
{
|
||||
if ($this->isRequired() && null !== $default) {
|
||||
throw new LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.');
|
||||
}
|
||||
|
||||
if ($this->isArray()) {
|
||||
if (null === $default) {
|
||||
$default = [];
|
||||
} elseif (!\is_array($default)) {
|
||||
throw new LogicException('A default value for an array argument must be an array.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->default = $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default value.
|
||||
*/
|
||||
public function getDefault(): mixed
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the argument has values for input completion.
|
||||
*/
|
||||
public function hasCompletion(): bool
|
||||
{
|
||||
return [] !== $this->suggestedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies suggestions when command resolves possible completion options for input.
|
||||
*
|
||||
* @see Command::complete()
|
||||
*/
|
||||
public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
|
||||
{
|
||||
$values = $this->suggestedValues;
|
||||
if ($values instanceof \Closure && !\is_array($values = $values($input))) {
|
||||
throw new LogicException(\sprintf('Closure for argument "%s" must return an array. Got "%s".', $this->name, get_debug_type($values)));
|
||||
}
|
||||
if ($values) {
|
||||
$suggestions->suggestValues($values);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description text.
|
||||
*/
|
||||
public function getDescription(): string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
/**
|
||||
* InputAwareInterface should be implemented by classes that depends on the
|
||||
* Console Input.
|
||||
*
|
||||
* @author Wouter J <waldio.webdesign@gmail.com>
|
||||
*/
|
||||
interface InputAwareInterface
|
||||
{
|
||||
/**
|
||||
* Sets the Console Input.
|
||||
*/
|
||||
public function setInput(InputInterface $input): void;
|
||||
}
|
||||
+402
@@ -0,0 +1,402 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\LogicException;
|
||||
|
||||
/**
|
||||
* A InputDefinition represents a set of valid command line arguments and options.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* $definition = new InputDefinition([
|
||||
* new InputArgument('name', InputArgument::REQUIRED),
|
||||
* new InputOption('foo', 'f', InputOption::VALUE_REQUIRED),
|
||||
* ]);
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class InputDefinition
|
||||
{
|
||||
private array $arguments = [];
|
||||
private int $requiredCount = 0;
|
||||
private ?InputArgument $lastArrayArgument = null;
|
||||
private ?InputArgument $lastOptionalArgument = null;
|
||||
private array $options = [];
|
||||
private array $negations = [];
|
||||
private array $shortcuts = [];
|
||||
|
||||
/**
|
||||
* @param array $definition An array of InputArgument and InputOption instance
|
||||
*/
|
||||
public function __construct(array $definition = [])
|
||||
{
|
||||
$this->setDefinition($definition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the definition of the input.
|
||||
*/
|
||||
public function setDefinition(array $definition): void
|
||||
{
|
||||
$arguments = [];
|
||||
$options = [];
|
||||
foreach ($definition as $item) {
|
||||
if ($item instanceof InputOption) {
|
||||
$options[] = $item;
|
||||
} else {
|
||||
$arguments[] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
$this->setArguments($arguments);
|
||||
$this->setOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the InputArgument objects.
|
||||
*
|
||||
* @param InputArgument[] $arguments An array of InputArgument objects
|
||||
*/
|
||||
public function setArguments(array $arguments = []): void
|
||||
{
|
||||
$this->arguments = [];
|
||||
$this->requiredCount = 0;
|
||||
$this->lastOptionalArgument = null;
|
||||
$this->lastArrayArgument = null;
|
||||
$this->addArguments($arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of InputArgument objects.
|
||||
*
|
||||
* @param InputArgument[] $arguments An array of InputArgument objects
|
||||
*/
|
||||
public function addArguments(?array $arguments = []): void
|
||||
{
|
||||
if (null !== $arguments) {
|
||||
foreach ($arguments as $argument) {
|
||||
$this->addArgument($argument);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LogicException When incorrect argument is given
|
||||
*/
|
||||
public function addArgument(InputArgument $argument): void
|
||||
{
|
||||
if (isset($this->arguments[$argument->getName()])) {
|
||||
throw new LogicException(\sprintf('An argument with name "%s" already exists.', $argument->getName()));
|
||||
}
|
||||
|
||||
if (null !== $this->lastArrayArgument) {
|
||||
throw new LogicException(\sprintf('Cannot add a required argument "%s" after an array argument "%s".', $argument->getName(), $this->lastArrayArgument->getName()));
|
||||
}
|
||||
|
||||
if ($argument->isRequired() && null !== $this->lastOptionalArgument) {
|
||||
throw new LogicException(\sprintf('Cannot add a required argument "%s" after an optional one "%s".', $argument->getName(), $this->lastOptionalArgument->getName()));
|
||||
}
|
||||
|
||||
if ($argument->isArray()) {
|
||||
$this->lastArrayArgument = $argument;
|
||||
}
|
||||
|
||||
if ($argument->isRequired()) {
|
||||
++$this->requiredCount;
|
||||
} else {
|
||||
$this->lastOptionalArgument = $argument;
|
||||
}
|
||||
|
||||
$this->arguments[$argument->getName()] = $argument;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an InputArgument by name or by position.
|
||||
*
|
||||
* @throws InvalidArgumentException When argument given doesn't exist
|
||||
*/
|
||||
public function getArgument(string|int $name): InputArgument
|
||||
{
|
||||
if (!$this->hasArgument($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "%s" argument does not exist.', $name));
|
||||
}
|
||||
|
||||
$arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments;
|
||||
|
||||
return $arguments[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an InputArgument object exists by name or position.
|
||||
*/
|
||||
public function hasArgument(string|int $name): bool
|
||||
{
|
||||
$arguments = \is_int($name) ? array_values($this->arguments) : $this->arguments;
|
||||
|
||||
return isset($arguments[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the array of InputArgument objects.
|
||||
*
|
||||
* @return InputArgument[]
|
||||
*/
|
||||
public function getArguments(): array
|
||||
{
|
||||
return $this->arguments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of InputArguments.
|
||||
*/
|
||||
public function getArgumentCount(): int
|
||||
{
|
||||
return null !== $this->lastArrayArgument ? \PHP_INT_MAX : \count($this->arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of required InputArguments.
|
||||
*/
|
||||
public function getArgumentRequiredCount(): int
|
||||
{
|
||||
return $this->requiredCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string|bool|int|float|array|null>
|
||||
*/
|
||||
public function getArgumentDefaults(): array
|
||||
{
|
||||
$values = [];
|
||||
foreach ($this->arguments as $argument) {
|
||||
$values[$argument->getName()] = $argument->getDefault();
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the InputOption objects.
|
||||
*
|
||||
* @param InputOption[] $options An array of InputOption objects
|
||||
*/
|
||||
public function setOptions(array $options = []): void
|
||||
{
|
||||
$this->options = [];
|
||||
$this->shortcuts = [];
|
||||
$this->negations = [];
|
||||
$this->addOptions($options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an array of InputOption objects.
|
||||
*
|
||||
* @param InputOption[] $options An array of InputOption objects
|
||||
*/
|
||||
public function addOptions(array $options = []): void
|
||||
{
|
||||
foreach ($options as $option) {
|
||||
$this->addOption($option);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws LogicException When option given already exist
|
||||
*/
|
||||
public function addOption(InputOption $option): void
|
||||
{
|
||||
if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) {
|
||||
throw new LogicException(\sprintf('An option named "%s" already exists.', $option->getName()));
|
||||
}
|
||||
if (isset($this->negations[$option->getName()])) {
|
||||
throw new LogicException(\sprintf('An option named "%s" already exists.', $option->getName()));
|
||||
}
|
||||
|
||||
if ($option->getShortcut()) {
|
||||
foreach (explode('|', $option->getShortcut()) as $shortcut) {
|
||||
if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) {
|
||||
throw new LogicException(\sprintf('An option with shortcut "%s" already exists.', $shortcut));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->options[$option->getName()] = $option;
|
||||
if ($option->getShortcut()) {
|
||||
foreach (explode('|', $option->getShortcut()) as $shortcut) {
|
||||
$this->shortcuts[$shortcut] = $option->getName();
|
||||
}
|
||||
}
|
||||
|
||||
if ($option->isNegatable()) {
|
||||
$negatedName = 'no-'.$option->getName();
|
||||
if (isset($this->options[$negatedName])) {
|
||||
throw new LogicException(\sprintf('An option named "%s" already exists.', $negatedName));
|
||||
}
|
||||
$this->negations[$negatedName] = $option->getName();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an InputOption by name.
|
||||
*
|
||||
* @throws InvalidArgumentException When option given doesn't exist
|
||||
*/
|
||||
public function getOption(string $name): InputOption
|
||||
{
|
||||
if (!$this->hasOption($name)) {
|
||||
throw new InvalidArgumentException(\sprintf('The "--%s" option does not exist.', $name));
|
||||
}
|
||||
|
||||
return $this->options[$name];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an InputOption object exists by name.
|
||||
*
|
||||
* This method can't be used to check if the user included the option when
|
||||
* executing the command (use getOption() instead).
|
||||
*/
|
||||
public function hasOption(string $name): bool
|
||||
{
|
||||
return isset($this->options[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the array of InputOption objects.
|
||||
*
|
||||
* @return InputOption[]
|
||||
*/
|
||||
public function getOptions(): array
|
||||
{
|
||||
return $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an InputOption object exists by shortcut.
|
||||
*/
|
||||
public function hasShortcut(string $name): bool
|
||||
{
|
||||
return isset($this->shortcuts[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if an InputOption object exists by negated name.
|
||||
*/
|
||||
public function hasNegation(string $name): bool
|
||||
{
|
||||
return isset($this->negations[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets an InputOption by shortcut.
|
||||
*/
|
||||
public function getOptionForShortcut(string $shortcut): InputOption
|
||||
{
|
||||
return $this->getOption($this->shortcutToName($shortcut));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string|bool|int|float|array|null>
|
||||
*/
|
||||
public function getOptionDefaults(): array
|
||||
{
|
||||
$values = [];
|
||||
foreach ($this->options as $option) {
|
||||
$values[$option->getName()] = $option->getDefault();
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the InputOption name given a shortcut.
|
||||
*
|
||||
* @throws InvalidArgumentException When option given does not exist
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function shortcutToName(string $shortcut): string
|
||||
{
|
||||
if (!isset($this->shortcuts[$shortcut])) {
|
||||
throw new InvalidArgumentException(\sprintf('The "-%s" option does not exist.', $shortcut));
|
||||
}
|
||||
|
||||
return $this->shortcuts[$shortcut];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the InputOption name given a negation.
|
||||
*
|
||||
* @throws InvalidArgumentException When option given does not exist
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function negationToName(string $negation): string
|
||||
{
|
||||
if (!isset($this->negations[$negation])) {
|
||||
throw new InvalidArgumentException(\sprintf('The "--%s" option does not exist.', $negation));
|
||||
}
|
||||
|
||||
return $this->negations[$negation];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the synopsis.
|
||||
*/
|
||||
public function getSynopsis(bool $short = false): string
|
||||
{
|
||||
$elements = [];
|
||||
|
||||
if ($short && $this->getOptions()) {
|
||||
$elements[] = '[options]';
|
||||
} elseif (!$short) {
|
||||
foreach ($this->getOptions() as $option) {
|
||||
$value = '';
|
||||
if ($option->acceptValue()) {
|
||||
$value = \sprintf(
|
||||
' %s%s%s',
|
||||
$option->isValueOptional() ? '[' : '',
|
||||
strtoupper($option->getName()),
|
||||
$option->isValueOptional() ? ']' : ''
|
||||
);
|
||||
}
|
||||
|
||||
$shortcut = $option->getShortcut() ? \sprintf('-%s|', $option->getShortcut()) : '';
|
||||
$negation = $option->isNegatable() ? \sprintf('|--no-%s', $option->getName()) : '';
|
||||
$elements[] = \sprintf('[%s--%s%s%s]', $shortcut, $option->getName(), $value, $negation);
|
||||
}
|
||||
}
|
||||
|
||||
if (\count($elements) && $this->getArguments()) {
|
||||
$elements[] = '[--]';
|
||||
}
|
||||
|
||||
$tail = '';
|
||||
foreach ($this->getArguments() as $argument) {
|
||||
$element = '<'.$argument->getName().'>';
|
||||
if ($argument->isArray()) {
|
||||
$element .= '...';
|
||||
}
|
||||
|
||||
if (!$argument->isRequired()) {
|
||||
$element = '['.$element;
|
||||
$tail .= ']';
|
||||
}
|
||||
|
||||
$elements[] = $element;
|
||||
}
|
||||
|
||||
return implode(' ', $elements).$tail;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\RuntimeException;
|
||||
|
||||
/**
|
||||
* InputInterface is the interface implemented by all input classes.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
interface InputInterface
|
||||
{
|
||||
/**
|
||||
* Returns the first argument from the raw parameters (not parsed).
|
||||
*/
|
||||
public function getFirstArgument(): ?string;
|
||||
|
||||
/**
|
||||
* Returns true if the raw parameters (not parsed) contain a value.
|
||||
*
|
||||
* This method is to be used to introspect the input parameters
|
||||
* before they have been validated. It must be used carefully.
|
||||
* Does not necessarily return the correct result for short options
|
||||
* when multiple flags are combined in the same option.
|
||||
*
|
||||
* @param string|array $values The values to look for in the raw parameters (can be an array)
|
||||
* @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal
|
||||
*/
|
||||
public function hasParameterOption(string|array $values, bool $onlyParams = false): bool;
|
||||
|
||||
/**
|
||||
* Returns the value of a raw option (not parsed).
|
||||
*
|
||||
* This method is to be used to introspect the input parameters
|
||||
* before they have been validated. It must be used carefully.
|
||||
* Does not necessarily return the correct result for short options
|
||||
* when multiple flags are combined in the same option.
|
||||
*
|
||||
* @param string|array $values The value(s) to look for in the raw parameters (can be an array)
|
||||
* @param string|bool|int|float|array|null $default The default value to return if no result is found
|
||||
* @param bool $onlyParams Only check real parameters, skip those following an end of options (--) signal
|
||||
*/
|
||||
public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed;
|
||||
|
||||
/**
|
||||
* Binds the current Input instance with the given arguments and options.
|
||||
*
|
||||
* @throws RuntimeException
|
||||
*/
|
||||
public function bind(InputDefinition $definition): void;
|
||||
|
||||
/**
|
||||
* Validates the input.
|
||||
*
|
||||
* @throws RuntimeException When not enough arguments are given
|
||||
*/
|
||||
public function validate(): void;
|
||||
|
||||
/**
|
||||
* Returns all the given arguments merged with the default values.
|
||||
*
|
||||
* @return array<string|bool|int|float|array|null>
|
||||
*/
|
||||
public function getArguments(): array;
|
||||
|
||||
/**
|
||||
* Returns the argument value for a given argument name.
|
||||
*
|
||||
* @throws InvalidArgumentException When argument given doesn't exist
|
||||
*/
|
||||
public function getArgument(string $name): mixed;
|
||||
|
||||
/**
|
||||
* Sets an argument value by name.
|
||||
*
|
||||
* @throws InvalidArgumentException When argument given doesn't exist
|
||||
*/
|
||||
public function setArgument(string $name, mixed $value): void;
|
||||
|
||||
/**
|
||||
* Returns true if an InputArgument object exists by name or position.
|
||||
*/
|
||||
public function hasArgument(string $name): bool;
|
||||
|
||||
/**
|
||||
* Returns all the given options merged with the default values.
|
||||
*
|
||||
* @return array<string|bool|int|float|array|null>
|
||||
*/
|
||||
public function getOptions(): array;
|
||||
|
||||
/**
|
||||
* Returns the option value for a given option name.
|
||||
*
|
||||
* @throws InvalidArgumentException When option given doesn't exist
|
||||
*/
|
||||
public function getOption(string $name): mixed;
|
||||
|
||||
/**
|
||||
* Sets an option value by name.
|
||||
*
|
||||
* @throws InvalidArgumentException When option given doesn't exist
|
||||
*/
|
||||
public function setOption(string $name, mixed $value): void;
|
||||
|
||||
/**
|
||||
* Returns true if an InputOption object exists by name.
|
||||
*/
|
||||
public function hasOption(string $name): bool;
|
||||
|
||||
/**
|
||||
* Is this input means interactive?
|
||||
*/
|
||||
public function isInteractive(): bool;
|
||||
|
||||
/**
|
||||
* Sets the input interactivity.
|
||||
*/
|
||||
public function setInteractive(bool $interactive): void;
|
||||
|
||||
/**
|
||||
* Returns a stringified representation of the args passed to the command.
|
||||
*
|
||||
* InputArguments MUST be escaped as well as the InputOption values passed to the command.
|
||||
*/
|
||||
public function __toString(): string;
|
||||
}
|
||||
+270
@@ -0,0 +1,270 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Command\Command;
|
||||
use Symfony\Component\Console\Completion\CompletionInput;
|
||||
use Symfony\Component\Console\Completion\CompletionSuggestions;
|
||||
use Symfony\Component\Console\Completion\Suggestion;
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
use Symfony\Component\Console\Exception\LogicException;
|
||||
|
||||
/**
|
||||
* Represents a command line option.
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class InputOption
|
||||
{
|
||||
/**
|
||||
* Do not accept input for the option (e.g. --yell). This is the default behavior of options.
|
||||
*/
|
||||
public const VALUE_NONE = 1;
|
||||
|
||||
/**
|
||||
* A value must be passed when the option is used (e.g. --iterations=5 or -i5).
|
||||
*/
|
||||
public const VALUE_REQUIRED = 2;
|
||||
|
||||
/**
|
||||
* The option may or may not have a value (e.g. --yell or --yell=loud).
|
||||
*/
|
||||
public const VALUE_OPTIONAL = 4;
|
||||
|
||||
/**
|
||||
* The option accepts multiple values (e.g. --dir=/foo --dir=/bar).
|
||||
*/
|
||||
public const VALUE_IS_ARRAY = 8;
|
||||
|
||||
/**
|
||||
* The option allows passing a negated variant (e.g. --ansi or --no-ansi).
|
||||
*/
|
||||
public const VALUE_NEGATABLE = 16;
|
||||
|
||||
private string $name;
|
||||
private ?string $shortcut;
|
||||
private int $mode;
|
||||
private mixed $default;
|
||||
|
||||
/**
|
||||
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
|
||||
* @param int-mask-of<InputOption::*>|null $mode The option mode: One of the VALUE_* constants
|
||||
* @param mixed $default The default value (must be null for self::VALUE_NONE)
|
||||
* @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
|
||||
*
|
||||
* @throws InvalidArgumentException If option mode is invalid or incompatible
|
||||
*/
|
||||
public function __construct(
|
||||
string $name,
|
||||
string|array|null $shortcut = null,
|
||||
?int $mode = null,
|
||||
private string $description = '',
|
||||
mixed $default = null,
|
||||
private array|\Closure $suggestedValues = [],
|
||||
) {
|
||||
if (str_starts_with($name, '--')) {
|
||||
$name = substr($name, 2);
|
||||
}
|
||||
|
||||
if (!$name) {
|
||||
throw new InvalidArgumentException('An option name cannot be empty.');
|
||||
}
|
||||
|
||||
if ('' === $shortcut || [] === $shortcut) {
|
||||
$shortcut = null;
|
||||
}
|
||||
|
||||
if (null !== $shortcut) {
|
||||
if (\is_array($shortcut)) {
|
||||
$shortcut = implode('|', $shortcut);
|
||||
}
|
||||
$shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-'));
|
||||
$shortcuts = array_filter($shortcuts, 'strlen');
|
||||
$shortcut = implode('|', $shortcuts);
|
||||
|
||||
if ('' === $shortcut) {
|
||||
throw new InvalidArgumentException('An option shortcut cannot be empty.');
|
||||
}
|
||||
}
|
||||
|
||||
// If not explicitly marked as required or optional, we assume the value accepts no input
|
||||
$mode = self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $mode) || self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $mode) ? $mode : (self::VALUE_NONE | $mode);
|
||||
if ($mode >= (self::VALUE_NEGATABLE << 1) || $mode < 1) {
|
||||
throw new InvalidArgumentException(\sprintf('Option mode "%s" is not valid.', $mode));
|
||||
}
|
||||
|
||||
if (!\in_array($mode & (self::VALUE_NONE | self::VALUE_REQUIRED | self::VALUE_OPTIONAL), [self::VALUE_NONE, self::VALUE_REQUIRED, self::VALUE_OPTIONAL], true)) {
|
||||
trigger_deprecation('symfony/console', '8.1', 'Option "%s" mode should be either none, required or optional.', $name);
|
||||
}
|
||||
|
||||
$this->name = $name;
|
||||
$this->shortcut = $shortcut;
|
||||
$this->mode = $mode;
|
||||
|
||||
if ($suggestedValues && !$this->acceptValue()) {
|
||||
throw new LogicException('Cannot set suggested values if the option does not accept a value.');
|
||||
}
|
||||
if ($this->isArray() && !$this->acceptValue()) {
|
||||
throw new InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.');
|
||||
}
|
||||
if ($this->isNegatable() && $this->acceptValue()) {
|
||||
throw new InvalidArgumentException('Impossible to have an option mode VALUE_NEGATABLE if the option also accepts a value.');
|
||||
}
|
||||
|
||||
$this->setDefault($default);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the option shortcut.
|
||||
*/
|
||||
public function getShortcut(): ?string
|
||||
{
|
||||
return $this->shortcut;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the option name.
|
||||
*/
|
||||
public function getName(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option accepts a value.
|
||||
*
|
||||
* @return bool true if value mode is not self::VALUE_NONE, false otherwise
|
||||
*/
|
||||
public function acceptValue(): bool
|
||||
{
|
||||
return $this->isValueRequired() || $this->isValueOptional();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option requires a value.
|
||||
*
|
||||
* @return bool true if value mode is self::VALUE_REQUIRED, false otherwise
|
||||
*/
|
||||
public function isValueRequired(): bool
|
||||
{
|
||||
return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option takes an optional value.
|
||||
*
|
||||
* @return bool true if value mode is self::VALUE_OPTIONAL, false otherwise
|
||||
*/
|
||||
public function isValueOptional(): bool
|
||||
{
|
||||
return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option can take multiple values.
|
||||
*
|
||||
* @return bool true if mode is self::VALUE_IS_ARRAY, false otherwise
|
||||
*/
|
||||
public function isArray(): bool
|
||||
{
|
||||
return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option allows passing a negated variant.
|
||||
*
|
||||
* @return bool true if mode is self::VALUE_NEGATABLE, false otherwise
|
||||
*/
|
||||
public function isNegatable(): bool
|
||||
{
|
||||
return self::VALUE_NEGATABLE === (self::VALUE_NEGATABLE & $this->mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the default value.
|
||||
*/
|
||||
public function setDefault(mixed $default): void
|
||||
{
|
||||
if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && !$this->isNegatable() && null !== $default) {
|
||||
throw new LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.');
|
||||
}
|
||||
|
||||
if ($this->isNegatable() && null !== $default && !\is_bool($default)) {
|
||||
throw new LogicException('A default value for a negatable option must be a boolean or null.');
|
||||
}
|
||||
|
||||
if ($this->isArray()) {
|
||||
if (null === $default) {
|
||||
$default = [];
|
||||
} elseif (!\is_array($default)) {
|
||||
throw new LogicException('A default value for an array option must be an array.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->default = $this->acceptValue() || $this->isNegatable() ? $default : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the default value.
|
||||
*/
|
||||
public function getDefault(): mixed
|
||||
{
|
||||
return $this->default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the description text.
|
||||
*/
|
||||
public function getDescription(): string
|
||||
{
|
||||
return $this->description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the option has values for input completion.
|
||||
*/
|
||||
public function hasCompletion(): bool
|
||||
{
|
||||
return [] !== $this->suggestedValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Supplies suggestions when command resolves possible completion options for input.
|
||||
*
|
||||
* @see Command::complete()
|
||||
*/
|
||||
public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
|
||||
{
|
||||
$values = $this->suggestedValues;
|
||||
if ($values instanceof \Closure && !\is_array($values = $values($input))) {
|
||||
throw new LogicException(\sprintf('Closure for option "%s" must return an array. Got "%s".', $this->name, get_debug_type($values)));
|
||||
}
|
||||
if ($values) {
|
||||
$suggestions->suggestValues($values);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the given option equals this one.
|
||||
*/
|
||||
public function equals(self $option): bool
|
||||
{
|
||||
return $option->getName() === $this->getName()
|
||||
&& $option->getShortcut() === $this->getShortcut()
|
||||
&& $option->getDefault() === $this->getDefault()
|
||||
&& $option->isNegatable() === $this->isNegatable()
|
||||
&& $option->isArray() === $this->isArray()
|
||||
&& $option->isValueRequired() === $this->isValueRequired()
|
||||
&& $option->isValueOptional() === $this->isValueOptional()
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
/**
|
||||
* Provides access to the original input arguments and options
|
||||
* before they are merged with default values, and allows
|
||||
* unparsing options back to their CLI representation.
|
||||
*
|
||||
* @author Théo FIDRY <theo.fidry@gmail.com>
|
||||
*/
|
||||
interface RawInputInterface extends InputInterface
|
||||
{
|
||||
/**
|
||||
* Returns all the given arguments NOT merged with the default values.
|
||||
*
|
||||
* @return array<string|bool|int|float|array<string|bool|int|float|null>|null>
|
||||
*/
|
||||
public function getRawArguments(): array;
|
||||
|
||||
/**
|
||||
* Returns all the given options NOT merged with the default values.
|
||||
*
|
||||
* @return array<string|bool|int|float|array<string|bool|int|float|null>|null>
|
||||
*/
|
||||
public function getRawOptions(): array;
|
||||
|
||||
/**
|
||||
* Returns a stringified representation of the options passed to the command.
|
||||
*
|
||||
* The returned strings interpolate raw option values verbatim and are NOT
|
||||
* shell-escaped. They are intended to be passed as an array argv to
|
||||
* {@see \Symfony\Component\Process\Process}, which performs its own
|
||||
* escaping. Never concatenate the result into a shell string nor pass it
|
||||
* to {@see \Symfony\Component\Process\Process::fromShellCommandline()},
|
||||
* `shell_exec()`, `exec()`, `system()`, `passthru()`, or `proc_open()`
|
||||
* with a string command: untrusted option values would allow command
|
||||
* injection.
|
||||
*
|
||||
* @param string[]|null $optionNames Names of the options returned. If null, all options are returned.
|
||||
* Requested options that either do not exist or were not passed
|
||||
* (even if the option has a default value) will be ignored.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function unparse(?array $optionNames = null): array;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
/**
|
||||
* StreamableInputInterface is the interface implemented by all input classes
|
||||
* that have an input stream.
|
||||
*
|
||||
* @author Robin Chalas <robin.chalas@gmail.com>
|
||||
*/
|
||||
interface StreamableInputInterface extends InputInterface
|
||||
{
|
||||
/**
|
||||
* Sets the input stream to read from when interacting with the user.
|
||||
*
|
||||
* This is mainly useful for testing purpose.
|
||||
*
|
||||
* @param resource $stream The input stream
|
||||
*/
|
||||
public function setStream($stream): void;
|
||||
|
||||
/**
|
||||
* Returns the input stream.
|
||||
*
|
||||
* @return resource|null
|
||||
*/
|
||||
public function getStream();
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\Console\Input;
|
||||
|
||||
use Symfony\Component\Console\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* StringInput represents an input provided as a string.
|
||||
*
|
||||
* Usage:
|
||||
*
|
||||
* $input = new StringInput('foo --bar="foobar"');
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
*/
|
||||
class StringInput extends ArgvInput
|
||||
{
|
||||
public const REGEX_UNQUOTED_STRING = '([^\s\\\\]+?)';
|
||||
public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
|
||||
|
||||
/**
|
||||
* @param string $input A string representing the parameters from the CLI
|
||||
*/
|
||||
public function __construct(string $input)
|
||||
{
|
||||
parent::__construct([]);
|
||||
|
||||
$this->setTokens($this->tokenize($input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenizes a string.
|
||||
*
|
||||
* @return list<string>
|
||||
*
|
||||
* @throws InvalidArgumentException When unable to parse input (should never happen)
|
||||
*/
|
||||
private function tokenize(string $input): array
|
||||
{
|
||||
$tokens = [];
|
||||
$length = \strlen($input);
|
||||
$cursor = 0;
|
||||
$token = null;
|
||||
while ($cursor < $length) {
|
||||
if ('\\' === $input[$cursor]) {
|
||||
$token .= $input[++$cursor] ?? '';
|
||||
++$cursor;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/\s+/A', $input, $match, 0, $cursor)) {
|
||||
if (null !== $token) {
|
||||
$tokens[] = $token;
|
||||
$token = null;
|
||||
}
|
||||
} elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) {
|
||||
$token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1)));
|
||||
} elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
|
||||
$token .= stripcslashes(substr($match[0], 1, -1));
|
||||
} elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) {
|
||||
$token .= $match[1];
|
||||
} else {
|
||||
// should never happen
|
||||
throw new InvalidArgumentException(\sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10)));
|
||||
}
|
||||
|
||||
$cursor += \strlen($match[0]);
|
||||
}
|
||||
|
||||
if (null !== $token) {
|
||||
$tokens[] = $token;
|
||||
}
|
||||
|
||||
return $tokens;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user