updated packages

This commit is contained in:
2019-05-18 09:06:43 +00:00
parent 901d16349e
commit e9487fa58a
2025 changed files with 30366 additions and 49653 deletions

View File

@@ -62,7 +62,7 @@ use Symfony\Component\EventDispatcher\EventDispatcherInterface;
*/
class Application
{
private $commands = array();
private $commands = [];
private $wantHelps = false;
private $runningCommand;
private $name;
@@ -193,17 +193,24 @@ class Application
*/
public function doRun(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--version', '-V'), true)) {
if (true === $input->hasParameterOption(['--version', '-V'], true)) {
$output->writeln($this->getLongVersion());
return 0;
}
try {
// Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument.
$input->bind($this->getDefinition());
} catch (ExceptionInterface $e) {
// Errors must be ignored, full binding/validation happens later when the command is known.
}
$name = $this->getCommandName($input);
if (true === $input->hasParameterOption(array('--help', '-h'), true)) {
if (true === $input->hasParameterOption(['--help', '-h'], true)) {
if (!$name) {
$name = 'help';
$input = new ArrayInput(array('command_name' => $this->defaultCommand));
$input = new ArrayInput(['command_name' => $this->defaultCommand]);
} else {
$this->wantHelps = true;
}
@@ -214,9 +221,9 @@ class Application
$definition = $this->getDefinition();
$definition->setArguments(array_merge(
$definition->getArguments(),
array(
[
'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
)
]
));
}
@@ -535,7 +542,7 @@ class Application
*/
public function getNamespaces()
{
$namespaces = array();
$namespaces = [];
foreach ($this->all() as $command) {
$namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
@@ -602,7 +609,7 @@ class Application
{
$this->init();
$aliases = array();
$aliases = [];
$allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
$commands = preg_grep('{^'.$expr.'}', $allCommands);
@@ -695,7 +702,7 @@ class Application
return $commands;
}
$commands = array();
$commands = [];
foreach ($this->commands as $name => $command) {
if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
$commands[$name] = $command;
@@ -722,7 +729,7 @@ class Application
*/
public static function getAbbreviations($names)
{
$abbrevs = array();
$abbrevs = [];
foreach ($names as $name) {
for ($len = \strlen($name); $len > 0; --$len) {
$abbrev = substr($name, 0, $len);
@@ -768,18 +775,18 @@ class Application
}
$width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
$lines = array();
foreach ('' !== $message ? preg_split('/\r?\n/', $message) : array() as $line) {
$lines = [];
foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
// pre-format lines to get the right string length
$lineLength = Helper::strlen($line) + 4;
$lines[] = array($line, $lineLength);
$lines[] = [$line, $lineLength];
$len = max($lineLength, $len);
}
}
$messages = array();
$messages = [];
if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$messages[] = sprintf('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
}
@@ -801,12 +808,12 @@ class Application
// exception related properties
$trace = $e->getTrace();
array_unshift($trace, array(
array_unshift($trace, [
'function' => '',
'file' => $e->getFile() ?: 'n/a',
'line' => $e->getLine() ?: 'n/a',
'args' => array(),
));
'args' => [],
]);
for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
@@ -828,13 +835,13 @@ class Application
*/
protected function configureIO(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--ansi'), true)) {
if (true === $input->hasParameterOption(['--ansi'], true)) {
$output->setDecorated(true);
} elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) {
} elseif (true === $input->hasParameterOption(['--no-ansi'], true)) {
$output->setDecorated(false);
}
if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) {
$input->setInteractive(false);
} elseif (\function_exists('posix_isatty')) {
$inputStream = null;
@@ -856,7 +863,7 @@ class Application
default: $shellVerbosity = 0; break;
}
if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
if (true === $input->hasParameterOption(['--quiet', '-q'], true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
$shellVerbosity = -1;
} else {
@@ -957,7 +964,7 @@ class Application
*/
protected function getDefaultInputDefinition()
{
return new InputDefinition(array(
return new InputDefinition([
new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
@@ -967,7 +974,7 @@ class Application
new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
));
]);
}
/**
@@ -977,7 +984,7 @@ class Application
*/
protected function getDefaultCommands()
{
return array(new HelpCommand(), new ListCommand());
return [new HelpCommand(), new ListCommand()];
}
/**
@@ -987,12 +994,12 @@ class Application
*/
protected function getDefaultHelperSet()
{
return new HelperSet(array(
return new HelperSet([
new FormatterHelper(),
new DebugFormatterHelper(),
new ProcessHelper(),
new QuestionHelper(),
));
]);
}
/**
@@ -1037,9 +1044,9 @@ class Application
private function findAlternatives($name, $collection)
{
$threshold = 1e3;
$alternatives = array();
$alternatives = [];
$collectionParts = array();
$collectionParts = [];
foreach ($collection as $item) {
$collectionParts[$item] = explode(':', $item);
}
@@ -1116,7 +1123,7 @@ class Application
}
$utf8String = mb_convert_encoding($string, 'utf8', $encoding);
$lines = array();
$lines = [];
$line = '';
foreach (preg_split('//u', $utf8String) as $char) {
// test if $char could be appended to current line
@@ -1147,7 +1154,7 @@ class Application
{
// -1 as third argument is needed to skip the command short name when exploding
$parts = explode(':', $name, -1);
$namespaces = array();
$namespaces = [];
foreach ($parts as $part) {
if (\count($namespaces)) {

View File

@@ -4,7 +4,7 @@ CHANGELOG
4.2.0
-----
* allowed passing commands as `array($process, 'ENV_VAR' => 'value')` to
* allowed passing commands as `[$process, 'ENV_VAR' => 'value']` to
`ProcessHelper::run()` to pass environment variables
* deprecated passing a command as a string to `ProcessHelper::run()`,
pass it the command as an array of its arguments instead

View File

@@ -37,7 +37,7 @@ class Command
private $application;
private $name;
private $processTitle;
private $aliases = array();
private $aliases = [];
private $definition;
private $hidden = false;
private $help;
@@ -46,8 +46,8 @@ class Command
private $applicationDefinitionMerged = false;
private $applicationDefinitionMergedWithArgs = false;
private $code;
private $synopsis = array();
private $usages = array();
private $synopsis = [];
private $usages = [];
private $helperSet;
/**
@@ -380,7 +380,7 @@ class Command
* Adds an option.
*
* @param string $name The option name
* @param string|array $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param int|null $mode The option mode: One of the InputOption::VALUE_* constants
* @param string $description A description text
* @param string|string[]|int|bool|null $default The default value (must be null for InputOption::VALUE_NONE)
@@ -527,14 +527,14 @@ class Command
$name = $this->name;
$isSingleCommand = $this->application && $this->application->isSingleCommand();
$placeholders = array(
$placeholders = [
'%command.name%',
'%command.full_name%',
);
$replacements = array(
];
$replacements = [
$name,
$isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name,
);
];
return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
}

View File

@@ -35,11 +35,11 @@ class HelpCommand extends Command
$this
->setName('help')
->setDefinition(array(
->setDefinition([
new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
))
])
->setDescription('Displays help for a command')
->setHelp(<<<'EOF'
The <info>%command.name%</info> command displays help for a given command:
@@ -71,10 +71,10 @@ EOF
}
$helper = new DescriptorHelper();
$helper->describe($output, $this->command, array(
$helper->describe($output, $this->command, [
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
));
]);
$this->command = null;
}

View File

@@ -69,11 +69,11 @@ EOF
protected function execute(InputInterface $input, OutputInterface $output)
{
$helper = new DescriptorHelper();
$helper->describe($output, $this->getApplication(), array(
$helper->describe($output, $this->getApplication(), [
'format' => $input->getOption('format'),
'raw_text' => $input->getOption('raw'),
'namespace' => $input->getArgument('namespace'),
));
]);
}
/**
@@ -81,10 +81,10 @@ EOF
*/
private function createDefinition()
{
return new InputDefinition(array(
return new InputDefinition([
new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'),
));
]);
}
}

View File

@@ -38,9 +38,9 @@ class AddConsoleCommandPass implements CompilerPassInterface
public function process(ContainerBuilder $container)
{
$commandServices = $container->findTaggedServiceIds($this->commandTag, true);
$lazyCommandMap = array();
$lazyCommandRefs = array();
$serviceIds = array();
$lazyCommandMap = [];
$lazyCommandRefs = [];
$serviceIds = [];
foreach ($commandServices as $id => $tags) {
$definition = $container->getDefinition($id);
@@ -72,7 +72,7 @@ class AddConsoleCommandPass implements CompilerPassInterface
unset($tags[0]);
$lazyCommandMap[$commandName] = $id;
$lazyCommandRefs[$id] = new TypedReference($id, $class);
$aliases = array();
$aliases = [];
foreach ($tags as $tag) {
if (isset($tag['command'])) {
@@ -81,17 +81,17 @@ class AddConsoleCommandPass implements CompilerPassInterface
}
}
$definition->addMethodCall('setName', array($commandName));
$definition->addMethodCall('setName', [$commandName]);
if ($aliases) {
$definition->addMethodCall('setAliases', array($aliases));
$definition->addMethodCall('setAliases', [$aliases]);
}
}
$container
->register($this->commandLoaderServiceId, ContainerCommandLoader::class)
->setPublic(true)
->setArguments(array(ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap));
->setArguments([ServiceLocatorTagPass::register($container, $lazyCommandRefs), $lazyCommandMap]);
$container->setParameter('console.command.ids', $serviceIds);
}

View File

@@ -92,12 +92,12 @@ class ApplicationDescription
private function inspectApplication()
{
$this->commands = array();
$this->namespaces = array();
$this->commands = [];
$this->namespaces = [];
$all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
foreach ($this->sortCommands($all) as $namespace => $commands) {
$names = array();
$names = [];
/** @var Command $command */
foreach ($commands as $name => $command) {
@@ -114,14 +114,14 @@ class ApplicationDescription
$names[] = $name;
}
$this->namespaces[$namespace] = array('id' => $namespace, 'commands' => $names);
$this->namespaces[$namespace] = ['id' => $namespace, 'commands' => $names];
}
}
private function sortCommands(array $commands): array
{
$namespacedCommands = array();
$globalCommands = array();
$namespacedCommands = [];
$globalCommands = [];
foreach ($commands as $name => $command) {
$key = $this->application->extractNamespace($name, 1);
if (!$key) {

View File

@@ -34,7 +34,7 @@ abstract class Descriptor implements DescriptorInterface
/**
* {@inheritdoc}
*/
public function describe(OutputInterface $output, $object, array $options = array())
public function describe(OutputInterface $output, $object, array $options = [])
{
$this->output = $output;
@@ -75,33 +75,33 @@ abstract class Descriptor implements DescriptorInterface
*
* @return string|mixed
*/
abstract protected function describeInputArgument(InputArgument $argument, array $options = array());
abstract protected function describeInputArgument(InputArgument $argument, array $options = []);
/**
* Describes an InputOption instance.
*
* @return string|mixed
*/
abstract protected function describeInputOption(InputOption $option, array $options = array());
abstract protected function describeInputOption(InputOption $option, array $options = []);
/**
* Describes an InputDefinition instance.
*
* @return string|mixed
*/
abstract protected function describeInputDefinition(InputDefinition $definition, array $options = array());
abstract protected function describeInputDefinition(InputDefinition $definition, array $options = []);
/**
* Describes a Command instance.
*
* @return string|mixed
*/
abstract protected function describeCommand(Command $command, array $options = array());
abstract protected function describeCommand(Command $command, array $options = []);
/**
* Describes an Application instance.
*
* @return string|mixed
*/
abstract protected function describeApplication(Application $application, array $options = array());
abstract protected function describeApplication(Application $application, array $options = []);
}

View File

@@ -27,5 +27,5 @@ interface DescriptorInterface
* @param object $object
* @param array $options
*/
public function describe(OutputInterface $output, $object, array $options = array());
public function describe(OutputInterface $output, $object, array $options = []);
}

View File

@@ -29,7 +29,7 @@ class JsonDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputArgument(InputArgument $argument, array $options = array())
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->writeData($this->getInputArgumentData($argument), $options);
}
@@ -37,7 +37,7 @@ class JsonDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputOption(InputOption $option, array $options = array())
protected function describeInputOption(InputOption $option, array $options = [])
{
$this->writeData($this->getInputOptionData($option), $options);
}
@@ -45,7 +45,7 @@ class JsonDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$this->writeData($this->getInputDefinitionData($definition), $options);
}
@@ -53,7 +53,7 @@ class JsonDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeCommand(Command $command, array $options = array())
protected function describeCommand(Command $command, array $options = [])
{
$this->writeData($this->getCommandData($command), $options);
}
@@ -61,17 +61,17 @@ class JsonDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeApplication(Application $application, array $options = array())
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace, true);
$commands = array();
$commands = [];
foreach ($description->getCommands() as $command) {
$commands[] = $this->getCommandData($command);
}
$data = array();
$data = [];
if ('UNKNOWN' !== $application->getName()) {
$data['application']['name'] = $application->getName();
if ('UNKNOWN' !== $application->getVersion()) {
@@ -105,13 +105,13 @@ class JsonDescriptor extends Descriptor
*/
private function getInputArgumentData(InputArgument $argument)
{
return array(
return [
'name' => $argument->getName(),
'is_required' => $argument->isRequired(),
'is_array' => $argument->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $argument->getDescription()),
'default' => INF === $argument->getDefault() ? 'INF' : $argument->getDefault(),
);
];
}
/**
@@ -119,7 +119,7 @@ class JsonDescriptor extends Descriptor
*/
private function getInputOptionData(InputOption $option)
{
return array(
return [
'name' => '--'.$option->getName(),
'shortcut' => $option->getShortcut() ? '-'.str_replace('|', '|-', $option->getShortcut()) : '',
'accept_value' => $option->acceptValue(),
@@ -127,7 +127,7 @@ class JsonDescriptor extends Descriptor
'is_multiple' => $option->isArray(),
'description' => preg_replace('/\s*[\r\n]\s*/', ' ', $option->getDescription()),
'default' => INF === $option->getDefault() ? 'INF' : $option->getDefault(),
);
];
}
/**
@@ -135,17 +135,17 @@ class JsonDescriptor extends Descriptor
*/
private function getInputDefinitionData(InputDefinition $definition)
{
$inputArguments = array();
$inputArguments = [];
foreach ($definition->getArguments() as $name => $argument) {
$inputArguments[$name] = $this->getInputArgumentData($argument);
}
$inputOptions = array();
$inputOptions = [];
foreach ($definition->getOptions() as $name => $option) {
$inputOptions[$name] = $this->getInputOptionData($option);
}
return array('arguments' => $inputArguments, 'options' => $inputOptions);
return ['arguments' => $inputArguments, 'options' => $inputOptions];
}
/**
@@ -156,13 +156,13 @@ class JsonDescriptor extends Descriptor
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
return array(
return [
'name' => $command->getName(),
'usage' => array_merge(array($command->getSynopsis()), $command->getUsages(), $command->getAliases()),
'usage' => array_merge([$command->getSynopsis()], $command->getUsages(), $command->getAliases()),
'description' => $command->getDescription(),
'help' => $command->getProcessedHelp(),
'definition' => $this->getInputDefinitionData($command->getNativeDefinition()),
'hidden' => $command->isHidden(),
);
];
}
}

View File

@@ -31,7 +31,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
public function describe(OutputInterface $output, $object, array $options = array())
public function describe(OutputInterface $output, $object, array $options = [])
{
$decorated = $output->isDecorated();
$output->setDecorated(false);
@@ -52,7 +52,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputArgument(InputArgument $argument, array $options = array())
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->write(
'#### `'.($argument->getName() ?: '<none>')."`\n\n"
@@ -66,7 +66,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputOption(InputOption $option, array $options = array())
protected function describeInputOption(InputOption $option, array $options = [])
{
$name = '--'.$option->getName();
if ($option->getShortcut()) {
@@ -86,7 +86,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
if ($showArguments = \count($definition->getArguments()) > 0) {
$this->write('### Arguments');
@@ -112,7 +112,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeCommand(Command $command, array $options = array())
protected function describeCommand(Command $command, array $options = [])
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);
@@ -122,7 +122,7 @@ class MarkdownDescriptor extends Descriptor
.str_repeat('-', Helper::strlen($command->getName()) + 2)."\n\n"
.($command->getDescription() ? $command->getDescription()."\n\n" : '')
.'### Usage'."\n\n"
.array_reduce(array_merge(array($command->getSynopsis()), $command->getAliases(), $command->getUsages()), function ($carry, $usage) {
.array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), function ($carry, $usage) {
return $carry.'* `'.$usage.'`'."\n";
})
);
@@ -141,7 +141,7 @@ class MarkdownDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeApplication(Application $application, array $options = array())
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);

View File

@@ -31,7 +31,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputArgument(InputArgument $argument, array $options = array())
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
@@ -54,7 +54,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputOption(InputOption $option, array $options = array())
protected function describeInputOption(InputOption $option, array $options = [])
{
if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
@@ -71,7 +71,7 @@ class TextDescriptor extends Descriptor
}
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions(array($option));
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions([$option]);
$synopsis = sprintf('%s%s',
$option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ',
sprintf('--%s%s', $option->getName(), $value)
@@ -92,7 +92,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
foreach ($definition->getArguments() as $argument) {
@@ -103,7 +103,7 @@ class TextDescriptor extends Descriptor
$this->writeText('<comment>Arguments:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getArguments() as $argument) {
$this->describeInputArgument($argument, array_merge($options, array('total_width' => $totalWidth)));
$this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
$this->writeText("\n");
}
}
@@ -113,7 +113,7 @@ class TextDescriptor extends Descriptor
}
if ($definition->getOptions()) {
$laterOptions = array();
$laterOptions = [];
$this->writeText('<comment>Options:</comment>', $options);
foreach ($definition->getOptions() as $option) {
@@ -122,11 +122,11 @@ class TextDescriptor extends Descriptor
continue;
}
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, array('total_width' => $totalWidth)));
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
foreach ($laterOptions as $option) {
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, array('total_width' => $totalWidth)));
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
}
}
@@ -134,7 +134,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeCommand(Command $command, array $options = array())
protected function describeCommand(Command $command, array $options = [])
{
$command->getSynopsis(true);
$command->getSynopsis(false);
@@ -148,7 +148,7 @@ class TextDescriptor extends Descriptor
}
$this->writeText('<comment>Usage:</comment>', $options);
foreach (array_merge(array($command->getSynopsis(true)), $command->getAliases(), $command->getUsages()) as $usage) {
foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
$this->writeText("\n");
$this->writeText(' '.OutputFormatter::escape($usage), $options);
}
@@ -174,7 +174,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeApplication(Application $application, array $options = array())
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
@@ -250,7 +250,7 @@ class TextDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
private function writeText($content, array $options = array())
private function writeText($content, array $options = [])
{
$this->write(
isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
@@ -302,7 +302,7 @@ class TextDescriptor extends Descriptor
*/
private function getColumnWidth(array $commands): int
{
$widths = array();
$widths = [];
foreach ($commands as $command) {
if ($command instanceof Command) {

View File

@@ -64,7 +64,7 @@ class XmlDescriptor extends Descriptor
$commandXML->appendChild($usagesXML = $dom->createElement('usages'));
foreach (array_merge(array($command->getSynopsis()), $command->getAliases(), $command->getUsages()) as $usage) {
foreach (array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()) as $usage) {
$usagesXML->appendChild($dom->createElement('usage', $usage));
}
@@ -130,7 +130,7 @@ class XmlDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputArgument(InputArgument $argument, array $options = array())
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
$this->writeDocument($this->getInputArgumentDocument($argument));
}
@@ -138,7 +138,7 @@ class XmlDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputOption(InputOption $option, array $options = array())
protected function describeInputOption(InputOption $option, array $options = [])
{
$this->writeDocument($this->getInputOptionDocument($option));
}
@@ -146,7 +146,7 @@ class XmlDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeInputDefinition(InputDefinition $definition, array $options = array())
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$this->writeDocument($this->getInputDefinitionDocument($definition));
}
@@ -154,7 +154,7 @@ class XmlDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeCommand(Command $command, array $options = array())
protected function describeCommand(Command $command, array $options = [])
{
$this->writeDocument($this->getCommandDocument($command));
}
@@ -162,7 +162,7 @@ class XmlDescriptor extends Descriptor
/**
* {@inheritdoc}
*/
protected function describeApplication(Application $application, array $options = array())
protected function describeApplication(Application $application, array $options = [])
{
$this->writeDocument($this->getApplicationDocument($application, isset($options['namespace']) ? $options['namespace'] : null));
}
@@ -200,7 +200,7 @@ class XmlDescriptor extends Descriptor
$descriptionXML->appendChild($dom->createTextNode($argument->getDescription()));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
$defaults = \is_array($argument->getDefault()) ? $argument->getDefault() : (\is_bool($argument->getDefault()) ? array(var_export($argument->getDefault(), true)) : ($argument->getDefault() ? array($argument->getDefault()) : array()));
$defaults = \is_array($argument->getDefault()) ? $argument->getDefault() : (\is_bool($argument->getDefault()) ? [var_export($argument->getDefault(), true)] : ($argument->getDefault() ? [$argument->getDefault()] : []));
foreach ($defaults as $default) {
$defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
$defaultXML->appendChild($dom->createTextNode($default));
@@ -229,7 +229,7 @@ class XmlDescriptor extends Descriptor
$descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
if ($option->acceptValue()) {
$defaults = \is_array($option->getDefault()) ? $option->getDefault() : (\is_bool($option->getDefault()) ? array(var_export($option->getDefault(), true)) : ($option->getDefault() ? array($option->getDefault()) : array()));
$defaults = \is_array($option->getDefault()) ? $option->getDefault() : (\is_bool($option->getDefault()) ? [var_export($option->getDefault(), true)] : ($option->getDefault() ? [$option->getDefault()] : []));
$objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
if (!empty($defaults)) {

View File

@@ -40,10 +40,10 @@ class ErrorListener implements EventSubscriberInterface
$error = $event->getError();
if (!$inputString = $this->getInputString($event)) {
return $this->logger->error('An error occurred while using the console. Message: "{message}"', array('exception' => $error, 'message' => $error->getMessage()));
return $this->logger->error('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]);
}
$this->logger->error('Error thrown while running command "{command}". Message: "{message}"', array('exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()));
$this->logger->error('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]);
}
public function onConsoleTerminate(ConsoleTerminateEvent $event)
@@ -59,18 +59,18 @@ class ErrorListener implements EventSubscriberInterface
}
if (!$inputString = $this->getInputString($event)) {
return $this->logger->debug('The console exited with code "{code}"', array('code' => $exitCode));
return $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);
}
$this->logger->debug('Command "{command}" exited with code "{code}"', array('command' => $inputString, 'code' => $exitCode));
$this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]);
}
public static function getSubscribedEvents()
{
return array(
ConsoleEvents::ERROR => array('onConsoleError', -128),
ConsoleEvents::TERMINATE => array('onConsoleTerminate', -128),
);
return [
ConsoleEvents::ERROR => ['onConsoleError', -128],
ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128],
];
}
private static function getInputString(ConsoleEvent $event)
@@ -80,7 +80,7 @@ class ErrorListener implements EventSubscriberInterface
if (method_exists($input, '__toString')) {
if ($commandName) {
return str_replace(array("'$commandName'", "\"$commandName\""), $commandName, (string) $input);
return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input);
}
return (string) $input;

View File

@@ -26,7 +26,7 @@ class CommandNotFoundException extends \InvalidArgumentException implements Exce
* @param int $code Exception code
* @param \Exception $previous Previous exception used for the exception chaining
*/
public function __construct(string $message, array $alternatives = array(), int $code = 0, \Exception $previous = null)
public function __construct(string $message, array $alternatives = [], int $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);

View File

@@ -22,7 +22,7 @@ use Symfony\Component\Console\Exception\InvalidArgumentException;
class OutputFormatter implements WrappableOutputFormatterInterface
{
private $decorated;
private $styles = array();
private $styles = [];
private $styleStack;
/**
@@ -66,7 +66,7 @@ class OutputFormatter implements WrappableOutputFormatterInterface
* @param bool $decorated Whether this formatter should actually decorate strings
* @param OutputFormatterStyleInterface[] $styles Array of "name => FormatterStyle" instances
*/
public function __construct(bool $decorated = false, array $styles = array())
public function __construct(bool $decorated = false, array $styles = [])
{
$this->decorated = $decorated;
@@ -178,7 +178,7 @@ class OutputFormatter implements WrappableOutputFormatterInterface
$output .= $this->applyCurrentStyle(substr($message, $offset), $output, $width, $currentLineLength);
if (false !== strpos($output, "\0")) {
return strtr($output, array("\0" => '\\', '\\<' => '<'));
return strtr($output, ["\0" => '\\', '\\<' => '<']);
}
return str_replace('\\<', '<', $output);
@@ -263,8 +263,12 @@ class OutputFormatter implements WrappableOutputFormatterInterface
}
$lines = explode("\n", $text);
if ($width === $currentLineLength = \strlen(end($lines))) {
$currentLineLength = 0;
foreach ($lines as $line) {
$currentLineLength += \strlen($line);
if ($width <= $currentLineLength) {
$currentLineLength = 0;
}
}
if ($this->isDecorated()) {

View File

@@ -20,39 +20,39 @@ use Symfony\Component\Console\Exception\InvalidArgumentException;
*/
class OutputFormatterStyle implements OutputFormatterStyleInterface
{
private static $availableForegroundColors = array(
'black' => array('set' => 30, 'unset' => 39),
'red' => array('set' => 31, 'unset' => 39),
'green' => array('set' => 32, 'unset' => 39),
'yellow' => array('set' => 33, 'unset' => 39),
'blue' => array('set' => 34, 'unset' => 39),
'magenta' => array('set' => 35, 'unset' => 39),
'cyan' => array('set' => 36, 'unset' => 39),
'white' => array('set' => 37, 'unset' => 39),
'default' => array('set' => 39, 'unset' => 39),
);
private static $availableBackgroundColors = array(
'black' => array('set' => 40, 'unset' => 49),
'red' => array('set' => 41, 'unset' => 49),
'green' => array('set' => 42, 'unset' => 49),
'yellow' => array('set' => 43, 'unset' => 49),
'blue' => array('set' => 44, 'unset' => 49),
'magenta' => array('set' => 45, 'unset' => 49),
'cyan' => array('set' => 46, 'unset' => 49),
'white' => array('set' => 47, 'unset' => 49),
'default' => array('set' => 49, 'unset' => 49),
);
private static $availableOptions = array(
'bold' => array('set' => 1, 'unset' => 22),
'underscore' => array('set' => 4, 'unset' => 24),
'blink' => array('set' => 5, 'unset' => 25),
'reverse' => array('set' => 7, 'unset' => 27),
'conceal' => array('set' => 8, 'unset' => 28),
);
private static $availableForegroundColors = [
'black' => ['set' => 30, 'unset' => 39],
'red' => ['set' => 31, 'unset' => 39],
'green' => ['set' => 32, 'unset' => 39],
'yellow' => ['set' => 33, 'unset' => 39],
'blue' => ['set' => 34, 'unset' => 39],
'magenta' => ['set' => 35, 'unset' => 39],
'cyan' => ['set' => 36, 'unset' => 39],
'white' => ['set' => 37, 'unset' => 39],
'default' => ['set' => 39, 'unset' => 39],
];
private static $availableBackgroundColors = [
'black' => ['set' => 40, 'unset' => 49],
'red' => ['set' => 41, 'unset' => 49],
'green' => ['set' => 42, 'unset' => 49],
'yellow' => ['set' => 43, 'unset' => 49],
'blue' => ['set' => 44, 'unset' => 49],
'magenta' => ['set' => 45, 'unset' => 49],
'cyan' => ['set' => 46, 'unset' => 49],
'white' => ['set' => 47, 'unset' => 49],
'default' => ['set' => 49, 'unset' => 49],
];
private static $availableOptions = [
'bold' => ['set' => 1, 'unset' => 22],
'underscore' => ['set' => 4, 'unset' => 24],
'blink' => ['set' => 5, 'unset' => 25],
'reverse' => ['set' => 7, 'unset' => 27],
'conceal' => ['set' => 8, 'unset' => 28],
];
private $foreground;
private $background;
private $options = array();
private $options = [];
/**
* Initializes output formatter style.
@@ -61,7 +61,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
* @param string|null $background The style background color name
* @param array $options The style options
*/
public function __construct(string $foreground = null, string $background = null, array $options = array())
public function __construct(string $foreground = null, string $background = null, array $options = [])
{
if (null !== $foreground) {
$this->setForeground($foreground);
@@ -160,7 +160,7 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
*/
public function setOptions(array $options)
{
$this->options = array();
$this->options = [];
foreach ($options as $option) {
$this->setOption($option);
@@ -176,8 +176,8 @@ class OutputFormatterStyle implements OutputFormatterStyleInterface
*/
public function apply($text)
{
$setCodes = array();
$unsetCodes = array();
$setCodes = [];
$unsetCodes = [];
if (null !== $this->foreground) {
$setCodes[] = $this->foreground['set'];

View File

@@ -37,7 +37,7 @@ class OutputFormatterStyleStack implements ResetInterface
*/
public function reset()
{
$this->styles = array();
$this->styles = [];
}
/**

View File

@@ -20,8 +20,8 @@ namespace Symfony\Component\Console\Helper;
*/
class DebugFormatterHelper extends Helper
{
private $colors = array('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default');
private $started = array();
private $colors = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'default'];
private $started = [];
private $count = -1;
/**
@@ -35,7 +35,7 @@ class DebugFormatterHelper extends Helper
*/
public function start($id, $message, $prefix = 'RUN')
{
$this->started[$id] = array('border' => ++$this->count % \count($this->colors));
$this->started[$id] = ['border' => ++$this->count % \count($this->colors)];
return sprintf("%s<bg=blue;fg=white> %s </> <fg=blue>%s</>\n", $this->getBorder($id), $prefix, $message);
}

View File

@@ -29,7 +29,7 @@ class DescriptorHelper extends Helper
/**
* @var DescriptorInterface[]
*/
private $descriptors = array();
private $descriptors = [];
public function __construct()
{
@@ -54,12 +54,12 @@ class DescriptorHelper extends Helper
*
* @throws InvalidArgumentException when the given format is not supported
*/
public function describe(OutputInterface $output, $object, array $options = array())
public function describe(OutputInterface $output, $object, array $options = [])
{
$options = array_merge(array(
$options = array_merge([
'raw_text' => false,
'format' => 'txt',
), $options);
], $options);
if (!isset($this->descriptors[$options['format']])) {
throw new InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));

View File

@@ -46,18 +46,18 @@ class FormatterHelper extends Helper
public function formatBlock($messages, $style, $large = false)
{
if (!\is_array($messages)) {
$messages = array($messages);
$messages = [$messages];
}
$len = 0;
$lines = array();
$lines = [];
foreach ($messages as $message) {
$message = OutputFormatter::escape($message);
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max($this->strlen($message) + ($large ? 4 : 2), $len);
}
$messages = $large ? array(str_repeat(' ', $len)) : array();
$messages = $large ? [str_repeat(' ', $len)] : [];
for ($i = 0; isset($lines[$i]); ++$i) {
$messages[] = $lines[$i].str_repeat(' ', $len - $this->strlen($lines[$i]));
}

View File

@@ -74,17 +74,17 @@ abstract class Helper implements HelperInterface
public static function formatTime($secs)
{
static $timeFormats = array(
array(0, '< 1 sec'),
array(1, '1 sec'),
array(2, 'secs', 1),
array(60, '1 min'),
array(120, 'mins', 60),
array(3600, '1 hr'),
array(7200, 'hrs', 3600),
array(86400, '1 day'),
array(172800, 'days', 86400),
);
static $timeFormats = [
[0, '< 1 sec'],
[1, '1 sec'],
[2, 'secs', 1],
[60, '1 min'],
[120, 'mins', 60],
[3600, '1 hr'],
[7200, 'hrs', 3600],
[86400, '1 day'],
[172800, 'days', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {

View File

@@ -24,13 +24,13 @@ class HelperSet implements \IteratorAggregate
/**
* @var Helper[]
*/
private $helpers = array();
private $helpers = [];
private $command;
/**
* @param Helper[] $helpers An array of helper
*/
public function __construct(array $helpers = array())
public function __construct(array $helpers = [])
{
foreach ($helpers as $alias => $helper) {
$this->set($helper, \is_int($alias) ? null : $alias);

View File

@@ -46,17 +46,17 @@ class ProcessHelper extends Helper
$formatter = $this->getHelperSet()->get('debug_formatter');
if ($cmd instanceof Process) {
$cmd = array($cmd);
$cmd = [$cmd];
}
if (!\is_array($cmd)) {
@trigger_error(sprintf('Passing a command as a string to "%s()" is deprecated since Symfony 4.2, pass it the command as an array of arguments instead.', __METHOD__), E_USER_DEPRECATED);
$cmd = array(\method_exists(Process::class, 'fromShellCommandline') ? Process::fromShellCommandline($cmd) : new Process($cmd));
$cmd = [\method_exists(Process::class, 'fromShellCommandline') ? Process::fromShellCommandline($cmd) : new Process($cmd)];
}
if (\is_string($cmd[0] ?? null)) {
$process = new Process($cmd);
$cmd = array();
$cmd = [];
} elseif (($cmd[0] ?? null) instanceof Process) {
$process = $cmd[0];
unset($cmd[0]);

View File

@@ -39,7 +39,7 @@ final class ProgressBar
private $stepWidth;
private $percent = 0.0;
private $formatLineCount;
private $messages = array();
private $messages = [];
private $overwrite = true;
private $terminal;
private $firstRun = true;
@@ -381,20 +381,17 @@ final class ProgressBar
$lines = floor(Helper::strlen($message) / $this->terminal->getWidth()) + $this->formatLineCount + 1;
$this->output->clear($lines);
} else {
// Move the cursor to the beginning of the line
$this->output->write("\x0D");
// Erase the line
$this->output->write("\x1B[2K");
// Erase previous lines
if ($this->formatLineCount > 0) {
$this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount));
$message = str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount).$message;
}
// Move the cursor to the beginning of the line and erase the line
$message = "\x0D\x1B[2K$message";
}
}
} elseif ($this->step > 0) {
$this->output->writeln('');
$message = PHP_EOL.$message;
}
$this->firstRun = false;
@@ -419,8 +416,8 @@ final class ProgressBar
private static function initPlaceholderFormatters(): array
{
return array(
'bar' => function (ProgressBar $bar, OutputInterface $output) {
return [
'bar' => function (self $bar, OutputInterface $output) {
$completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
$display = str_repeat($bar->getBarCharacter(), $completeBars);
if ($completeBars < $bar->getBarWidth()) {
@@ -430,10 +427,10 @@ final class ProgressBar
return $display;
},
'elapsed' => function (ProgressBar $bar) {
'elapsed' => function (self $bar) {
return Helper::formatTime(time() - $bar->getStartTime());
},
'remaining' => function (ProgressBar $bar) {
'remaining' => function (self $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
}
@@ -446,7 +443,7 @@ final class ProgressBar
return Helper::formatTime($remaining);
},
'estimated' => function (ProgressBar $bar) {
'estimated' => function (self $bar) {
if (!$bar->getMaxSteps()) {
throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
}
@@ -459,24 +456,24 @@ final class ProgressBar
return Helper::formatTime($estimated);
},
'memory' => function (ProgressBar $bar) {
'memory' => function (self $bar) {
return Helper::formatMemory(memory_get_usage(true));
},
'current' => function (ProgressBar $bar) {
'current' => function (self $bar) {
return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
},
'max' => function (ProgressBar $bar) {
'max' => function (self $bar) {
return $bar->getMaxSteps();
},
'percent' => function (ProgressBar $bar) {
'percent' => function (self $bar) {
return floor($bar->getProgressPercent() * 100);
},
);
];
}
private static function initFormats(): array
{
return array(
return [
'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
'normal_nomax' => ' %current% [%bar%]',
@@ -488,7 +485,7 @@ final class ProgressBar
'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
);
];
}
private function buildLine(): string

View File

@@ -48,7 +48,7 @@ class ProgressIndicator
}
if (null === $indicatorValues) {
$indicatorValues = array('-', '\\', '|', '/');
$indicatorValues = ['-', '\\', '|', '/'];
}
$indicatorValues = array_values($indicatorValues);
@@ -237,25 +237,25 @@ class ProgressIndicator
private static function initPlaceholderFormatters()
{
return array(
'indicator' => function (ProgressIndicator $indicator) {
return [
'indicator' => function (self $indicator) {
return $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)];
},
'message' => function (ProgressIndicator $indicator) {
'message' => function (self $indicator) {
return $indicator->message;
},
'elapsed' => function (ProgressIndicator $indicator) {
'elapsed' => function (self $indicator) {
return Helper::formatTime(time() - $indicator->startTime);
},
'memory' => function () {
return Helper::formatMemory(memory_get_usage(true));
},
);
];
}
private static function initFormats()
{
return array(
return [
'normal' => ' %indicator% %message%',
'normal_no_ansi' => ' %message%',
@@ -264,6 +264,6 @@ class ProgressIndicator
'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
);
];
}
}

View File

@@ -49,7 +49,13 @@ class QuestionHelper extends Helper
if (!$input->isInteractive()) {
$default = $question->getDefault();
if (null !== $default && $question instanceof ChoiceQuestion) {
if (null === $default) {
return $default;
}
if ($validator = $question->getValidator()) {
return \call_user_func($question->getValidator(), $default);
} elseif ($question instanceof ChoiceQuestion) {
$choices = $question->getChoices();
if (!$question->isMultiselect()) {
@@ -126,7 +132,7 @@ class QuestionHelper extends Helper
if (false === $ret) {
$ret = fgets($inputStream, 4096);
if (false === $ret) {
throw new RuntimeException('Aborted');
throw new RuntimeException('Aborted.');
}
$ret = trim($ret);
}
@@ -155,7 +161,7 @@ class QuestionHelper extends Helper
$message = $question->getQuestion();
if ($question instanceof ChoiceQuestion) {
$maxWidth = max(array_map(array($this, 'strlen'), array_keys($question->getChoices())));
$maxWidth = max(array_map([$this, 'strlen'], array_keys($question->getChoices())));
$messages = (array) $question->getQuestion();
foreach ($question->getChoices() as $key => $value) {
@@ -213,8 +219,11 @@ class QuestionHelper extends Helper
while (!feof($inputStream)) {
$c = fread($inputStream, 1);
// Backspace Character
if ("\177" === $c) {
// as opposed to fgets(), fread() returns an empty string when the stream content is empty, not false.
if (false === $c || ('' === $ret && '' === $c && null === $question->getDefault())) {
shell_exec(sprintf('stty %s', $sttyMode));
throw new RuntimeException('Aborted.');
} elseif ("\177" === $c) { // Backspace Character
if (0 === $numMatches && 0 !== $i) {
--$i;
// Move cursor backwards
@@ -267,6 +276,10 @@ class QuestionHelper extends Helper
continue;
} else {
if ("\x80" <= $c) {
$c .= fread($inputStream, ["\xC0" => 1, "\xD0" => 1, "\xE0" => 2, "\xF0" => 3][$c & "\xF0"]);
}
$output->write($c);
$ret .= $c;
++$i;
@@ -339,7 +352,7 @@ class QuestionHelper extends Helper
shell_exec(sprintf('stty %s', $sttyMode));
if (false === $value) {
throw new RuntimeException('Aborted');
throw new RuntimeException('Aborted.');
}
$value = trim($value);
@@ -407,7 +420,7 @@ class QuestionHelper extends Helper
if (file_exists('/usr/bin/env')) {
// handle other OSs with bash/zsh/ksh/csh if available to hide the answer
$test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
foreach (['bash', 'zsh', 'ksh', 'csh'] as $sh) {
if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
self::$shell = $sh;
break;

View File

@@ -13,6 +13,7 @@ namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\WrappableOutputFormatterInterface;
use Symfony\Component\Console\Output\ConsoleSectionOutput;
use Symfony\Component\Console\Output\OutputInterface;
@@ -41,17 +42,17 @@ class Table
/**
* Table headers.
*/
private $headers = array();
private $headers = [];
/**
* Table rows.
*/
private $rows = array();
private $rows = [];
/**
* Column widths cache.
*/
private $effectiveColumnWidths = array();
private $effectiveColumnWidths = [];
/**
* Number of columns cache.
@@ -73,15 +74,15 @@ class Table
/**
* @var array
*/
private $columnStyles = array();
private $columnStyles = [];
/**
* User set column widths.
*
* @var array
*/
private $columnWidths = array();
private $columnMaxWidths = array();
private $columnWidths = [];
private $columnMaxWidths = [];
private static $styles;
@@ -212,7 +213,7 @@ class Table
*/
public function setColumnWidths(array $widths)
{
$this->columnWidths = array();
$this->columnWidths = [];
foreach ($widths as $index => $width) {
$this->setColumnWidth($index, $width);
}
@@ -243,7 +244,7 @@ class Table
{
$headers = array_values($headers);
if (!empty($headers) && !\is_array($headers[0])) {
$headers = array($headers);
$headers = [$headers];
}
$this->headers = $headers;
@@ -253,7 +254,7 @@ class Table
public function setRows(array $rows)
{
$this->rows = array();
$this->rows = [];
return $this->addRows($rows);
}
@@ -339,7 +340,7 @@ class Table
*/
public function render()
{
$rows = array_merge($this->headers, array($divider = new TableSeparator()), $this->rows);
$rows = array_merge($this->headers, [$divider = new TableSeparator()], $this->rows);
$this->calculateNumberOfColumns($rows);
$rows = $this->buildTableRows($rows);
@@ -400,13 +401,13 @@ class Table
$crossings = $this->style->getCrossingChars();
if (self::SEPARATOR_MID === $type) {
list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[2], $crossings[8], $crossings[0], $crossings[4]);
list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[2], $crossings[8], $crossings[0], $crossings[4]];
} elseif (self::SEPARATOR_TOP === $type) {
list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[1], $crossings[2], $crossings[3]);
list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[1], $crossings[2], $crossings[3]];
} elseif (self::SEPARATOR_TOP_BOTTOM === $type) {
list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[9], $crossings[10], $crossings[11]);
list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[9], $crossings[10], $crossings[11]];
} else {
list($horizontal, $leftChar, $midChar, $rightChar) = array($borders[0], $crossings[7], $crossings[6], $crossings[5]);
list($horizontal, $leftChar, $midChar, $rightChar) = [$borders[0], $crossings[7], $crossings[6], $crossings[5]];
}
$markup = $leftChar;
@@ -500,7 +501,7 @@ class Table
*/
private function calculateNumberOfColumns($rows)
{
$columns = array(0);
$columns = [0];
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
continue;
@@ -516,22 +517,26 @@ class Table
{
/** @var WrappableOutputFormatterInterface $formatter */
$formatter = $this->output->getFormatter();
$unmergedRows = array();
$unmergedRows = [];
for ($rowKey = 0; $rowKey < \count($rows); ++$rowKey) {
$rows = $this->fillNextRows($rows, $rowKey);
// Remove any new line breaks and replace it with a new line
foreach ($rows[$rowKey] as $column => $cell) {
$colspan = $cell instanceof TableCell ? $cell->getColspan() : 1;
if (isset($this->columnMaxWidths[$column]) && Helper::strlenWithoutDecoration($formatter, $cell) > $this->columnMaxWidths[$column]) {
$cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column]);
$cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan);
}
if (!strstr($cell, "\n")) {
continue;
}
$escaped = implode("\n", array_map([OutputFormatter::class, 'escapeTrailingBackslash'], explode("\n", $cell)));
$cell = $cell instanceof TableCell ? new TableCell($escaped, ['colspan' => $cell->getColspan()]) : $escaped;
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
foreach ($lines as $lineKey => $line) {
if ($cell instanceof TableCell) {
$line = new TableCell($line, array('colspan' => $cell->getColspan()));
if ($colspan > 1) {
$line = new TableCell($line, ['colspan' => $colspan]);
}
if (0 === $lineKey) {
$rows[$rowKey][$column] = $line;
@@ -557,7 +562,7 @@ class Table
private function calculateRowCount(): int
{
$numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, array(new TableSeparator()), $this->rows))));
$numberOfRows = \count(iterator_to_array($this->buildTableRows(array_merge($this->headers, [new TableSeparator()], $this->rows))));
if ($this->headers) {
++$numberOfRows; // Add row for header separator
@@ -575,27 +580,27 @@ class Table
*/
private function fillNextRows(array $rows, int $line): array
{
$unmergedRows = array();
$unmergedRows = [];
foreach ($rows[$line] as $column => $cell) {
if (null !== $cell && !$cell instanceof TableCell && !is_scalar($cell) && !(\is_object($cell) && method_exists($cell, '__toString'))) {
throw new InvalidArgumentException(sprintf('A cell must be a TableCell, a scalar or an object implementing __toString, %s given.', \gettype($cell)));
}
if ($cell instanceof TableCell && $cell->getRowspan() > 1) {
$nbLines = $cell->getRowspan() - 1;
$lines = array($cell);
$lines = [$cell];
if (strstr($cell, "\n")) {
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
$nbLines = \count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;
$rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
$rows[$line][$column] = new TableCell($lines[0], ['colspan' => $cell->getColspan()]);
unset($lines[0]);
}
// create a two dimensional array (rowspan x colspan)
$unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, array()), $unmergedRows);
$unmergedRows = array_replace_recursive(array_fill($line + 1, $nbLines, []), $unmergedRows);
foreach ($unmergedRows as $unmergedRowKey => $unmergedRow) {
$value = isset($lines[$unmergedRowKey - $line]) ? $lines[$unmergedRowKey - $line] : '';
$unmergedRows[$unmergedRowKey][$column] = new TableCell($value, array('colspan' => $cell->getColspan()));
$unmergedRows[$unmergedRowKey][$column] = new TableCell($value, ['colspan' => $cell->getColspan()]);
if ($nbLines === $unmergedRowKey - $line) {
break;
}
@@ -608,7 +613,7 @@ class Table
if (isset($rows[$unmergedRowKey]) && \is_array($rows[$unmergedRowKey]) && ($this->getNumberOfColumns($rows[$unmergedRowKey]) + $this->getNumberOfColumns($unmergedRows[$unmergedRowKey]) <= $this->numberOfColumns)) {
foreach ($unmergedRow as $cellKey => $cell) {
// insert cell into row at cellKey position
array_splice($rows[$unmergedRowKey], $cellKey, 0, array($cell));
array_splice($rows[$unmergedRowKey], $cellKey, 0, [$cell]);
}
} else {
$row = $this->copyRow($rows, $unmergedRowKey - 1);
@@ -617,7 +622,7 @@ class Table
$row[$column] = $unmergedRow[$column];
}
}
array_splice($rows, $unmergedRowKey, 0, array($row));
array_splice($rows, $unmergedRowKey, 0, [$row]);
}
}
@@ -629,7 +634,7 @@ class Table
*/
private function fillCells($row)
{
$newRow = array();
$newRow = [];
foreach ($row as $column => $cell) {
$newRow[] = $cell;
if ($cell instanceof TableCell && $cell->getColspan() > 1) {
@@ -649,7 +654,7 @@ class Table
foreach ($row as $cellKey => $cellValue) {
$row[$cellKey] = '';
if ($cellValue instanceof TableCell) {
$row[$cellKey] = new TableCell('', array('colspan' => $cellValue->getColspan()));
$row[$cellKey] = new TableCell('', ['colspan' => $cellValue->getColspan()]);
}
}
@@ -691,7 +696,7 @@ class Table
private function calculateColumnsWidth(iterable $rows)
{
for ($column = 0; $column < $this->numberOfColumns; ++$column) {
$lengths = array();
$lengths = [];
foreach ($rows as $row) {
if ($row instanceof TableSeparator) {
continue;
@@ -742,7 +747,7 @@ class Table
*/
private function cleanup()
{
$this->effectiveColumnWidths = array();
$this->effectiveColumnWidths = [];
$this->numberOfColumns = null;
}
@@ -783,14 +788,14 @@ class Table
->setCrossingChars('┼', '╔', '╤', '╗', '╢', '╝', '╧', '╚', '╟', '╠', '╪', '╣')
;
return array(
return [
'default' => new TableStyle(),
'borderless' => $borderless,
'compact' => $compact,
'symfony-style-guide' => $styleGuide,
'box' => $box,
'box-double' => $boxDouble,
);
];
}
private function resolveStyle($name)

View File

@@ -19,12 +19,12 @@ use Symfony\Component\Console\Exception\InvalidArgumentException;
class TableCell
{
private $value;
private $options = array(
private $options = [
'rowspan' => 1,
'colspan' => 1,
);
];
public function __construct(string $value = '', array $options = array())
public function __construct(string $value = '', array $options = [])
{
$this->value = $value;

View File

@@ -18,7 +18,7 @@ namespace Symfony\Component\Console\Helper;
*/
class TableSeparator extends TableCell
{
public function __construct(array $options = array())
public function __construct(array $options = [])
{
parent::__construct('', $options);
}

View File

@@ -194,12 +194,12 @@ class TableStyle
*/
public function getBorderChars()
{
return array(
return [
$this->horizontalOutsideBorderChar,
$this->verticalOutsideBorderChar,
$this->horizontalInsideBorderChar,
$this->verticalInsideBorderChar,
);
];
}
/**
@@ -292,7 +292,7 @@ class TableStyle
*/
public function getCrossingChars(): array
{
return array(
return [
$this->crossingChar,
$this->crossingTopLeftChar,
$this->crossingTopMidChar,
@@ -305,7 +305,7 @@ class TableStyle
$this->crossingTopLeftBottomChar,
$this->crossingTopMidBottomChar,
$this->crossingTopRightBottomChar,
);
];
}
/**
@@ -413,7 +413,7 @@ class TableStyle
*/
public function setPadType($padType)
{
if (!\in_array($padType, array(STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH), true)) {
if (!\in_array($padType, [STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH], true)) {
throw new InvalidArgumentException('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).');
}

View File

@@ -169,7 +169,7 @@ class ArgvInput extends Input
// if input is expecting another argument, add it
if ($this->definition->hasArgument($c)) {
$arg = $this->definition->getArgument($c);
$this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
$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()) {
@@ -224,11 +224,11 @@ class ArgvInput extends Input
throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
}
if (\in_array($value, array('', null), true) && $option->acceptValue() && \count($this->parsed)) {
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, array('', null), true)) {
if ((isset($next[0]) && '-' !== $next[0]) || \in_array($next, ['', null], true)) {
$value = $next;
} else {
array_unshift($this->parsed, $next);
@@ -257,8 +257,27 @@ class ArgvInput extends Input
*/
public function getFirstArgument()
{
foreach ($this->tokens as $token) {
$isOption = false;
foreach ($this->tokens as $i => $token) {
if ($token && '-' === $token[0]) {
if (false !== strpos($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;
}

View File

@@ -19,7 +19,7 @@ use Symfony\Component\Console\Exception\InvalidOptionException;
*
* Usage:
*
* $input = new ArrayInput(array('name' => 'foo', '--bar' => 'foobar'));
* $input = new ArrayInput(['command' => 'foo:bar', 'foo' => 'bar', '--bar' => 'foobar']);
*
* @author Fabien Potencier <fabien@symfony.com>
*/
@@ -103,7 +103,7 @@ class ArrayInput extends Input
*/
public function __toString()
{
$params = array();
$params = [];
foreach ($this->parameters as $param => $val) {
if ($param && '-' === $param[0]) {
if (\is_array($val)) {
@@ -114,7 +114,7 @@ class ArrayInput extends Input
$params[] = $param.('' != $val ? '='.$this->escapeToken($val) : '');
}
} else {
$params[] = \is_array($val) ? implode(' ', array_map(array($this, 'escapeToken'), $val)) : $this->escapeToken($val);
$params[] = \is_array($val) ? implode(' ', array_map([$this, 'escapeToken'], $val)) : $this->escapeToken($val);
}
}

View File

@@ -29,8 +29,8 @@ abstract class Input implements InputInterface, StreamableInputInterface
{
protected $definition;
protected $stream;
protected $options = array();
protected $arguments = array();
protected $options = [];
protected $arguments = [];
protected $interactive = true;
public function __construct(InputDefinition $definition = null)
@@ -48,8 +48,8 @@ abstract class Input implements InputInterface, StreamableInputInterface
*/
public function bind(InputDefinition $definition)
{
$this->arguments = array();
$this->options = array();
$this->arguments = [];
$this->options = [];
$this->definition = $definition;
$this->parse();
@@ -69,7 +69,7 @@ abstract class Input implements InputInterface, StreamableInputInterface
$givenArguments = $this->arguments;
$missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) {
return !array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired();
return !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired();
});
if (\count($missingArguments) > 0) {
@@ -150,7 +150,7 @@ abstract class Input implements InputInterface, StreamableInputInterface
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();
return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();
}
/**

View File

@@ -98,7 +98,7 @@ class InputArgument
if ($this->isArray()) {
if (null === $default) {
$default = array();
$default = [];
} elseif (!\is_array($default)) {
throw new LogicException('A default value for an array argument must be an array.');
}

View File

@@ -19,10 +19,10 @@ use Symfony\Component\Console\Exception\LogicException;
*
* Usage:
*
* $definition = new InputDefinition(array(
* $definition = new InputDefinition([
* new InputArgument('name', InputArgument::REQUIRED),
* new InputOption('foo', 'f', InputOption::VALUE_REQUIRED),
* ));
* ]);
*
* @author Fabien Potencier <fabien@symfony.com>
*/
@@ -38,7 +38,7 @@ class InputDefinition
/**
* @param array $definition An array of InputArgument and InputOption instance
*/
public function __construct(array $definition = array())
public function __construct(array $definition = [])
{
$this->setDefinition($definition);
}
@@ -48,8 +48,8 @@ class InputDefinition
*/
public function setDefinition(array $definition)
{
$arguments = array();
$options = array();
$arguments = [];
$options = [];
foreach ($definition as $item) {
if ($item instanceof InputOption) {
$options[] = $item;
@@ -67,9 +67,9 @@ class InputDefinition
*
* @param InputArgument[] $arguments An array of InputArgument objects
*/
public function setArguments($arguments = array())
public function setArguments($arguments = [])
{
$this->arguments = array();
$this->arguments = [];
$this->requiredCount = 0;
$this->hasOptional = false;
$this->hasAnArrayArgument = false;
@@ -81,7 +81,7 @@ class InputDefinition
*
* @param InputArgument[] $arguments An array of InputArgument objects
*/
public function addArguments($arguments = array())
public function addArguments($arguments = [])
{
if (null !== $arguments) {
foreach ($arguments as $argument) {
@@ -191,7 +191,7 @@ class InputDefinition
*/
public function getArgumentDefaults()
{
$values = array();
$values = [];
foreach ($this->arguments as $argument) {
$values[$argument->getName()] = $argument->getDefault();
}
@@ -204,10 +204,10 @@ class InputDefinition
*
* @param InputOption[] $options An array of InputOption objects
*/
public function setOptions($options = array())
public function setOptions($options = [])
{
$this->options = array();
$this->shortcuts = array();
$this->options = [];
$this->shortcuts = [];
$this->addOptions($options);
}
@@ -216,7 +216,7 @@ class InputDefinition
*
* @param InputOption[] $options An array of InputOption objects
*/
public function addOptions($options = array())
public function addOptions($options = [])
{
foreach ($options as $option) {
$this->addOption($option);
@@ -322,7 +322,7 @@ class InputDefinition
*/
public function getOptionDefaults()
{
$values = array();
$values = [];
foreach ($this->options as $option) {
$values[$option->getName()] = $option->getDefault();
}
@@ -338,8 +338,10 @@ class InputDefinition
* @return string The InputOption name
*
* @throws InvalidArgumentException When option given does not exist
*
* @internal
*/
private function shortcutToName($shortcut)
public function shortcutToName($shortcut)
{
if (!isset($this->shortcuts[$shortcut])) {
throw new InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
@@ -357,7 +359,7 @@ class InputDefinition
*/
public function getSynopsis($short = false)
{
$elements = array();
$elements = [];
if ($short && $this->getOptions()) {
$elements[] = '[options]';

View File

@@ -34,7 +34,7 @@ class InputOption
/**
* @param string $name The option name
* @param string|array $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param string|array|null $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
* @param int|null $mode The option mode: One of the VALUE_* constants
* @param string $description A description text
* @param string|string[]|int|bool|null $default The default value (must be null for self::VALUE_NONE)
@@ -89,7 +89,7 @@ class InputOption
/**
* Returns the option shortcut.
*
* @return string The shortcut
* @return string|null The shortcut
*/
public function getShortcut()
{
@@ -161,7 +161,7 @@ class InputOption
if ($this->isArray()) {
if (null === $default) {
$default = array();
$default = [];
} elseif (!\is_array($default)) {
throw new LogicException('A default value for an array option must be an array.');
}

View File

@@ -32,7 +32,7 @@ class StringInput extends ArgvInput
*/
public function __construct(string $input)
{
parent::__construct(array());
parent::__construct([]);
$this->setTokens($this->tokenize($input));
}
@@ -48,13 +48,13 @@ class StringInput extends ArgvInput
*/
private function tokenize($input)
{
$tokens = array();
$tokens = [];
$length = \strlen($input);
$cursor = 0;
while ($cursor < $length) {
if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
} elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
$tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, \strlen($match[3]) - 2)));
$tokens[] = $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, \strlen($match[3]) - 2)));
} elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
$tokens[] = stripcslashes(substr($match[0], 1, \strlen($match[0]) - 2));
} elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {

View File

@@ -30,7 +30,7 @@ class ConsoleLogger extends AbstractLogger
const ERROR = 'error';
private $output;
private $verbosityLevelMap = array(
private $verbosityLevelMap = [
LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
@@ -39,8 +39,8 @@ class ConsoleLogger extends AbstractLogger
LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE,
LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE,
LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG,
);
private $formatLevelMap = array(
];
private $formatLevelMap = [
LogLevel::EMERGENCY => self::ERROR,
LogLevel::ALERT => self::ERROR,
LogLevel::CRITICAL => self::ERROR,
@@ -49,10 +49,10 @@ class ConsoleLogger extends AbstractLogger
LogLevel::NOTICE => self::INFO,
LogLevel::INFO => self::INFO,
LogLevel::DEBUG => self::INFO,
);
];
private $errored = false;
public function __construct(OutputInterface $output, array $verbosityLevelMap = array(), array $formatLevelMap = array())
public function __construct(OutputInterface $output, array $verbosityLevelMap = [], array $formatLevelMap = [])
{
$this->output = $output;
$this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
@@ -62,7 +62,7 @@ class ConsoleLogger extends AbstractLogger
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
public function log($level, $message, array $context = [])
{
if (!isset($this->verbosityLevelMap[$level])) {
throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
@@ -106,7 +106,7 @@ class ConsoleLogger extends AbstractLogger
return $message;
}
$replacements = array();
$replacements = [];
foreach ($context as $key => $val) {
if (null === $val || is_scalar($val) || (\is_object($val) && method_exists($val, '__toString'))) {
$replacements["{{$key}}"] = $val;

View File

@@ -30,7 +30,7 @@ use Symfony\Component\Console\Formatter\OutputFormatterInterface;
class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
{
private $stderr;
private $consoleSectionOutputs = array();
private $consoleSectionOutputs = [];
/**
* @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface)
@@ -130,11 +130,11 @@ class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
*/
private function isRunningOS400()
{
$checks = array(
$checks = [
\function_exists('php_uname') ? php_uname('s') : '',
getenv('OSTYPE'),
PHP_OS,
);
];
return false !== stripos(implode(';', $checks), 'OS400');
}

View File

@@ -21,7 +21,7 @@ use Symfony\Component\Console\Terminal;
*/
class ConsoleSectionOutput extends StreamOutput
{
private $content = array();
private $content = [];
private $lines = 0;
private $sections;
private $terminal;
@@ -53,7 +53,7 @@ class ConsoleSectionOutput extends StreamOutput
\array_splice($this->content, -($lines * 2)); // Multiply lines by 2 to cater for each new line added between content
} else {
$lines = $this->lines;
$this->content = array();
$this->content = [];
}
$this->lines -= $lines;
@@ -113,7 +113,7 @@ class ConsoleSectionOutput extends StreamOutput
private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string
{
$numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection;
$erasedContent = array();
$erasedContent = [];
foreach ($this->sections as $section) {
if ($section === $this) {

View File

@@ -138,7 +138,7 @@ abstract class Output implements OutputInterface
public function write($messages, $newline = false, $options = self::OUTPUT_NORMAL)
{
if (!is_iterable($messages)) {
$messages = array($messages);
$messages = [$messages];
}
$types = self::OUTPUT_NORMAL | self::OUTPUT_RAW | self::OUTPUT_PLAIN;

View File

@@ -139,12 +139,12 @@ class ChoiceQuestion extends Question
}
$selectedChoices = explode(',', $selectedChoices);
} else {
$selectedChoices = array($selected);
$selectedChoices = [$selected];
}
$multiselectChoices = array();
$multiselectChoices = [];
foreach ($selectedChoices as $value) {
$results = array();
$results = [];
foreach ($choices as $key => $choice) {
if ($choice === $value) {
$results[] = $key;

View File

@@ -53,7 +53,7 @@ class ConfirmationQuestion extends Question
return $answer && $answerIsTrue;
}
return !$answer || $answerIsTrue;
return '' === $answer || $answerIsTrue;
};
}
}

View File

@@ -63,7 +63,7 @@ class SymfonyStyle extends OutputStyle
*/
public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = true)
{
$messages = \is_array($messages) ? array_values($messages) : array($messages);
$messages = \is_array($messages) ? array_values($messages) : [$messages];
$this->autoPrependBlock();
$this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
@@ -76,10 +76,10 @@ class SymfonyStyle extends OutputStyle
public function title($message)
{
$this->autoPrependBlock();
$this->writeln(array(
$this->writeln([
sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
));
]);
$this->newLine();
}
@@ -89,10 +89,10 @@ class SymfonyStyle extends OutputStyle
public function section($message)
{
$this->autoPrependBlock();
$this->writeln(array(
$this->writeln([
sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
));
]);
$this->newLine();
}
@@ -117,7 +117,7 @@ class SymfonyStyle extends OutputStyle
{
$this->autoPrependText();
$messages = \is_array($message) ? array_values($message) : array($message);
$messages = \is_array($message) ? array_values($message) : [$message];
foreach ($messages as $message) {
$this->writeln(sprintf(' %s', $message));
}
@@ -307,7 +307,7 @@ class SymfonyStyle extends OutputStyle
public function writeln($messages, $type = self::OUTPUT_NORMAL)
{
if (!is_iterable($messages)) {
$messages = array($messages);
$messages = [$messages];
}
foreach ($messages as $message) {
@@ -322,7 +322,7 @@ class SymfonyStyle extends OutputStyle
public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
{
if (!is_iterable($messages)) {
$messages = array($messages);
$messages = [$messages];
}
foreach ($messages as $message) {
@@ -392,7 +392,7 @@ class SymfonyStyle extends OutputStyle
{
$indentLength = 0;
$prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
$lines = array();
$lines = [];
if (null !== $type) {
$type = sprintf('[%s] ', $type);

View File

@@ -91,11 +91,11 @@ class Terminal
return;
}
$descriptorspec = array(
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
$descriptorspec = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open('mode CON', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
if (\is_resource($process)) {
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);
@@ -103,7 +103,7 @@ class Terminal
proc_close($process);
if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
return array((int) $matches[2], (int) $matches[1]);
return [(int) $matches[2], (int) $matches[1]];
}
}
}
@@ -119,12 +119,12 @@ class Terminal
return;
}
$descriptorspec = array(
1 => array('pipe', 'w'),
2 => array('pipe', 'w'),
);
$descriptorspec = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
$process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]);
if (\is_resource($process)) {
$info = stream_get_contents($pipes[1]);
fclose($pipes[1]);

View File

@@ -52,7 +52,7 @@ class ApplicationTester
*
* @return int The command exit code
*/
public function run(array $input, $options = array())
public function run(array $input, $options = [])
{
$this->input = new ArrayInput($input);
if (isset($options['interactive'])) {

View File

@@ -48,7 +48,7 @@ class CommandTester
*
* @return int The command exit code
*/
public function execute(array $input, array $options = array())
public function execute(array $input, array $options = [])
{
// set the command name automatically if the application requires
// this argument and no command name was passed
@@ -56,13 +56,12 @@ class CommandTester
&& (null !== $application = $this->command->getApplication())
&& $application->getDefinition()->hasArgument('command')
) {
$input = array_merge(array('command' => $this->command->getName()), $input);
$input = array_merge(['command' => $this->command->getName()], $input);
}
$this->input = new ArrayInput($input);
if ($this->inputs) {
$this->input->setStream(self::createStream($this->inputs));
}
// Use an in-memory input stream even if no inputs are set so that QuestionHelper::ask() does not rely on the blocking STDIN.
$this->input->setStream(self::createStream($this->inputs));
if (isset($options['interactive'])) {
$this->input->setInteractive($options['interactive']);

View File

@@ -23,7 +23,7 @@ trait TesterTrait
{
/** @var StreamOutput */
private $output;
private $inputs = array();
private $inputs = [];
private $captureStreamsIndependently = false;
/**
@@ -35,6 +35,10 @@ trait TesterTrait
*/
public function getDisplay($normalize = false)
{
if (null === $this->output) {
throw new \RuntimeException('Output not initialized, did you execute the command before requesting the display?');
}
rewind($this->output->getStream());
$display = stream_get_contents($this->output->getStream());
@@ -126,7 +130,7 @@ trait TesterTrait
*/
private function initOutput(array $options)
{
$this->captureStreamsIndependently = array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately'];
$this->captureStreamsIndependently = \array_key_exists('capture_stderr_separately', $options) && $options['capture_stderr_separately'];
if (!$this->captureStreamsIndependently) {
$this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) {

View File

@@ -41,6 +41,21 @@ class ApplicationTest extends TestCase
{
protected static $fixturesPath;
private $colSize;
protected function setUp()
{
$this->colSize = getenv('COLUMNS');
}
protected function tearDown()
{
putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
putenv('SHELL_VERBOSITY');
unset($_ENV['SHELL_VERBOSITY']);
unset($_SERVER['SHELL_VERBOSITY']);
}
public static function setUpBeforeClass()
{
self::$fixturesPath = realpath(__DIR__.'/Fixtures/');
@@ -84,7 +99,7 @@ class ApplicationTest extends TestCase
$application = new Application('foo', 'bar');
$this->assertEquals('foo', $application->getName(), '__construct() takes the application name as its first argument');
$this->assertEquals('bar', $application->getVersion(), '__construct() takes the application version as its second argument');
$this->assertEquals(array('help', 'list'), array_keys($application->all()), '__construct() registered the help and list commands by default');
$this->assertEquals(['help', 'list'], array_keys($application->all()), '__construct() registered the help and list commands by default');
}
public function testSetGetName()
@@ -134,9 +149,9 @@ class ApplicationTest extends TestCase
$commands = $application->all('foo');
$this->assertCount(1, $commands, '->all() takes a namespace as its first argument');
$application->setCommandLoader(new FactoryCommandLoader(array(
$application->setCommandLoader(new FactoryCommandLoader([
'foo:bar1' => function () { return new \Foo1Command(); },
)));
]));
$commands = $application->all('foo');
$this->assertCount(2, $commands, '->all() takes a namespace as its first argument');
$this->assertInstanceOf(\FooCommand::class, $commands['foo:bar'], '->all() returns the registered commands');
@@ -158,9 +173,9 @@ class ApplicationTest extends TestCase
$this->assertEquals($foo, $commands['foo:bar'], '->add() registers a command');
$application = new Application();
$application->addCommands(array($foo = new \FooCommand(), $foo1 = new \Foo1Command()));
$application->addCommands([$foo = new \FooCommand(), $foo1 = new \Foo1Command()]);
$commands = $application->all();
$this->assertEquals(array($foo, $foo1), array($commands['foo:bar'], $commands['foo:bar1']), '->addCommands() registers an array of commands');
$this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands');
}
/**
@@ -206,9 +221,9 @@ class ApplicationTest extends TestCase
$this->assertEquals($foo, $application->get('foo:bar'), '->get() returns a command by name');
$this->assertEquals($foo, $application->get('afoobar'), '->get() returns a command by alias');
$application->setCommandLoader(new FactoryCommandLoader(array(
$application->setCommandLoader(new FactoryCommandLoader([
'foo:bar1' => function () { return new \Foo1Command(); },
)));
]));
$this->assertTrue($application->has('afoobar'), '->has() returns true if an instance is registered for an alias even with command loader');
$this->assertEquals($foo, $application->get('foo:bar'), '->get() returns an instance by name even with command loader');
@@ -226,7 +241,7 @@ class ApplicationTest extends TestCase
$application->setCatchExceptions(false);
$tester = new ApplicationTester($application);
$tester->run(array('-h' => true, '-q' => true), array('decorated' => false));
$tester->run(['-h' => true, '-q' => true], ['decorated' => false]);
$this->assertEmpty($tester->getDisplay(true));
}
@@ -246,7 +261,7 @@ class ApplicationTest extends TestCase
$application = new Application();
$application->add(new \FooCommand());
$application->add(new \Foo1Command());
$this->assertEquals(array('foo'), $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
$this->assertEquals(['foo'], $application->getNamespaces(), '->getNamespaces() returns an array of unique used namespaces');
}
public function testFindNamespace()
@@ -368,9 +383,9 @@ class ApplicationTest extends TestCase
public function testFindWithCommandLoader()
{
$application = new Application();
$application->setCommandLoader(new FactoryCommandLoader(array(
$application->setCommandLoader(new FactoryCommandLoader([
'foo:bar' => $f = function () { return new \FooCommand(); },
)));
]));
$this->assertInstanceOf('FooCommand', $application->find('foo:bar'), '->find() returns a command if its name exists');
$this->assertInstanceOf('Symfony\Component\Console\Command\HelpCommand', $application->find('h'), '->find() returns a command if its name exists');
@@ -384,6 +399,7 @@ class ApplicationTest extends TestCase
*/
public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage)
{
putenv('COLUMNS=120');
if (method_exists($this, 'expectException')) {
$this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException');
$this->expectExceptionMessage($expectedExceptionMessage);
@@ -401,23 +417,23 @@ class ApplicationTest extends TestCase
public function provideAmbiguousAbbreviations()
{
return array(
array('f', 'Command "f" is not defined.'),
array(
return [
['f', 'Command "f" is not defined.'],
[
'a',
"Command \"a\" is ambiguous.\nDid you mean one of these?\n".
" afoobar The foo:bar command\n".
" afoobar1 The foo:bar1 command\n".
' afoobar2 The foo1:bar command',
),
array(
],
[
'foo:b',
"Command \"foo:b\" is ambiguous.\nDid you mean one of these?\n".
" foo:bar The foo:bar command\n".
" foo:bar1 The foo:bar1 command\n".
' foo1:bar The foo1:bar command',
),
);
],
];
}
public function testFindCommandEqualNamespace()
@@ -465,7 +481,7 @@ class ApplicationTest extends TestCase
$application->add(new \Foo1Command());
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foos:bar1'), array('decorated' => false));
$tester->run(['command' => 'foos:bar1'], ['decorated' => false]);
$this->assertSame('
There are no commands defined in the "foos" namespace.
@@ -483,8 +499,8 @@ class ApplicationTest extends TestCase
$application->add(new \FooWithoutAliasCommand());
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->setInputs(array('y'));
$tester->run(array('command' => 'foos'), array('decorated' => false));
$tester->setInputs(['y']);
$tester->run(['command' => 'foos'], ['decorated' => false]);
$display = trim($tester->getDisplay(true));
$this->assertContains('Command "foos" is not defined', $display);
$this->assertContains('Do you want to run "foo" instead? (yes/no) [no]:', $display);
@@ -497,8 +513,8 @@ class ApplicationTest extends TestCase
$application->add(new \FooWithoutAliasCommand());
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->setInputs(array('n'));
$exitCode = $tester->run(array('command' => 'foos'), array('decorated' => false));
$tester->setInputs(['n']);
$exitCode = $tester->run(['command' => 'foos'], ['decorated' => false]);
$this->assertSame(1, $exitCode);
$display = trim($tester->getDisplay(true));
$this->assertContains('Command "foos" is not defined', $display);
@@ -507,14 +523,15 @@ class ApplicationTest extends TestCase
public function provideInvalidCommandNamesSingle()
{
return array(
array('foo3:barr'),
array('fooo3:bar'),
);
return [
['foo3:barr'],
['fooo3:bar'],
];
}
public function testFindAlternativeExceptionMessageMultiple()
{
putenv('COLUMNS=120');
$application = new Application();
$application->add(new \FooCommand());
$application->add(new \Foo1Command());
@@ -568,7 +585,7 @@ class ApplicationTest extends TestCase
$this->fail('->find() throws a CommandNotFoundException if command does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist');
$this->assertSame(array(), $e->getAlternatives());
$this->assertSame([], $e->getAlternatives());
$this->assertEquals(sprintf('Command "%s" is not defined.', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, without alternatives');
}
@@ -579,7 +596,7 @@ class ApplicationTest extends TestCase
$this->fail('->find() throws a CommandNotFoundException if command does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if command does not exist');
$this->assertSame(array('afoobar1', 'foo:bar1'), $e->getAlternatives());
$this->assertSame(['afoobar1', 'foo:bar1'], $e->getAlternatives());
$this->assertRegExp(sprintf('/Command "%s" is not defined./', $commandName), $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternatives');
$this->assertRegExp('/afoobar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "afoobar1"');
$this->assertRegExp('/foo:bar1/', $e->getMessage(), '->find() throws a CommandNotFoundException if command does not exist, with alternative : "foo:bar1"');
@@ -590,7 +607,7 @@ class ApplicationTest extends TestCase
public function testFindAlternativeCommandsWithAnAlias()
{
$fooCommand = new \FooCommand();
$fooCommand->setAliases(array('foo2'));
$fooCommand->setAliases(['foo2']);
$application = new Application();
$application->add($fooCommand);
@@ -614,7 +631,7 @@ class ApplicationTest extends TestCase
$this->fail('->find() throws a CommandNotFoundException if namespace does not exist');
} catch (\Exception $e) {
$this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e, '->find() throws a CommandNotFoundException if namespace does not exist');
$this->assertSame(array(), $e->getAlternatives());
$this->assertSame([], $e->getAlternatives());
$this->assertEquals('There are no commands defined in the "Unknown-namespace" namespace.', $e->getMessage(), '->find() throws a CommandNotFoundException if namespace does not exist, without alternatives');
}
@@ -644,7 +661,7 @@ class ApplicationTest extends TestCase
$application->add(new \Foo2Command());
$application->add(new \Foo3Command());
$expectedAlternatives = array(
$expectedAlternatives = [
'afoobar',
'afoobar1',
'afoobar2',
@@ -652,7 +669,7 @@ class ApplicationTest extends TestCase
'foo3:bar',
'foo:bar',
'foo:bar1',
);
];
try {
$application->find('foo');
@@ -667,10 +684,10 @@ class ApplicationTest extends TestCase
public function testFindNamespaceDoesNotFailOnDeepSimilarNamespaces()
{
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('getNamespaces'))->getMock();
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getNamespaces'])->getMock();
$application->expects($this->once())
->method('getNamespaces')
->will($this->returnValue(array('foo:sublong', 'bar:sub')));
->will($this->returnValue(['foo:sublong', 'bar:sub']));
$this->assertEquals('foo:sublong', $application->findNamespace('f:sub'));
}
@@ -697,16 +714,16 @@ class ApplicationTest extends TestCase
$application->setCatchExceptions(true);
$this->assertTrue($application->areExceptionsCaught());
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getDisplay(true), '->setCatchExceptions() sets the catch exception flag');
$tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->setCatchExceptions() sets the catch exception flag');
$this->assertSame('', $tester->getDisplay(true));
$application->setCatchExceptions(false);
try {
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->fail('->setCatchExceptions() sets the catch exception flag');
} catch (\Exception $e) {
$this->assertInstanceOf('\Exception', $e, '->setCatchExceptions() sets the catch exception flag');
@@ -730,29 +747,29 @@ class ApplicationTest extends TestCase
putenv('COLUMNS=120');
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception');
$tester->run(array('command' => 'foo'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]);
$this->assertContains('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose');
$tester->run(array('command' => 'list', '--foo' => true), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getErrorOutput(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command');
$application->add(new \Foo3Command());
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo3:bar'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
$tester->run(array('command' => 'foo3:bar'), array('decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE));
$tester->run(['command' => 'foo3:bar'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]);
$this->assertRegExp('/\[Exception\]\s*First exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is default and verbosity is verbose');
$this->assertRegExp('/\[Exception\]\s*Second exception/', $tester->getDisplay(), '->renderException() renders a pretty exception without code exception when code exception is 0 and verbosity is verbose');
$this->assertRegExp('/\[Exception \(404\)\]\s*Third exception/', $tester->getDisplay(), '->renderException() renders a pretty exception with code exception when code exception is 404 and verbosity is verbose');
$tester->run(array('command' => 'foo3:bar'), array('decorated' => true));
$tester->run(['command' => 'foo3:bar'], ['decorated' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getDisplay(true), '->renderException() renders a pretty exceptions with previous exceptions');
$tester->run(array('command' => 'foo3:bar'), array('decorated' => true, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo3:bar'], ['decorated' => true, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception3decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
$application = new Application();
@@ -760,7 +777,7 @@ class ApplicationTest extends TestCase
putenv('COLUMNS=32');
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception4.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
putenv('COLUMNS=120');
}
@@ -775,10 +792,10 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
$tester->run(array('command' => 'foo'), array('decorated' => true, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => true, 'capture_stderr_separately' => true]);
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth1decorated.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exceptions with previous exceptions');
$application = new Application();
@@ -788,7 +805,7 @@ class ApplicationTest extends TestCase
throw new \Exception('コマンドの実行中にエラーが発生しました。');
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false, 'capture_stderr_separately' => true));
$tester->run(['command' => 'foo'], ['decorated' => false, 'capture_stderr_separately' => true]);
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getErrorOutput(true), '->renderException() wraps messages when they are bigger than the terminal');
putenv('COLUMNS=120');
}
@@ -803,14 +820,14 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting');
putenv('COLUMNS=120');
}
public function testRenderExceptionLineBreaks()
{
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('getTerminalWidth'))->getMock();
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['getTerminalWidth'])->getMock();
$application->setAutoExit(false);
$application->expects($this->any())
->method('getTerminalWidth')
@@ -820,7 +837,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
}
@@ -834,7 +851,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
$application = new Application();
@@ -845,7 +862,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true));
}
@@ -859,7 +876,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));
$application = new Application();
@@ -870,7 +887,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'), array('decorated' => false));
$tester->run(['command' => 'foo'], ['decorated' => false]);
$this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true));
}
@@ -880,7 +897,7 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->add($command = new \Foo1Command());
$_SERVER['argv'] = array('cli.php', 'foo:bar1');
$_SERVER['argv'] = ['cli.php', 'foo:bar1'];
ob_start();
$application->run();
@@ -896,63 +913,63 @@ class ApplicationTest extends TestCase
$this->ensureStaticCommandHelp($application);
$tester = new ApplicationTester($application);
$tester->run(array(), array('decorated' => false));
$tester->run([], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run1.txt', $tester->getDisplay(true), '->run() runs the list command if no argument is passed');
$tester->run(array('--help' => true), array('decorated' => false));
$tester->run(['--help' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if --help is passed');
$tester->run(array('-h' => true), array('decorated' => false));
$tester->run(['-h' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run2.txt', $tester->getDisplay(true), '->run() runs the help command if -h is passed');
$tester->run(array('command' => 'list', '--help' => true), array('decorated' => false));
$tester->run(['command' => 'list', '--help' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if --help is passed');
$tester->run(array('command' => 'list', '-h' => true), array('decorated' => false));
$tester->run(['command' => 'list', '-h' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run3.txt', $tester->getDisplay(true), '->run() displays the help if -h is passed');
$tester->run(array('--ansi' => true));
$tester->run(['--ansi' => true]);
$this->assertTrue($tester->getOutput()->isDecorated(), '->run() forces color output if --ansi is passed');
$tester->run(array('--no-ansi' => true));
$tester->run(['--no-ansi' => true]);
$this->assertFalse($tester->getOutput()->isDecorated(), '->run() forces color output to be disabled if --no-ansi is passed');
$tester->run(array('--version' => true), array('decorated' => false));
$tester->run(['--version' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if --version is passed');
$tester->run(array('-V' => true), array('decorated' => false));
$tester->run(['-V' => true], ['decorated' => false]);
$this->assertStringEqualsFile(self::$fixturesPath.'/application_run4.txt', $tester->getDisplay(true), '->run() displays the program version if -v is passed');
$tester->run(array('command' => 'list', '--quiet' => true));
$tester->run(['command' => 'list', '--quiet' => true]);
$this->assertSame('', $tester->getDisplay(), '->run() removes all output if --quiet is passed');
$this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if --quiet is passed');
$tester->run(array('command' => 'list', '-q' => true));
$tester->run(['command' => 'list', '-q' => true]);
$this->assertSame('', $tester->getDisplay(), '->run() removes all output if -q is passed');
$this->assertFalse($tester->getInput()->isInteractive(), '->run() sets off the interactive mode if -q is passed');
$tester->run(array('command' => 'list', '--verbose' => true));
$tester->run(['command' => 'list', '--verbose' => true]);
$this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose is passed');
$tester->run(array('command' => 'list', '--verbose' => 1));
$tester->run(['command' => 'list', '--verbose' => 1]);
$this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if --verbose=1 is passed');
$tester->run(array('command' => 'list', '--verbose' => 2));
$tester->run(['command' => 'list', '--verbose' => 2]);
$this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to very verbose if --verbose=2 is passed');
$tester->run(array('command' => 'list', '--verbose' => 3));
$tester->run(['command' => 'list', '--verbose' => 3]);
$this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to debug if --verbose=3 is passed');
$tester->run(array('command' => 'list', '--verbose' => 4));
$tester->run(['command' => 'list', '--verbose' => 4]);
$this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if unknown --verbose level is passed');
$tester->run(array('command' => 'list', '-v' => true));
$tester->run(['command' => 'list', '-v' => true]);
$this->assertSame(Output::VERBOSITY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
$tester->run(array('command' => 'list', '-vv' => true));
$tester->run(['command' => 'list', '-vv' => true]);
$this->assertSame(Output::VERBOSITY_VERY_VERBOSE, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
$tester->run(array('command' => 'list', '-vvv' => true));
$tester->run(['command' => 'list', '-vvv' => true]);
$this->assertSame(Output::VERBOSITY_DEBUG, $tester->getOutput()->getVerbosity(), '->run() sets the output to verbose if -v is passed');
$application = new Application();
@@ -961,13 +978,26 @@ class ApplicationTest extends TestCase
$application->add(new \FooCommand());
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo:bar', '--no-interaction' => true), array('decorated' => false));
$tester->run(['command' => 'foo:bar', '--no-interaction' => true], ['decorated' => false]);
$this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if --no-interaction is passed');
$tester->run(array('command' => 'foo:bar', '-n' => true), array('decorated' => false));
$tester->run(['command' => 'foo:bar', '-n' => true], ['decorated' => false]);
$this->assertSame('called'.PHP_EOL, $tester->getDisplay(), '->run() does not call interact() if -n is passed');
}
public function testRunWithGlobalOptionAndNoCommand()
{
$application = new Application();
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->getDefinition()->addOption(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL));
$output = new StreamOutput(fopen('php://memory', 'w', false));
$input = new ArgvInput(['cli.php', '--foo', 'bar']);
$this->assertSame(0, $application->run($input, $output));
}
/**
* Issue #9285.
*
@@ -984,12 +1014,12 @@ class ApplicationTest extends TestCase
$output = new StreamOutput(fopen('php://memory', 'w', false));
$input = new ArgvInput(array('cli.php', '-v', 'foo:bar'));
$input = new ArgvInput(['cli.php', '-v', 'foo:bar']);
$application->run($input, $output);
$this->addToAssertionCount(1);
$input = new ArgvInput(array('cli.php', '--verbose', 'foo:bar'));
$input = new ArgvInput(['cli.php', '--verbose', 'foo:bar']);
$application->run($input, $output);
$this->addToAssertionCount(1);
@@ -999,13 +1029,13 @@ class ApplicationTest extends TestCase
{
$exception = new \Exception('', 4);
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock();
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock();
$application->setAutoExit(false);
$application->expects($this->once())
->method('doRun')
->willThrowException($exception);
$exitCode = $application->run(new ArrayInput(array()), new NullOutput());
$exitCode = $application->run(new ArrayInput([]), new NullOutput());
$this->assertSame(4, $exitCode, '->run() returns integer exit code extracted from raised exception');
}
@@ -1029,7 +1059,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'test'));
$tester->run(['command' => 'test']);
$this->assertTrue($passedRightValue, '-> exit code 4 was passed in the console.terminate event');
}
@@ -1038,13 +1068,13 @@ class ApplicationTest extends TestCase
{
$exception = new \Exception('', 0);
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('doRun'))->getMock();
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(['doRun'])->getMock();
$application->setAutoExit(false);
$application->expects($this->once())
->method('doRun')
->willThrowException($exception);
$exitCode = $application->run(new ArrayInput(array()), new NullOutput());
$exitCode = $application->run(new ArrayInput([]), new NullOutput());
$this->assertSame(1, $exitCode, '->run() returns exit code 1 when exception code is 0');
}
@@ -1068,7 +1098,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'test'));
$tester->run(['command' => 'test']);
$this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event');
}
@@ -1089,12 +1119,12 @@ class ApplicationTest extends TestCase
$application
->register('foo')
->setAliases(array('f'))
->setDefinition(array(new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')))
->setAliases(['f'])
->setDefinition([new InputOption('survey', 'e', InputOption::VALUE_REQUIRED, 'My option with a shortcut.')])
->setCode(function (InputInterface $input, OutputInterface $output) {})
;
$input = new ArrayInput(array('command' => 'foo'));
$input = new ArrayInput(['command' => 'foo']);
$output = new NullOutput();
$application->run($input, $output);
@@ -1111,22 +1141,22 @@ class ApplicationTest extends TestCase
$application->setCatchExceptions(false);
$application
->register('foo')
->setDefinition(array($def))
->setDefinition([$def])
->setCode(function (InputInterface $input, OutputInterface $output) {})
;
$input = new ArrayInput(array('command' => 'foo'));
$input = new ArrayInput(['command' => 'foo']);
$output = new NullOutput();
$application->run($input, $output);
}
public function getAddingAlreadySetDefinitionElementData()
{
return array(
array(new InputArgument('command', InputArgument::REQUIRED)),
array(new InputOption('quiet', '', InputOption::VALUE_NONE)),
array(new InputOption('query', 'q', InputOption::VALUE_NONE)),
);
return [
[new InputArgument('command', InputArgument::REQUIRED)],
[new InputOption('quiet', '', InputOption::VALUE_NONE)],
[new InputOption('query', 'q', InputOption::VALUE_NONE)],
];
}
public function testGetDefaultHelperSetReturnsDefaultValues()
@@ -1146,7 +1176,7 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->setHelperSet(new HelperSet(array(new FormatterHelper())));
$application->setHelperSet(new HelperSet([new FormatterHelper()]));
$helperSet = $application->getHelperSet();
@@ -1163,7 +1193,7 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->setHelperSet(new HelperSet(array(new FormatterHelper())));
$application->setHelperSet(new HelperSet([new FormatterHelper()]));
$helperSet = $application->getHelperSet();
@@ -1221,7 +1251,7 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$application->setCatchExceptions(false);
$application->setDefinition(new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.'))));
$application->setDefinition(new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]));
$inputDefinition = $application->getDefinition();
@@ -1250,7 +1280,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
$tester->run(['command' => 'foo']);
$this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay());
}
@@ -1270,7 +1300,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
$tester->run(['command' => 'foo']);
}
public function testRunDispatchesAllEventsWithException()
@@ -1286,7 +1316,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
$tester->run(['command' => 'foo']);
$this->assertContains('before.foo.error.after.', $tester->getDisplay());
}
@@ -1306,7 +1336,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
$tester->run(['command' => 'foo']);
$this->assertContains('before.error.after.', $tester->getDisplay());
}
@@ -1325,7 +1355,7 @@ class ApplicationTest extends TestCase
$tester = new ApplicationTester($application);
try {
$tester->run(array('command' => 'dym'));
$tester->run(['command' => 'dym']);
$this->fail('Error expected.');
} catch (\Error $e) {
$this->assertSame('dymerr', $e->getMessage());
@@ -1354,7 +1384,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
$tester->run(['command' => 'foo']);
$this->assertContains('before.error.silenced.after.', $tester->getDisplay());
$this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode());
}
@@ -1373,7 +1403,7 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'unknown'));
$tester->run(['command' => 'unknown']);
$this->assertContains('silenced command not found', $tester->getDisplay());
$this->assertEquals(1, $tester->getStatusCode());
}
@@ -1392,7 +1422,7 @@ class ApplicationTest extends TestCase
$tester = new ApplicationTester($application);
try {
$tester->run(array('command' => 'dym'));
$tester->run(['command' => 'dym']);
$this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
} catch (\Error $e) {
$this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
@@ -1417,7 +1447,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'dym'));
$tester->run(['command' => 'dym']);
$this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
}
@@ -1434,7 +1464,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'dym'));
$tester->run(['command' => 'dym']);
$this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events');
}
@@ -1451,7 +1481,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'dus'));
$tester->run(['command' => 'dus']);
$this->assertSame(1, $tester->getStatusCode(), 'Status code should be 1');
}
@@ -1466,7 +1496,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$exitCode = $tester->run(array('command' => 'foo'));
$exitCode = $tester->run(['command' => 'foo']);
$this->assertContains('before.after.', $tester->getDisplay());
$this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode);
}
@@ -1493,7 +1523,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo', '--no-interaction' => true));
$tester->run(['command' => 'foo', '--no-interaction' => true]);
$this->assertTrue($noInteractionValue);
$this->assertFalse($quietValue);
@@ -1523,7 +1553,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo', '--extra' => 'some test value'));
$tester->run(['command' => 'foo', '--extra' => 'some test value']);
$this->assertEquals('some test value', $extraValue);
}
@@ -1538,14 +1568,14 @@ class ApplicationTest extends TestCase
$application->setDefaultCommand($command->getName());
$tester = new ApplicationTester($application);
$tester->run(array(), array('interactive' => false));
$tester->run([], ['interactive' => false]);
$this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
$application = new CustomDefaultCommandApplication();
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(array(), array('interactive' => false));
$tester->run([], ['interactive' => false]);
$this->assertEquals('called'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
}
@@ -1560,7 +1590,7 @@ class ApplicationTest extends TestCase
$application->setDefaultCommand($command->getName());
$tester = new ApplicationTester($application);
$tester->run(array('--fooopt' => 'opt'), array('interactive' => false));
$tester->run(['--fooopt' => 'opt'], ['interactive' => false]);
$this->assertEquals('called'.PHP_EOL.'opt'.PHP_EOL, $tester->getDisplay(), 'Application runs the default set command if different from \'list\' command');
}
@@ -1576,10 +1606,10 @@ class ApplicationTest extends TestCase
$tester = new ApplicationTester($application);
$tester->run(array());
$tester->run([]);
$this->assertContains('called', $tester->getDisplay());
$tester->run(array('--help' => true));
$tester->run(['--help' => true]);
$this->assertContains('The foo:bar command', $tester->getDisplay());
}
@@ -1592,9 +1622,9 @@ class ApplicationTest extends TestCase
$application->setAutoExit(false);
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'help'));
$tester->run(['command' => 'help']);
$this->assertFalse($tester->getInput()->hasParameterOption(array('--no-interaction', '-n')));
$this->assertFalse($tester->getInput()->hasParameterOption(['--no-interaction', '-n']));
$inputStream = $tester->getInput()->getStream();
$this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream));
@@ -1606,9 +1636,9 @@ class ApplicationTest extends TestCase
$container->addCompilerPass(new AddConsoleCommandPass());
$container
->register('lazy-command', LazyCommand::class)
->addTag('console.command', array('command' => 'lazy:command'))
->addTag('console.command', array('command' => 'lazy:alias'))
->addTag('console.command', array('command' => 'lazy:alias2'));
->addTag('console.command', ['command' => 'lazy:command'])
->addTag('console.command', ['command' => 'lazy:alias'])
->addTag('console.command', ['command' => 'lazy:alias2']);
$container->compile();
$application = new Application();
@@ -1617,17 +1647,17 @@ class ApplicationTest extends TestCase
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'lazy:command'));
$tester->run(['command' => 'lazy:command']);
$this->assertSame("lazy-command called\n", $tester->getDisplay(true));
$tester->run(array('command' => 'lazy:alias'));
$tester->run(['command' => 'lazy:alias']);
$this->assertSame("lazy-command called\n", $tester->getDisplay(true));
$tester->run(array('command' => 'lazy:alias2'));
$tester->run(['command' => 'lazy:alias2']);
$this->assertSame("lazy-command called\n", $tester->getDisplay(true));
$command = $application->get('lazy:command');
$this->assertSame(array('lazy:alias', 'lazy:alias2'), $command->getAliases());
$this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases());
}
/**
@@ -1636,21 +1666,21 @@ class ApplicationTest extends TestCase
public function testGetDisabledLazyCommand()
{
$application = new Application();
$application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
$application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
$application->get('disabled');
}
public function testHasReturnsFalseForDisabledLazyCommand()
{
$application = new Application();
$application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
$application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
$this->assertFalse($application->has('disabled'));
}
public function testAllExcludesDisabledLazyCommand()
{
$application = new Application();
$application->setCommandLoader(new FactoryCommandLoader(array('disabled' => function () { return new DisabledCommand(); })));
$application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }]));
$this->assertArrayNotHasKey('disabled', $application->all());
}
@@ -1693,7 +1723,7 @@ class ApplicationTest extends TestCase
$tester = new ApplicationTester($application);
try {
$tester->run(array('command' => 'dym'));
$tester->run(['command' => 'dym']);
$this->fail('->run() should rethrow PHP errors if not handled via ConsoleErrorEvent.');
} catch (\Error $e) {
$this->assertSame($e->getMessage(), 'Class \'UnknownClass\' not found');
@@ -1725,14 +1755,7 @@ class ApplicationTest extends TestCase
});
$tester = new ApplicationTester($application);
$tester->run(array('command' => 'foo'));
}
protected function tearDown()
{
putenv('SHELL_VERBOSITY');
unset($_ENV['SHELL_VERBOSITY']);
unset($_SERVER['SHELL_VERBOSITY']);
$tester->run(['command' => 'foo']);
}
}
@@ -1745,7 +1768,7 @@ class CustomApplication extends Application
*/
protected function getDefaultInputDefinition()
{
return new InputDefinition(array(new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')));
return new InputDefinition([new InputOption('--custom', '-c', InputOption::VALUE_NONE, 'Set the custom input definition.')]);
}
/**
@@ -1755,7 +1778,7 @@ class CustomApplication extends Application
*/
protected function getDefaultHelperSet()
{
return new HelperSet(array(new FormatterHelper()));
return new HelperSet([new FormatterHelper()]);
}
}

View File

@@ -71,7 +71,7 @@ class CommandTest extends TestCase
$ret = $command->setDefinition($definition = new InputDefinition());
$this->assertEquals($command, $ret, '->setDefinition() implements a fluent interface');
$this->assertEquals($definition, $command->getDefinition(), '->setDefinition() sets the current InputDefinition instance');
$command->setDefinition(array(new InputArgument('foo'), new InputOption('bar')));
$command->setDefinition([new InputArgument('foo'), new InputOption('bar')]);
$this->assertTrue($command->getDefinition()->hasArgument('foo'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
$this->assertTrue($command->getDefinition()->hasOption('bar'), '->setDefinition() also takes an array of InputArguments and InputOptions as an argument');
$command->setDefinition(new InputDefinition());
@@ -130,10 +130,10 @@ class CommandTest extends TestCase
public function provideInvalidCommandNames()
{
return array(
array(''),
array('foo:'),
);
return [
[''],
['foo:'],
];
}
public function testGetSetDescription()
@@ -179,10 +179,10 @@ class CommandTest extends TestCase
public function testGetSetAliases()
{
$command = new \TestCommand();
$this->assertEquals(array('name'), $command->getAliases(), '->getAliases() returns the aliases');
$ret = $command->setAliases(array('name1'));
$this->assertEquals(['name'], $command->getAliases(), '->getAliases() returns the aliases');
$ret = $command->setAliases(['name1']);
$this->assertEquals($command, $ret, '->setAliases() implements a fluent interface');
$this->assertEquals(array('name1'), $command->getAliases(), '->setAliases() sets the aliases');
$this->assertEquals(['name1'], $command->getAliases(), '->setAliases() sets the aliases');
}
public function testSetAliasesNull()
@@ -231,11 +231,11 @@ class CommandTest extends TestCase
public function testMergeApplicationDefinition()
{
$application1 = new Application();
$application1->getDefinition()->addArguments(array(new InputArgument('foo')));
$application1->getDefinition()->addOptions(array(new InputOption('bar')));
$application1->getDefinition()->addArguments([new InputArgument('foo')]);
$application1->getDefinition()->addOptions([new InputOption('bar')]);
$command = new \TestCommand();
$command->setApplication($application1);
$command->setDefinition($definition = new InputDefinition(array(new InputArgument('bar'), new InputOption('foo'))));
$command->setDefinition($definition = new InputDefinition([new InputArgument('bar'), new InputOption('foo')]));
$r = new \ReflectionObject($command);
$m = $r->getMethod('mergeApplicationDefinition');
@@ -253,11 +253,11 @@ class CommandTest extends TestCase
public function testMergeApplicationDefinitionWithoutArgsThenWithArgsAddsArgs()
{
$application1 = new Application();
$application1->getDefinition()->addArguments(array(new InputArgument('foo')));
$application1->getDefinition()->addOptions(array(new InputOption('bar')));
$application1->getDefinition()->addArguments([new InputArgument('foo')]);
$application1->getDefinition()->addOptions([new InputOption('bar')]);
$command = new \TestCommand();
$command->setApplication($application1);
$command->setDefinition($definition = new InputDefinition(array()));
$command->setDefinition($definition = new InputDefinition([]));
$r = new \ReflectionObject($command);
$m = $r->getMethod('mergeApplicationDefinition');
@@ -277,7 +277,7 @@ class CommandTest extends TestCase
{
$tester = new CommandTester(new \TestCommand());
$tester->execute(array(), array('interactive' => true));
$tester->execute([], ['interactive' => true]);
$this->assertEquals('interact called'.PHP_EOL.'execute called'.PHP_EOL, $tester->getDisplay(), '->run() calls the interact() method if the input is interactive');
}
@@ -286,7 +286,7 @@ class CommandTest extends TestCase
{
$tester = new CommandTester(new \TestCommand());
$tester->execute(array(), array('interactive' => false));
$tester->execute([], ['interactive' => false]);
$this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive');
}
@@ -309,7 +309,7 @@ class CommandTest extends TestCase
{
$command = new \TestCommand();
$tester = new CommandTester($command);
$tester->execute(array('--bar' => true));
$tester->execute(['--bar' => true]);
}
public function testRunReturnsIntegerExitCode()
@@ -318,7 +318,7 @@ class CommandTest extends TestCase
$exitCode = $command->run(new StringInput(''), new NullOutput());
$this->assertSame(0, $exitCode, '->run() returns integer exit code (treats null as 0)');
$command = $this->getMockBuilder('TestCommand')->setMethods(array('execute'))->getMock();
$command = $this->getMockBuilder('TestCommand')->setMethods(['execute'])->getMock();
$command->expects($this->once())
->method('execute')
->will($this->returnValue('2.3'));
@@ -364,16 +364,16 @@ class CommandTest extends TestCase
});
$this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
$tester = new CommandTester($command);
$tester->execute(array());
$tester->execute([]);
$this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
}
public function getSetCodeBindToClosureTests()
{
return array(
array(true, 'not bound to the command'),
array(false, 'bound to the command'),
);
return [
[true, 'not bound to the command'],
[false, 'bound to the command'],
];
}
/**
@@ -389,7 +389,7 @@ class CommandTest extends TestCase
$command = new \TestCommand();
$command->setCode($code);
$tester = new CommandTester($command);
$tester->execute(array());
$tester->execute([]);
$this->assertEquals('interact called'.PHP_EOL.$expected.PHP_EOL, $tester->getDisplay());
}
@@ -398,7 +398,7 @@ class CommandTest extends TestCase
$command = new \TestCommand();
$command->setCode(self::createClosure());
$tester = new CommandTester($command);
$tester->execute(array());
$tester->execute([]);
$this->assertEquals('interact called'.PHP_EOL.'bound'.PHP_EOL, $tester->getDisplay());
}
@@ -413,10 +413,10 @@ class CommandTest extends TestCase
public function testSetCodeWithNonClosureCallable()
{
$command = new \TestCommand();
$ret = $command->setCode(array($this, 'callableMethodCommand'));
$ret = $command->setCode([$this, 'callableMethodCommand']);
$this->assertEquals($command, $ret, '->setCode() implements a fluent interface');
$tester = new CommandTester($command);
$tester->execute(array());
$tester->execute([]);
$this->assertEquals('interact called'.PHP_EOL.'from the code...'.PHP_EOL, $tester->getDisplay());
}

View File

@@ -24,7 +24,7 @@ class HelpCommandTest extends TestCase
$command = new HelpCommand();
$command->setApplication(new Application());
$commandTester = new CommandTester($command);
$commandTester->execute(array('command_name' => 'li'), array('decorated' => false));
$commandTester->execute(['command_name' => 'li'], ['decorated' => false]);
$this->assertContains('list [options] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias');
$this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias');
$this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias');
@@ -35,7 +35,7 @@ class HelpCommandTest extends TestCase
$command = new HelpCommand();
$commandTester = new CommandTester($command);
$command->setCommand(new ListCommand());
$commandTester->execute(array(), array('decorated' => false));
$commandTester->execute([], ['decorated' => false]);
$this->assertContains('list [options] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
$this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
$this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
@@ -46,7 +46,7 @@ class HelpCommandTest extends TestCase
$command = new HelpCommand();
$commandTester = new CommandTester($command);
$command->setCommand(new ListCommand());
$commandTester->execute(array('--format' => 'xml'));
$commandTester->execute(['--format' => 'xml']);
$this->assertContains('<command', $commandTester->getDisplay(), '->execute() returns an XML help text if --xml is passed');
}
@@ -54,7 +54,7 @@ class HelpCommandTest extends TestCase
{
$application = new Application();
$commandTester = new CommandTester($application->get('help'));
$commandTester->execute(array('command_name' => 'list'));
$commandTester->execute(['command_name' => 'list']);
$this->assertContains('list [options] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
$this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
$this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
@@ -64,7 +64,7 @@ class HelpCommandTest extends TestCase
{
$application = new Application();
$commandTester = new CommandTester($application->get('help'));
$commandTester->execute(array('command_name' => 'list', '--format' => 'xml'));
$commandTester->execute(['command_name' => 'list', '--format' => 'xml']);
$this->assertContains('list [--raw] [--format FORMAT] [--] [&lt;namespace&gt;]', $commandTester->getDisplay(), '->execute() returns a text help for the given command');
$this->assertContains('<command', $commandTester->getDisplay(), '->execute() returns an XML help text if --format=xml is passed');
}

View File

@@ -21,7 +21,7 @@ class ListCommandTest extends TestCase
{
$application = new Application();
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName()), array('decorated' => false));
$commandTester->execute(['command' => $command->getName()], ['decorated' => false]);
$this->assertRegExp('/help\s{2,}Displays help for a command/', $commandTester->getDisplay(), '->execute() returns a list of available commands');
}
@@ -30,7 +30,7 @@ class ListCommandTest extends TestCase
{
$application = new Application();
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName(), '--format' => 'xml'));
$commandTester->execute(['command' => $command->getName(), '--format' => 'xml']);
$this->assertRegExp('/<command id="list" name="list" hidden="0">/', $commandTester->getDisplay(), '->execute() returns a list of available commands in XML if --xml is passed');
}
@@ -38,7 +38,7 @@ class ListCommandTest extends TestCase
{
$application = new Application();
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName(), '--raw' => true));
$commandTester->execute(['command' => $command->getName(), '--raw' => true]);
$output = <<<'EOF'
help Displays help for a command
list Lists commands
@@ -54,7 +54,7 @@ EOF;
$application = new Application();
$application->add(new \FooCommand());
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName(), 'namespace' => 'foo', '--raw' => true));
$commandTester->execute(['command' => $command->getName(), 'namespace' => 'foo', '--raw' => true]);
$output = <<<'EOF'
foo:bar The foo:bar command
@@ -69,7 +69,7 @@ EOF;
$application = new Application();
$application->add(new \Foo6Command());
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName()), array('decorated' => false));
$commandTester->execute(['command' => $command->getName()], ['decorated' => false]);
$output = <<<'EOF'
Console Tool
@@ -101,7 +101,7 @@ EOF;
$application = new Application();
$application->add(new \Foo6Command());
$commandTester = new CommandTester($command = $application->get('list'));
$commandTester->execute(array('command' => $command->getName(), '--raw' => true));
$commandTester->execute(['command' => $command->getName(), '--raw' => true]);
$output = <<<'EOF'
help Displays help for a command
list Lists commands

View File

@@ -33,8 +33,8 @@ class LockableTraitTest extends TestCase
$command = new \FooLockCommand();
$tester = new CommandTester($command);
$this->assertSame(2, $tester->execute(array()));
$this->assertSame(2, $tester->execute(array()));
$this->assertSame(2, $tester->execute([]));
$this->assertSame(2, $tester->execute([]));
}
public function testLockReturnsFalseIfAlreadyLockedByAnotherCommand()
@@ -51,10 +51,10 @@ class LockableTraitTest extends TestCase
$lock->acquire();
$tester = new CommandTester($command);
$this->assertSame(1, $tester->execute(array()));
$this->assertSame(1, $tester->execute([]));
$lock->release();
$this->assertSame(2, $tester->execute(array()));
$this->assertSame(2, $tester->execute([]));
}
public function testMultipleLockCallsThrowLogicException()
@@ -62,6 +62,6 @@ class LockableTraitTest extends TestCase
$command = new \FooLock2Command();
$tester = new CommandTester($command);
$this->assertSame(1, $tester->execute(array()));
$this->assertSame(1, $tester->execute([]));
}
}

View File

@@ -20,10 +20,10 @@ class ContainerCommandLoaderTest extends TestCase
{
public function testHas()
{
$loader = new ContainerCommandLoader(new ServiceLocator(array(
$loader = new ContainerCommandLoader(new ServiceLocator([
'foo-service' => function () { return new Command('foo'); },
'bar-service' => function () { return new Command('bar'); },
)), array('foo' => 'foo-service', 'bar' => 'bar-service'));
]), ['foo' => 'foo-service', 'bar' => 'bar-service']);
$this->assertTrue($loader->has('foo'));
$this->assertTrue($loader->has('bar'));
@@ -32,10 +32,10 @@ class ContainerCommandLoaderTest extends TestCase
public function testGet()
{
$loader = new ContainerCommandLoader(new ServiceLocator(array(
$loader = new ContainerCommandLoader(new ServiceLocator([
'foo-service' => function () { return new Command('foo'); },
'bar-service' => function () { return new Command('bar'); },
)), array('foo' => 'foo-service', 'bar' => 'bar-service'));
]), ['foo' => 'foo-service', 'bar' => 'bar-service']);
$this->assertInstanceOf(Command::class, $loader->get('foo'));
$this->assertInstanceOf(Command::class, $loader->get('bar'));
@@ -46,16 +46,16 @@ class ContainerCommandLoaderTest extends TestCase
*/
public function testGetUnknownCommandThrows()
{
(new ContainerCommandLoader(new ServiceLocator(array()), array()))->get('unknown');
(new ContainerCommandLoader(new ServiceLocator([]), []))->get('unknown');
}
public function testGetCommandNames()
{
$loader = new ContainerCommandLoader(new ServiceLocator(array(
$loader = new ContainerCommandLoader(new ServiceLocator([
'foo-service' => function () { return new Command('foo'); },
'bar-service' => function () { return new Command('bar'); },
)), array('foo' => 'foo-service', 'bar' => 'bar-service'));
]), ['foo' => 'foo-service', 'bar' => 'bar-service']);
$this->assertSame(array('foo', 'bar'), $loader->getNames());
$this->assertSame(['foo', 'bar'], $loader->getNames());
}
}

View File

@@ -19,10 +19,10 @@ class FactoryCommandLoaderTest extends TestCase
{
public function testHas()
{
$loader = new FactoryCommandLoader(array(
$loader = new FactoryCommandLoader([
'foo' => function () { return new Command('foo'); },
'bar' => function () { return new Command('bar'); },
));
]);
$this->assertTrue($loader->has('foo'));
$this->assertTrue($loader->has('bar'));
@@ -31,10 +31,10 @@ class FactoryCommandLoaderTest extends TestCase
public function testGet()
{
$loader = new FactoryCommandLoader(array(
$loader = new FactoryCommandLoader([
'foo' => function () { return new Command('foo'); },
'bar' => function () { return new Command('bar'); },
));
]);
$this->assertInstanceOf(Command::class, $loader->get('foo'));
$this->assertInstanceOf(Command::class, $loader->get('bar'));
@@ -45,16 +45,16 @@ class FactoryCommandLoaderTest extends TestCase
*/
public function testGetUnknownCommandThrows()
{
(new FactoryCommandLoader(array()))->get('unknown');
(new FactoryCommandLoader([]))->get('unknown');
}
public function testGetCommandNames()
{
$loader = new FactoryCommandLoader(array(
$loader = new FactoryCommandLoader([
'foo' => function () { return new Command('foo'); },
'bar' => function () { return new Command('bar'); },
));
]);
$this->assertSame(array('foo', 'bar'), $loader->getNames());
$this->assertSame(['foo', 'bar'], $loader->getNames());
}
}

View File

@@ -53,7 +53,7 @@ class AddConsoleCommandPassTest extends TestCase
}
$this->assertTrue($container->hasParameter('console.command.ids'));
$this->assertSame(array($public ? $id : $alias), $container->getParameter('console.command.ids'));
$this->assertSame([$public ? $id : $alias], $container->getParameter('console.command.ids'));
}
public function testProcessRegistersLazyCommands()
@@ -62,8 +62,8 @@ class AddConsoleCommandPassTest extends TestCase
$command = $container
->register('my-command', MyCommand::class)
->setPublic(false)
->addTag('console.command', array('command' => 'my:command'))
->addTag('console.command', array('command' => 'my:alias'))
->addTag('console.command', ['command' => 'my:command'])
->addTag('console.command', ['command' => 'my:alias'])
;
(new AddConsoleCommandPass())->process($container);
@@ -72,10 +72,10 @@ class AddConsoleCommandPassTest extends TestCase
$commandLocator = $container->getDefinition((string) $commandLoader->getArgument(0));
$this->assertSame(ContainerCommandLoader::class, $commandLoader->getClass());
$this->assertSame(array('my:command' => 'my-command', 'my:alias' => 'my-command'), $commandLoader->getArgument(1));
$this->assertEquals(array(array('my-command' => new ServiceClosureArgument(new TypedReference('my-command', MyCommand::class)))), $commandLocator->getArguments());
$this->assertSame(array(), $container->getParameter('console.command.ids'));
$this->assertSame(array(array('setName', array('my:command')), array('setAliases', array(array('my:alias')))), $command->getMethodCalls());
$this->assertSame(['my:command' => 'my-command', 'my:alias' => 'my-command'], $commandLoader->getArgument(1));
$this->assertEquals([['my-command' => new ServiceClosureArgument(new TypedReference('my-command', MyCommand::class))]], $commandLocator->getArguments());
$this->assertSame([], $container->getParameter('console.command.ids'));
$this->assertSame([['setName', ['my:command']], ['setAliases', [['my:alias']]]], $command->getMethodCalls());
}
public function testProcessFallsBackToDefaultName()
@@ -94,28 +94,28 @@ class AddConsoleCommandPassTest extends TestCase
$commandLocator = $container->getDefinition((string) $commandLoader->getArgument(0));
$this->assertSame(ContainerCommandLoader::class, $commandLoader->getClass());
$this->assertSame(array('default' => 'with-default-name'), $commandLoader->getArgument(1));
$this->assertEquals(array(array('with-default-name' => new ServiceClosureArgument(new TypedReference('with-default-name', NamedCommand::class)))), $commandLocator->getArguments());
$this->assertSame(array(), $container->getParameter('console.command.ids'));
$this->assertSame(['default' => 'with-default-name'], $commandLoader->getArgument(1));
$this->assertEquals([['with-default-name' => new ServiceClosureArgument(new TypedReference('with-default-name', NamedCommand::class))]], $commandLocator->getArguments());
$this->assertSame([], $container->getParameter('console.command.ids'));
$container = new ContainerBuilder();
$container
->register('with-default-name', NamedCommand::class)
->setPublic(false)
->addTag('console.command', array('command' => 'new-name'))
->addTag('console.command', ['command' => 'new-name'])
;
$pass->process($container);
$this->assertSame(array('new-name' => 'with-default-name'), $container->getDefinition('console.command_loader')->getArgument(1));
$this->assertSame(['new-name' => 'with-default-name'], $container->getDefinition('console.command_loader')->getArgument(1));
}
public function visibilityProvider()
{
return array(
array(true),
array(false),
);
return [
[true],
[false],
];
}
/**

View File

@@ -89,19 +89,19 @@ abstract class AbstractDescriptorTest extends TestCase
protected function getDescriptionTestData(array $objects)
{
$data = array();
$data = [];
foreach ($objects as $name => $object) {
$description = file_get_contents(sprintf('%s/../Fixtures/%s.%s', __DIR__, $name, $this->getFormat()));
$data[] = array($object, $description);
$data[] = [$object, $description];
}
return $data;
}
protected function assertDescription($expectedDescription, $describedObject, array $options = array())
protected function assertDescription($expectedDescription, $describedObject, array $options = [])
{
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
$this->getDescriptor()->describe($output, $describedObject, $options + array('raw_output' => true));
$this->getDescriptor()->describe($output, $describedObject, $options + ['raw_output' => true]);
$this->assertEquals(trim($expectedDescription), trim(str_replace(PHP_EOL, "\n", $output->fetch())));
}
}

View File

@@ -26,10 +26,10 @@ class JsonDescriptorTest extends AbstractDescriptorTest
return 'json';
}
protected function assertDescription($expectedDescription, $describedObject, array $options = array())
protected function assertDescription($expectedDescription, $describedObject, array $options = [])
{
$output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
$this->getDescriptor()->describe($output, $describedObject, $options + array('raw_output' => true));
$this->getDescriptor()->describe($output, $describedObject, $options + ['raw_output' => true]);
$this->assertEquals(json_decode(trim($expectedDescription), true), json_decode(trim(str_replace(PHP_EOL, "\n", $output->fetch())), true));
}
}

View File

@@ -21,7 +21,7 @@ class MarkdownDescriptorTest extends AbstractDescriptorTest
{
return $this->getDescriptionTestData(array_merge(
ObjectsProvider::getCommands(),
array('command_mbstring' => new DescriptorCommandMbString())
['command_mbstring' => new DescriptorCommandMbString()]
));
}
@@ -29,7 +29,7 @@ class MarkdownDescriptorTest extends AbstractDescriptorTest
{
return $this->getDescriptionTestData(array_merge(
ObjectsProvider::getApplications(),
array('application_mbstring' => new DescriptorApplicationMbString())
['application_mbstring' => new DescriptorApplicationMbString()]
));
}

View File

@@ -26,57 +26,57 @@ class ObjectsProvider
{
public static function getInputArguments()
{
return array(
return [
'input_argument_1' => new InputArgument('argument_name', InputArgument::REQUIRED),
'input_argument_2' => new InputArgument('argument_name', InputArgument::IS_ARRAY, 'argument description'),
'input_argument_3' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', 'default_value'),
'input_argument_4' => new InputArgument('argument_name', InputArgument::REQUIRED, "multiline\nargument description"),
'input_argument_with_style' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', '<comment>style</>'),
'input_argument_with_default_inf_value' => new InputArgument('argument_name', InputArgument::OPTIONAL, 'argument description', INF),
);
];
}
public static function getInputOptions()
{
return array(
return [
'input_option_1' => new InputOption('option_name', 'o', InputOption::VALUE_NONE),
'input_option_2' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', 'default_value'),
'input_option_3' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, 'option description'),
'input_option_4' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 'option description', array()),
'input_option_4' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL, 'option description', []),
'input_option_5' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, "multiline\noption description"),
'input_option_6' => new InputOption('option_name', array('o', 'O'), InputOption::VALUE_REQUIRED, 'option with multiple shortcuts'),
'input_option_6' => new InputOption('option_name', ['o', 'O'], InputOption::VALUE_REQUIRED, 'option with multiple shortcuts'),
'input_option_with_style' => new InputOption('option_name', 'o', InputOption::VALUE_REQUIRED, 'option description', '<comment>style</>'),
'input_option_with_style_array' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'option description', array('<comment>Hello</comment>', '<info>world</info>')),
'input_option_with_style_array' => new InputOption('option_name', 'o', InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'option description', ['<comment>Hello</comment>', '<info>world</info>']),
'input_option_with_default_inf_value' => new InputOption('option_name', 'o', InputOption::VALUE_OPTIONAL, 'option description', INF),
);
];
}
public static function getInputDefinitions()
{
return array(
return [
'input_definition_1' => new InputDefinition(),
'input_definition_2' => new InputDefinition(array(new InputArgument('argument_name', InputArgument::REQUIRED))),
'input_definition_3' => new InputDefinition(array(new InputOption('option_name', 'o', InputOption::VALUE_NONE))),
'input_definition_4' => new InputDefinition(array(
'input_definition_2' => new InputDefinition([new InputArgument('argument_name', InputArgument::REQUIRED)]),
'input_definition_3' => new InputDefinition([new InputOption('option_name', 'o', InputOption::VALUE_NONE)]),
'input_definition_4' => new InputDefinition([
new InputArgument('argument_name', InputArgument::REQUIRED),
new InputOption('option_name', 'o', InputOption::VALUE_NONE),
)),
);
]),
];
}
public static function getCommands()
{
return array(
return [
'command_1' => new DescriptorCommand1(),
'command_2' => new DescriptorCommand2(),
);
];
}
public static function getApplications()
{
return array(
return [
'application_1' => new DescriptorApplication1(),
'application_2' => new DescriptorApplication2(),
);
];
}
}

View File

@@ -22,7 +22,7 @@ class TextDescriptorTest extends AbstractDescriptorTest
{
return $this->getDescriptionTestData(array_merge(
ObjectsProvider::getCommands(),
array('command_mbstring' => new DescriptorCommandMbString())
['command_mbstring' => new DescriptorCommandMbString()]
));
}
@@ -30,7 +30,7 @@ class TextDescriptorTest extends AbstractDescriptorTest
{
return $this->getDescriptionTestData(array_merge(
ObjectsProvider::getApplications(),
array('application_mbstring' => new DescriptorApplicationMbString())
['application_mbstring' => new DescriptorApplicationMbString()]
));
}
@@ -38,7 +38,7 @@ class TextDescriptorTest extends AbstractDescriptorTest
{
$application = new DescriptorApplication2();
$this->assertDescription(file_get_contents(__DIR__.'/../Fixtures/application_filtered_namespace.txt'), $application, array('namespace' => 'command4'));
$this->assertDescription(file_get_contents(__DIR__.'/../Fixtures/application_filtered_namespace.txt'), $application, ['namespace' => 'command4']);
}
protected function getDescriptor()

View File

@@ -34,11 +34,11 @@ class ErrorListenerTest extends TestCase
$logger
->expects($this->once())
->method('error')
->with('Error thrown while running command "{command}". Message: "{message}"', array('exception' => $error, 'command' => 'test:run --foo=baz buzz', 'message' => 'An error occurred'))
->with('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => 'test:run --foo=baz buzz', 'message' => 'An error occurred'])
;
$listener = new ErrorListener($logger);
$listener->onConsoleError(new ConsoleErrorEvent(new ArgvInput(array('console.php', 'test:run', '--foo=baz', 'buzz')), $this->getOutput(), $error, new Command('test:run')));
$listener->onConsoleError(new ConsoleErrorEvent(new ArgvInput(['console.php', 'test:run', '--foo=baz', 'buzz']), $this->getOutput(), $error, new Command('test:run')));
}
public function testOnConsoleErrorWithNoCommandAndNoInputString()
@@ -49,7 +49,7 @@ class ErrorListenerTest extends TestCase
$logger
->expects($this->once())
->method('error')
->with('An error occurred while using the console. Message: "{message}"', array('exception' => $error, 'message' => 'An error occurred'))
->with('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => 'An error occurred'])
;
$listener = new ErrorListener($logger);
@@ -62,11 +62,11 @@ class ErrorListenerTest extends TestCase
$logger
->expects($this->once())
->method('debug')
->with('Command "{command}" exited with code "{code}"', array('command' => 'test:run', 'code' => 255))
->with('Command "{command}" exited with code "{code}"', ['command' => 'test:run', 'code' => 255])
;
$listener = new ErrorListener($logger);
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(array('console.php', 'test:run')), 255));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(['console.php', 'test:run']), 255));
}
public function testOnConsoleTerminateForZeroExitCodeDoesNotWriteToLog()
@@ -78,16 +78,16 @@ class ErrorListenerTest extends TestCase
;
$listener = new ErrorListener($logger);
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(array('console.php', 'test:run')), 0));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(['console.php', 'test:run']), 0));
}
public function testGetSubscribedEvents()
{
$this->assertEquals(
array(
'console.error' => array('onConsoleError', -128),
'console.terminate' => array('onConsoleTerminate', -128),
),
[
'console.error' => ['onConsoleError', -128],
'console.terminate' => ['onConsoleTerminate', -128],
],
ErrorListener::getSubscribedEvents()
);
}
@@ -98,12 +98,12 @@ class ErrorListenerTest extends TestCase
$logger
->expects($this->exactly(3))
->method('debug')
->with('Command "{command}" exited with code "{code}"', array('command' => 'test:run --foo=bar', 'code' => 255))
->with('Command "{command}" exited with code "{code}"', ['command' => 'test:run --foo=bar', 'code' => 255])
;
$listener = new ErrorListener($logger);
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(array('console.php', 'test:run', '--foo=bar')), 255));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArrayInput(array('name' => 'test:run', '--foo' => 'bar')), 255));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArgvInput(['console.php', 'test:run', '--foo=bar']), 255));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new ArrayInput(['name' => 'test:run', '--foo' => 'bar']), 255));
$listener->onConsoleTerminate($this->getConsoleTerminateEvent(new StringInput('test:run --foo=bar'), 255));
}
@@ -113,7 +113,7 @@ class ErrorListenerTest extends TestCase
$logger
->expects($this->once())
->method('debug')
->with('Command "{command}" exited with code "{code}"', array('command' => 'test:run', 'code' => 255))
->with('Command "{command}" exited with code "{code}"', ['command' => 'test:run', 'code' => 255])
;
$listener = new ErrorListener($logger);

View File

@@ -19,7 +19,7 @@ class DescriptorCommand1 extends Command
{
$this
->setName('descriptor:command1')
->setAliases(array('alias1', 'alias2'))
->setAliases(['alias1', 'alias2'])
->setDescription('command 1 description')
->setHelp('command 1 help')
;

View File

@@ -19,7 +19,7 @@ class DescriptorCommand4 extends Command
{
$this
->setName('descriptor:command4')
->setAliases(array('descriptor:alias_command4', 'command4:descriptor'))
->setAliases(['descriptor:alias_command4', 'command4:descriptor'])
;
}
}

View File

@@ -25,7 +25,7 @@ class DummyOutput extends BufferedOutput
*/
public function getLogs()
{
$logs = array();
$logs = [];
foreach (explode(PHP_EOL, trim($this->fetch())) as $message) {
preg_match('/^\[(.*)\] (.*)/', $message, $matches);
$logs[] = sprintf('%s %s', $matches[1], $matches[2]);

View File

@@ -14,7 +14,7 @@ class Foo1Command extends Command
$this
->setName('foo:bar1')
->setDescription('The foo:bar1 command')
->setAliases(array('afoobar1'))
->setAliases(['afoobar1'])
;
}

View File

@@ -11,7 +11,7 @@ class Foo2Command extends Command
$this
->setName('foo1:bar')
->setDescription('The foo1:bar command')
->setAliases(array('afoobar2'))
->setAliases(['afoobar2'])
;
}

View File

@@ -14,7 +14,7 @@ class FooCommand extends Command
$this
->setName('foo:bar')
->setDescription('The foo:bar command')
->setAliases(array('afoobar'))
->setAliases(['afoobar'])
;
}

View File

@@ -15,7 +15,7 @@ class FooOptCommand extends Command
$this
->setName('foo:bar')
->setDescription('The foo:bar command')
->setAliases(array('afoobar'))
->setAliases(['afoobar'])
->addOption('fooopt', 'fo', InputOption::VALUE_OPTIONAL, 'fooopt description')
;
}

View File

@@ -14,7 +14,7 @@ class FooSubnamespaced1Command extends Command
$this
->setName('foo:bar:baz')
->setDescription('The foo:bar:baz command')
->setAliases(array('foobarbaz'))
->setAliases(['foobarbaz'])
;
}

View File

@@ -14,7 +14,7 @@ class FooSubnamespaced2Command extends Command
$this
->setName('foo:go:bret')
->setDescription('The foo:bar:go command')
->setAliases(array('foobargo'))
->setAliases(['foobargo'])
;
}

View File

@@ -20,12 +20,12 @@ return function (InputInterface $input, OutputInterface $output) {
//Ensure edge case by appending empty strings to history:
$output->write('Lorem ipsum dolor sit amet');
$output->write(array('', '', ''));
$output->write(['', '', '']);
$output->title('Fourth title');
//Ensure have manual control over number of blank lines:
$output->writeln('Lorem ipsum dolor sit amet');
$output->writeln(array('', '')); //Should append an extra blank line
$output->writeln(['', '']); //Should append an extra blank line
$output->title('Fifth title');
$output->writeln('Lorem ipsum dolor sit amet');

View File

@@ -20,12 +20,12 @@ return function (InputInterface $input, OutputInterface $output) {
//Ensure edge case by appending empty strings to history:
$output->write('Lorem ipsum dolor sit amet');
$output->write(new \ArrayIterator(array('', '', '')));
$output->write(new \ArrayIterator(['', '', '']));
$output->title('Fourth title');
//Ensure have manual control over number of blank lines:
$output->writeln('Lorem ipsum dolor sit amet');
$output->writeln(new \ArrayIterator(array('', ''))); //Should append an extra blank line
$output->writeln(new \ArrayIterator(['', ''])); //Should append an extra blank line
$output->title('Fifth title');
$output->writeln('Lorem ipsum dolor sit amet');

View File

@@ -9,29 +9,29 @@ return function (InputInterface $input, OutputInterface $output) {
$output = new SymfonyStyle($input, $output);
$output->writeln('Lorem ipsum dolor sit amet');
$output->listing(array(
$output->listing([
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
));
]);
//Even using write:
$output->write('Lorem ipsum dolor sit amet');
$output->listing(array(
$output->listing([
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
));
]);
$output->write('Lorem ipsum dolor sit amet');
$output->text(array(
$output->text([
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
));
]);
$output->newLine();
$output->write('Lorem ipsum dolor sit amet');
$output->comment(array(
$output->comment([
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
));
]);
};

View File

@@ -8,9 +8,9 @@ use Symfony\Component\Console\Style\SymfonyStyle;
return function (InputInterface $input, OutputInterface $output) {
$output = new SymfonyStyle($input, $output);
$output->listing(array(
$output->listing([
'Lorem ipsum dolor sit amet',
'consectetur adipiscing elit',
));
]);
$output->success('Lorem ipsum dolor sit amet');
};

View File

@@ -9,7 +9,7 @@ return function (InputInterface $input, OutputInterface $output) {
$output = new SymfonyStyle($input, $output);
$output->title('Title');
$output->askHidden('Hidden question');
$output->choice('Choice question with default', array('choice1', 'choice2'), 'choice1');
$output->choice('Choice question with default', ['choice1', 'choice2'], 'choice1');
$output->confirm('Confirmation with yes default', true);
$output->text('Duis aute irure dolor in reprehenderit in voluptate velit esse');
};

View File

@@ -7,19 +7,19 @@ use Symfony\Component\Console\Style\SymfonyStyle;
//Ensure formatting tables when using multiple headers with TableCell
return function (InputInterface $input, OutputInterface $output) {
$headers = array(
array(new TableCell('Main table title', array('colspan' => 3))),
array('ISBN', 'Title', 'Author'),
);
$headers = [
[new TableCell('Main table title', ['colspan' => 3])],
['ISBN', 'Title', 'Author'],
];
$rows = array(
array(
$rows = [
[
'978-0521567817',
'De Monarchia',
new TableCell("Dante Alighieri\nspans multiple rows", array('rowspan' => 2)),
),
array('978-0804169127', 'Divine Comedy'),
);
new TableCell("Dante Alighieri\nspans multiple rows", ['rowspan' => 2]),
],
['978-0804169127', 'Divine Comedy'],
];
$output = new SymfonyStyle($input, $output);
$output->table($headers, $rows);

View File

@@ -7,5 +7,5 @@ use Symfony\Component\Console\Style\SymfonyStyle;
//Ensure that all lines are aligned to the begin of the first line in a multi-line block
return function (InputInterface $input, OutputInterface $output) {
$output = new SymfonyStyle($input, $output);
$output->block(array('Custom block', 'Second custom block line'), 'CUSTOM', 'fg=white;bg=green', 'X ', true);
$output->block(['Custom block', 'Second custom block line'], 'CUSTOM', 'fg=white;bg=green', 'X ', true);
};

View File

@@ -10,7 +10,7 @@ class TestCommand extends Command
{
$this
->setName('namespace:name')
->setAliases(array('name'))
->setAliases(['name'])
->setDescription('description')
->setHelp('help')
;

View File

@@ -11,7 +11,7 @@ class TestToto extends Command
$this
->setName('test-toto')
->setDescription('The test-toto command')
->setAliases(array('test'))
->setAliases(['test'])
;
}

View File

@@ -18,10 +18,10 @@ class OutputFormatterStyleTest extends TestCase
{
public function testConstructor()
{
$style = new OutputFormatterStyle('green', 'black', array('bold', 'underscore'));
$style = new OutputFormatterStyle('green', 'black', ['bold', 'underscore']);
$this->assertEquals("\033[32;40;1;4mfoo\033[39;49;22;24m", $style->apply('foo'));
$style = new OutputFormatterStyle('red', null, array('blink'));
$style = new OutputFormatterStyle('red', null, ['blink']);
$this->assertEquals("\033[31;5mfoo\033[39;25m", $style->apply('foo'));
$style = new OutputFormatterStyle(null, 'white');
@@ -66,7 +66,7 @@ class OutputFormatterStyleTest extends TestCase
{
$style = new OutputFormatterStyle();
$style->setOptions(array('reverse', 'conceal'));
$style->setOptions(['reverse', 'conceal']);
$this->assertEquals("\033[7;8mfoo\033[27;28m", $style->apply('foo'));
$style->setOption('bold');
@@ -78,7 +78,7 @@ class OutputFormatterStyleTest extends TestCase
$style->setOption('bold');
$this->assertEquals("\033[8;1mfoo\033[28;22m", $style->apply('foo'));
$style->setOptions(array('bold'));
$style->setOptions(['bold']);
$this->assertEquals("\033[1mfoo\033[22m", $style->apply('foo'));
try {

View File

@@ -184,26 +184,26 @@ class OutputFormatterTest extends TestCase
public function provideInlineStyleOptionsCases()
{
return array(
array('<unknown=_unknown_>'),
array('<unknown=_unknown_;a=1;b>'),
array('<fg=green;>', "\033[32m[test]\033[39m", '[test]'),
array('<fg=green;bg=blue;>', "\033[32;44ma\033[39;49m", 'a'),
array('<fg=green;options=bold>', "\033[32;1mb\033[39;22m", 'b'),
array('<fg=green;options=reverse;>', "\033[32;7m<a>\033[39;27m", '<a>'),
array('<fg=green;options=bold,underscore>', "\033[32;1;4mz\033[39;22;24m", 'z'),
array('<fg=green;options=bold,underscore,reverse;>', "\033[32;1;4;7md\033[39;22;24;27m", 'd'),
);
return [
['<unknown=_unknown_>'],
['<unknown=_unknown_;a=1;b>'],
['<fg=green;>', "\033[32m[test]\033[39m", '[test]'],
['<fg=green;bg=blue;>', "\033[32;44ma\033[39;49m", 'a'],
['<fg=green;options=bold>', "\033[32;1mb\033[39;22m", 'b'],
['<fg=green;options=reverse;>', "\033[32;7m<a>\033[39;27m", '<a>'],
['<fg=green;options=bold,underscore>', "\033[32;1;4mz\033[39;22;24m", 'z'],
['<fg=green;options=bold,underscore,reverse;>', "\033[32;1;4;7md\033[39;22;24;27m", 'd'],
];
}
public function provideInlineStyleTagsWithUnknownOptions()
{
return array(
array('<options=abc;>', 'abc'),
array('<options=abc,def;>', 'abc'),
array('<fg=green;options=xyz;>', 'xyz'),
array('<fg=green;options=efg,abc>', 'efg'),
);
return [
['<options=abc;>', 'abc'],
['<options=abc,def;>', 'abc'],
['<fg=green;options=xyz;>', 'xyz'],
['<fg=green;options=efg,abc>', 'efg'],
];
}
public function testNonStyleTag()
@@ -332,6 +332,9 @@ EOF
$this->assertSame("pre\e[37;41m\e[39;49m\n\e[37;41mfoo\e[39;49m\n\e[37;41mbar\e[39;49m\n\e[37;41mbaz\e[39;49m\npos\nt", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 3));
$this->assertSame("pre \e[37;41m\e[39;49m\n\e[37;41mfoo \e[39;49m\n\e[37;41mbar \e[39;49m\n\e[37;41mbaz\e[39;49m \npost", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 4));
$this->assertSame("pre \e[37;41mf\e[39;49m\n\e[37;41moo ba\e[39;49m\n\e[37;41mr baz\e[39;49m\npost", $formatter->formatAndWrap('pre <error>foo bar baz</error> post', 5));
$this->assertSame("Lore\nm \e[37;41mip\e[39;49m\n\e[37;41msum\e[39;49m \ndolo\nr \e[32msi\e[39m\n\e[32mt\e[39m am\net", $formatter->formatAndWrap('Lorem <error>ipsum</error> dolor <info>sit</info> amet', 4));
$this->assertSame("Lorem \e[37;41mip\e[39;49m\n\e[37;41msum\e[39;49m dolo\nr \e[32msit\e[39m am\net", $formatter->formatAndWrap('Lorem <error>ipsum</error> dolor <info>sit</info> amet', 8));
$this->assertSame("Lorem \e[37;41mipsum\e[39;49m dolor \e[32m\e[39m\n\e[32msit\e[39m, \e[37;41mamet\e[39;49m et \e[32mlauda\e[39m\n\e[32mntium\e[39m architecto", $formatter->formatAndWrap('Lorem <error>ipsum</error> dolor <info>sit</info>, <error>amet</error> et <info>laudantium</info> architecto', 18));
$formatter = new OutputFormatter();

View File

@@ -40,7 +40,7 @@ class FormatterHelperTest extends TestCase
$this->assertEquals(
'<error> Some text to display </error>'."\n".
'<error> foo bar </error>',
$formatter->formatBlock(array('Some text to display', 'foo bar'), 'error'),
$formatter->formatBlock(['Some text to display', 'foo bar'], 'error'),
'::formatBlock() formats a message in a block'
);

View File

@@ -20,7 +20,7 @@ class HelperSetTest extends TestCase
public function testConstructor()
{
$mock_helper = $this->getGenericMockHelper('fake_helper');
$helperset = new HelperSet(array('fake_helper_alias' => $mock_helper));
$helperset = new HelperSet(['fake_helper_alias' => $mock_helper]);
$this->assertEquals($mock_helper, $helperset->get('fake_helper_alias'), '__construct sets given helper to helpers');
$this->assertTrue($helperset->has('fake_helper_alias'), '__construct sets helper alias for given helper');
@@ -46,7 +46,7 @@ class HelperSetTest extends TestCase
public function testHas()
{
$helperset = new HelperSet(array('fake_helper_alias' => $this->getGenericMockHelper('fake_helper')));
$helperset = new HelperSet(['fake_helper_alias' => $this->getGenericMockHelper('fake_helper')]);
$this->assertTrue($helperset->has('fake_helper'), '->has() finds set helper');
$this->assertTrue($helperset->has('fake_helper_alias'), '->has() finds set helper by alias');
}
@@ -55,7 +55,7 @@ class HelperSetTest extends TestCase
{
$helper_01 = $this->getGenericMockHelper('fake_helper_01');
$helper_02 = $this->getGenericMockHelper('fake_helper_02');
$helperset = new HelperSet(array('fake_helper_01_alias' => $helper_01, 'fake_helper_02_alias' => $helper_02));
$helperset = new HelperSet(['fake_helper_01_alias' => $helper_01, 'fake_helper_02_alias' => $helper_02]);
$this->assertEquals($helper_01, $helperset->get('fake_helper_01'), '->get() returns correct helper by name');
$this->assertEquals($helper_01, $helperset->get('fake_helper_01_alias'), '->get() returns correct helper by alias');
$this->assertEquals($helper_02, $helperset->get('fake_helper_02'), '->get() returns correct helper by name');
@@ -101,7 +101,7 @@ class HelperSetTest extends TestCase
$helperset->set($this->getGenericMockHelper('fake_helper_01', $helperset));
$helperset->set($this->getGenericMockHelper('fake_helper_02', $helperset));
$helpers = array('fake_helper_01', 'fake_helper_02');
$helpers = ['fake_helper_01', 'fake_helper_02'];
$i = 0;
foreach ($helperset as $helper) {

View File

@@ -18,28 +18,28 @@ class HelperTest extends TestCase
{
public function formatTimeProvider()
{
return array(
array(0, '< 1 sec'),
array(1, '1 sec'),
array(2, '2 secs'),
array(59, '59 secs'),
array(60, '1 min'),
array(61, '1 min'),
array(119, '1 min'),
array(120, '2 mins'),
array(121, '2 mins'),
array(3599, '59 mins'),
array(3600, '1 hr'),
array(7199, '1 hr'),
array(7200, '2 hrs'),
array(7201, '2 hrs'),
array(86399, '23 hrs'),
array(86400, '1 day'),
array(86401, '1 day'),
array(172799, '1 day'),
array(172800, '2 days'),
array(172801, '2 days'),
);
return [
[0, '< 1 sec'],
[1, '1 sec'],
[2, '2 secs'],
[59, '59 secs'],
[60, '1 min'],
[61, '1 min'],
[119, '1 min'],
[120, '2 mins'],
[121, '2 mins'],
[3599, '59 mins'],
[3600, '1 hr'],
[7199, '1 hr'],
[7200, '2 hrs'],
[7201, '2 hrs'],
[86399, '23 hrs'],
[86400, '1 day'],
[86401, '1 day'],
[172799, '1 day'],
[172800, '2 days'],
[172801, '2 days'],
];
}
/**

View File

@@ -30,7 +30,7 @@ class ProcessHelperTest extends TestCase
}
$helper = new ProcessHelper();
$helper->setHelperSet(new HelperSet(array(new DebugFormatterHelper())));
$helper->setHelperSet(new HelperSet([new DebugFormatterHelper()]));
$output = $this->getOutputStream($verbosity);
$helper->run($output, $cmd, $error);
$this->assertEquals($expected, $this->getOutput($output));
@@ -39,13 +39,13 @@ class ProcessHelperTest extends TestCase
public function testPassedCallbackIsExecuted()
{
$helper = new ProcessHelper();
$helper->setHelperSet(new HelperSet(array(new DebugFormatterHelper())));
$helper->setHelperSet(new HelperSet([new DebugFormatterHelper()]));
$output = $this->getOutputStream(StreamOutput::VERBOSITY_NORMAL);
$executed = false;
$callback = function () use (&$executed) { $executed = true; };
$helper->run($output, array('php', '-r', 'echo 42;'), null, $callback);
$helper->run($output, ['php', '-r', 'echo 42;'], null, $callback);
$this->assertTrue($executed);
}
@@ -96,27 +96,27 @@ EOT;
EOT;
$errorMessage = 'An error occurred';
$args = new Process(array('php', '-r', 'echo 42;'));
$args = new Process(['php', '-r', 'echo 42;']);
$args = $args->getCommandLine();
$successOutputProcessDebug = str_replace("'php' '-r' 'echo 42;'", $args, $successOutputProcessDebug);
$fromShellCommandline = \method_exists(Process::class, 'fromShellCommandline') ? array(Process::class, 'fromShellCommandline') : function ($cmd) { return new Process($cmd); };
$fromShellCommandline = \method_exists(Process::class, 'fromShellCommandline') ? [Process::class, 'fromShellCommandline'] : function ($cmd) { return new Process($cmd); };
return array(
array('', 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERBOSE, null),
array($successOutputVerbose, 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERY_VERBOSE, null),
array($successOutputDebug, 'php -r "echo 42;"', StreamOutput::VERBOSITY_DEBUG, null),
array($successOutputDebugWithTags, 'php -r "echo \'<info>42</info>\';"', StreamOutput::VERBOSITY_DEBUG, null),
array('', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null),
array($syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null),
array($syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null),
array($errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage),
array($syntaxErrorOutputVerbose.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage),
array($syntaxErrorOutputDebug.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage),
array($successOutputProcessDebug, array('php', '-r', 'echo 42;'), StreamOutput::VERBOSITY_DEBUG, null),
array($successOutputDebug, $fromShellCommandline('php -r "echo 42;"'), StreamOutput::VERBOSITY_DEBUG, null),
array($successOutputProcessDebug, array(new Process(array('php', '-r', 'echo 42;'))), StreamOutput::VERBOSITY_DEBUG, null),
array($successOutputPhp, array($fromShellCommandline('php -r '.$PHP), 'PHP' => 'echo 42;'), StreamOutput::VERBOSITY_DEBUG, null),
);
return [
['', 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERBOSE, null],
[$successOutputVerbose, 'php -r "echo 42;"', StreamOutput::VERBOSITY_VERY_VERBOSE, null],
[$successOutputDebug, 'php -r "echo 42;"', StreamOutput::VERBOSITY_DEBUG, null],
[$successOutputDebugWithTags, 'php -r "echo \'<info>42</info>\';"', StreamOutput::VERBOSITY_DEBUG, null],
['', 'php -r "syntax error"', StreamOutput::VERBOSITY_VERBOSE, null],
[$syntaxErrorOutputVerbose, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, null],
[$syntaxErrorOutputDebug, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, null],
[$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERBOSE, $errorMessage],
[$syntaxErrorOutputVerbose.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(50000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_VERY_VERBOSE, $errorMessage],
[$syntaxErrorOutputDebug.$errorMessage.PHP_EOL, 'php -r "fwrite(STDERR, \'error message\');usleep(500000);fwrite(STDOUT, \'out message\');exit(252);"', StreamOutput::VERBOSITY_DEBUG, $errorMessage],
[$successOutputProcessDebug, ['php', '-r', 'echo 42;'], StreamOutput::VERBOSITY_DEBUG, null],
[$successOutputDebug, $fromShellCommandline('php -r "echo 42;"'), StreamOutput::VERBOSITY_DEBUG, null],
[$successOutputProcessDebug, [new Process(['php', '-r', 'echo 42;'])], StreamOutput::VERBOSITY_DEBUG, null],
[$successOutputPhp, [$fromShellCommandline('php -r '.$PHP), 'PHP' => 'echo 42;'], StreamOutput::VERBOSITY_DEBUG, null],
];
}
private function getOutputStream($verbosity)

View File

@@ -23,6 +23,19 @@ use Symfony\Component\Console\Output\StreamOutput;
*/
class ProgressBarTest extends TestCase
{
private $colSize;
protected function setUp()
{
$this->colSize = getenv('COLUMNS');
putenv('COLUMNS=120');
}
protected function tearDown()
{
putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS');
}
public function testMultipleStart()
{
$bar = new ProgressBar($output = $this->getOutputStream());
@@ -314,7 +327,7 @@ class ProgressBarTest extends TestCase
public function testOverwriteWithSectionOutput()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream(true);
$output = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
@@ -336,7 +349,7 @@ class ProgressBarTest extends TestCase
public function testOverwriteMultipleProgressBarsWithSectionOutputs()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream(true);
$output1 = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
$output2 = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
@@ -365,7 +378,7 @@ class ProgressBarTest extends TestCase
public function testMultipleSectionsWithCustomFormat()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream(true);
$output1 = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
$output2 = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
@@ -859,12 +872,12 @@ class ProgressBarTest extends TestCase
*/
public function provideFormat()
{
return array(
array('normal'),
array('verbose'),
array('very_verbose'),
array('debug'),
);
return [
['normal'],
['verbose'],
['very_verbose'],
['debug'],
];
}
protected function getOutputStream($decorated = true, $verbosity = StreamOutput::VERBOSITY_NORMAL)

View File

@@ -79,7 +79,7 @@ class ProgressIndicatorTest extends TestCase
public function testCustomIndicatorValues()
{
$bar = new ProgressIndicator($output = $this->getOutputStream(), null, 100, array('a', 'b', 'c'));
$bar = new ProgressIndicator($output = $this->getOutputStream(), null, 100, ['a', 'b', 'c']);
$bar->start('Starting...');
usleep(101000);
@@ -106,7 +106,7 @@ class ProgressIndicatorTest extends TestCase
*/
public function testCannotSetInvalidIndicatorCharacters()
{
$bar = new ProgressIndicator($this->getOutputStream(), null, 100, array('1'));
$bar = new ProgressIndicator($this->getOutputStream(), null, 100, ['1']);
}
/**
@@ -161,12 +161,12 @@ class ProgressIndicatorTest extends TestCase
*/
public function provideFormat()
{
return array(
array('normal'),
array('verbose'),
array('very_verbose'),
array('debug'),
);
return [
['normal'],
['verbose'],
['very_verbose'],
['debug'],
];
}
protected function getOutputStream($decorated = true, $verbosity = StreamOutput::VERBOSITY_NORMAL)

View File

@@ -29,10 +29,10 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
{
$questionHelper = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$questionHelper->setHelperSet($helperSet);
$heroes = array('Superman', 'Batman', 'Spiderman');
$heroes = ['Superman', 'Batman', 'Spiderman'];
$inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n");
@@ -68,21 +68,21 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1');
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 ');
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, 0);
// We are supposed to get the default value since we are not in interactive mode
@@ -93,11 +93,11 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
{
$questionHelper = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$questionHelper->setHelperSet($helperSet);
$inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n");
$heroes = array('Superman', 'Batman', 'Spiderman');
$heroes = ['Superman', 'Batman', 'Spiderman'];
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0');
@@ -122,21 +122,24 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, 1');
$question->setMultiselect(true);
$this->assertSame(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, 1');
$question->setMultiselect(true);
$question->setValidator(null);
$this->assertSame(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '0, Batman');
$question->setMultiselect(true);
$this->assertSame(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$this->assertSame(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, null);
$question->setMultiselect(true);
$this->assertNull($questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream, false), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('Who are your favorite superheros?', ['a' => 'Batman', 'b' => 'Superman'], 'a');
$this->assertSame('a', $questionHelper->ask($this->createStreamableInputInterfaceMock('', false), $this->createOutputInterface(), $question), 'ChoiceQuestion validator returns the key if it\'s a string');
try {
$question = new ChoiceQuestion('Who are your favorite superheros?', $heroes, '');
$question->setMultiselect(true);
@@ -179,11 +182,11 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$inputStream = $this->getInputStream("Acm\nAc\177\177s\tTest\n\n\033[A\033[A\n\033[A\033[A\033[A\033[A\033[A\tTest\n\033[B\nS\177\177\033[B\033[B\nF00\177\177oo\t\n");
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new Question('Please select a bundle', 'FrameworkBundle');
$question->setAutocompleterValues(array('AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle'));
$question->setAutocompleterValues(['AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']);
$this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
@@ -205,9 +208,9 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$inputStream = $this->getInputStream("\033[A\033[A\n\033[B\033[B\n");
$dialog = new QuestionHelper();
$dialog->setHelperSet(new HelperSet(array(new FormatterHelper())));
$dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
$question = new ChoiceQuestion('Please select a bundle', array(1 => 'AcmeDemoBundle', 4 => 'AsseticBundle'));
$question = new ChoiceQuestion('Please select a bundle', [1 => 'AcmeDemoBundle', 4 => 'AsseticBundle']);
$question->setMaxAttempts(1);
$this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
@@ -222,14 +225,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$inputStream = $this->getInputStream("b\n");
$possibleChoices = array(
$possibleChoices = [
'a' => 'berlin',
'b' => 'copenhagen',
'c' => 'amsterdam',
);
];
$dialog = new QuestionHelper();
$dialog->setHelperSet(new HelperSet(array(new FormatterHelper())));
$dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
$question = new ChoiceQuestion('Please select a city', $possibleChoices);
$question->setMaxAttempts(1);
@@ -237,6 +240,43 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$this->assertSame('b', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
}
public function getInputs()
{
return [
['$'], // 1 byte character
['¢'], // 2 bytes character
['€'], // 3 bytes character
['𐍈'], // 4 bytes character
];
}
/**
* @dataProvider getInputs
*/
public function testAskWithAutocompleteWithMultiByteCharacter($character)
{
if (!$this->hasSttyAvailable()) {
$this->markTestSkipped('`stty` is required to test autocomplete functionality');
}
$inputStream = $this->getInputStream("$character\n");
$possibleChoices = [
'$' => '1 byte character',
'¢' => '2 bytes character',
'€' => '3 bytes character',
'𐍈' => '4 bytes character',
];
$dialog = new QuestionHelper();
$dialog->setHelperSet(new HelperSet([new FormatterHelper()]));
$question = new ChoiceQuestion('Please select a character', $possibleChoices);
$question->setMaxAttempts(1);
$this->assertSame($character, $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
}
public function testAutocompleteWithTrailingBackslash()
{
if (!$this->hasSttyAvailable()) {
@@ -246,12 +286,12 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$inputStream = $this->getInputStream('E');
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new Question('');
$expectedCompletion = 'ExampleNamespace\\';
$question->setAutocompleterValues(array($expectedCompletion));
$question->setAutocompleterValues([$expectedCompletion]);
$output = $this->createOutputInterface();
$dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $output, $question);
@@ -262,11 +302,11 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
// Shell control (esc) sequences are not so important: we only care that
// <hl> tag is interpreted correctly and replaced
$irrelevantEscSequences = array(
$irrelevantEscSequences = [
"\0337" => '', // Save cursor position
"\0338" => '', // Restore cursor position
"\033[K" => '', // Clear line from cursor till the end
);
];
$importantActualOutput = strtr($actualOutput, $irrelevantEscSequences);
@@ -304,14 +344,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function getAskConfirmationData()
{
return array(
array('', true),
array('', false, false),
array('y', true),
array('yes', true),
array('n', false),
array('no', false),
);
return [
['', true],
['', false, false],
['y', true],
['yes', true],
['n', false],
['no', false],
];
}
public function testAskConfirmationWithCustomTrueAnswer()
@@ -328,12 +368,12 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function testAskAndValidate()
{
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$error = 'This is not a color!';
$validator = function ($color) use ($error) {
if (!\in_array($color, array('white', 'black'))) {
if (!\in_array($color, ['white', 'black'])) {
throw new \InvalidArgumentException($error);
}
@@ -361,14 +401,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testSelectChoiceFromSimpleChoices($providedAnswer, $expectedValue)
{
$possibleChoices = array(
$possibleChoices = [
'My environment 1',
'My environment 2',
'My environment 3',
);
];
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
@@ -380,14 +420,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function simpleAnswerProvider()
{
return array(
array(0, 'My environment 1'),
array(1, 'My environment 2'),
array(2, 'My environment 3'),
array('My environment 1', 'My environment 1'),
array('My environment 2', 'My environment 2'),
array('My environment 3', 'My environment 3'),
);
return [
[0, 'My environment 1'],
[1, 'My environment 2'],
[2, 'My environment 3'],
['My environment 1', 'My environment 1'],
['My environment 2', 'My environment 2'],
['My environment 3', 'My environment 3'],
];
}
/**
@@ -395,14 +435,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testSpecialCharacterChoiceFromMultipleChoiceList($providedAnswer, $expectedValue)
{
$possibleChoices = array(
$possibleChoices = [
'.',
'src',
);
];
$dialog = new QuestionHelper();
$inputStream = $this->getInputStream($providedAnswer."\n");
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new ChoiceQuestion('Please select the directory', $possibleChoices);
@@ -415,10 +455,10 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function specialCharacterInMultipleChoice()
{
return array(
array('.', array('.')),
array('., src', array('.', 'src')),
);
return [
['.', ['.']],
['., src', ['.', 'src']],
];
}
/**
@@ -426,15 +466,15 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue)
{
$possibleChoices = array(
$possibleChoices = [
'0' => 'No environment',
'1' => 'My environment 1',
'env_2' => 'My environment 2',
3 => 'My environment 3',
);
];
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
@@ -446,14 +486,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function mixedKeysChoiceListAnswerProvider()
{
return array(
array('0', '0'),
array('No environment', '0'),
array('1', '1'),
array('env_2', 'env_2'),
array(3, '3'),
array('My environment 1', '1'),
);
return [
['0', '0'],
['No environment', '0'],
['1', '1'],
['env_2', 'env_2'],
[3, '3'],
['My environment 1', '1'],
];
}
/**
@@ -461,14 +501,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testSelectChoiceFromChoiceList($providedAnswer, $expectedValue)
{
$possibleChoices = array(
$possibleChoices = [
'env_1' => 'My environment 1',
'env_2' => 'My environment',
'env_3' => 'My environment',
);
];
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
@@ -484,14 +524,14 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testAmbiguousChoiceFromChoicelist()
{
$possibleChoices = array(
$possibleChoices = [
'env_1' => 'My first environment',
'env_2' => 'My environment',
'env_3' => 'My environment',
);
];
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new ChoiceQuestion('Please select the environment to load', $possibleChoices);
@@ -502,12 +542,12 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function answerProvider()
{
return array(
array('env_1', 'env_1'),
array('env_2', 'env_2'),
array('env_3', 'env_3'),
array('My environment 1', 'env_1'),
);
return [
['env_1', 'env_1'],
['env_2', 'env_2'],
['env_3', 'env_3'],
['My environment 1', 'env_1'],
];
}
public function testNoInteraction()
@@ -523,22 +563,22 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
public function testChoiceOutputFormattingQuestionForUtf8Keys()
{
$question = 'Lorem ipsum?';
$possibleChoices = array(
$possibleChoices = [
'foo' => 'foo',
'żółw' => 'bar',
'łabądź' => 'baz',
);
$outputShown = array(
];
$outputShown = [
$question,
' [<info>foo </info>] foo',
' [<info>żółw </info>] bar',
' [<info>łabądź</info>] baz',
);
];
$output = $this->getMockBuilder('\Symfony\Component\Console\Output\OutputInterface')->getMock();
$output->method('getFormatter')->willReturn(new OutputFormatter());
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$output->expects($this->once())->method('writeln')->with($this->equalTo($outputShown));
@@ -549,7 +589,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
/**
* @expectedException \Symfony\Component\Console\Exception\RuntimeException
* @expectedExceptionMessage Aborted
* @expectedExceptionMessage Aborted.
*/
public function testAskThrowsExceptionOnMissingInput()
{
@@ -559,7 +599,17 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
/**
* @expectedException \Symfony\Component\Console\Exception\RuntimeException
* @expectedExceptionMessage Aborted
* @expectedExceptionMessage Aborted.
*/
public function testAskThrowsExceptionOnMissingInputForChoiceQuestion()
{
$dialog = new QuestionHelper();
$dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b']));
}
/**
* @expectedException \Symfony\Component\Console\Exception\RuntimeException
* @expectedExceptionMessage Aborted.
*/
public function testAskThrowsExceptionOnMissingInputWithValidator()
{
@@ -581,7 +631,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
*/
public function testEmptyChoices()
{
new ChoiceQuestion('Question', array(), 'irrelevant');
new ChoiceQuestion('Question', [], 'irrelevant');
}
public function testTraversableAutocomplete()
@@ -601,11 +651,11 @@ class QuestionHelperTest extends AbstractQuestionHelperTest
$inputStream = $this->getInputStream("Acm\nAc\177\177s\tTest\n\n\033[A\033[A\n\033[A\033[A\033[A\033[A\033[A\tTest\n\033[B\nS\177\177\033[B\033[B\nF00\177\177oo\t\n");
$dialog = new QuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$dialog->setHelperSet($helperSet);
$question = new Question('Please select a bundle', 'FrameworkBundle');
$question->setAutocompleterValues(new AutocompleteValues(array('irrelevant' => 'AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle')));
$question->setAutocompleterValues(new AutocompleteValues(['irrelevant' => 'AcmeDemoBundle', 'AsseticBundle', 'SecurityBundle', 'FooBundle']));
$this->assertEquals('AcmeDemoBundle', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals('AsseticBundleTest', $dialog->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));

View File

@@ -18,10 +18,10 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest
{
$questionHelper = new SymfonyQuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$questionHelper->setHelperSet($helperSet);
$heroes = array('Superman', 'Batman', 'Spiderman');
$heroes = ['Superman', 'Batman', 'Spiderman'];
$inputStream = $this->getInputStream("\n1\n 1 \nFabien\n1\nFabien\n1\n0,2\n 0 , 2 \n\n\n");
@@ -55,31 +55,31 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(array('Superman', 'Spiderman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Spiderman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $this->createOutputInterface(), $question));
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '0,1');
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
$this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output);
$question = new ChoiceQuestion('What is your favorite superhero?', $heroes, ' 0 , 1 ');
$question->setMaxAttempts(1);
$question->setMultiselect(true);
$this->assertEquals(array('Superman', 'Batman'), $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
$this->assertEquals(['Superman', 'Batman'], $questionHelper->ask($this->createStreamableInputInterfaceMock($inputStream), $output = $this->createOutputInterface(), $question));
$this->assertOutputContains('What is your favorite superhero? [Superman, Batman]', $output);
}
public function testAskChoiceWithChoiceValueAsDefault()
{
$questionHelper = new SymfonyQuestionHelper();
$helperSet = new HelperSet(array(new FormatterHelper()));
$helperSet = new HelperSet([new FormatterHelper()]);
$questionHelper->setHelperSet($helperSet);
$question = new ChoiceQuestion('What is your favorite superhero?', array('Superman', 'Batman', 'Spiderman'), 'Batman');
$question = new ChoiceQuestion('What is your favorite superhero?', ['Superman', 'Batman', 'Spiderman'], 'Batman');
$question->setMaxAttempts(1);
$this->assertSame('Batman', $questionHelper->ask($this->createStreamableInputInterfaceMock($this->getInputStream("Batman\n")), $output = $this->createOutputInterface(), $question));
@@ -124,7 +124,7 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest
/**
* @expectedException \Symfony\Component\Console\Exception\RuntimeException
* @expectedExceptionMessage Aborted
* @expectedExceptionMessage Aborted.
*/
public function testAskThrowsExceptionOnMissingInput()
{

View File

@@ -87,16 +87,16 @@ class TableTest extends TestCase
public function renderProvider()
{
$books = array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
);
$books = [
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'],
['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'],
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
];
return array(
array(
array('ISBN', 'Title', 'Author'),
return [
[
['ISBN', 'Title', 'Author'],
$books,
'default',
<<<'TABLE'
@@ -110,9 +110,9 @@ class TableTest extends TestCase
+---------------+--------------------------+------------------+
TABLE
),
array(
array('ISBN', 'Title', 'Author'),
],
[
['ISBN', 'Title', 'Author'],
$books,
'compact',
<<<'TABLE'
@@ -123,9 +123,9 @@ TABLE
80-902734-1-6 And Then There Were None Agatha Christie
TABLE
),
array(
array('ISBN', 'Title', 'Author'),
],
[
['ISBN', 'Title', 'Author'],
$books,
'borderless',
<<<'TABLE'
@@ -139,9 +139,9 @@ TABLE
=============== ========================== ==================
TABLE
),
array(
array('ISBN', 'Title', 'Author'),
],
[
['ISBN', 'Title', 'Author'],
$books,
'box',
<<<'TABLE'
@@ -155,16 +155,16 @@ TABLE
└───────────────┴──────────────────────────┴──────────────────┘
TABLE
),
array(
array('ISBN', 'Title', 'Author'),
array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
],
[
['ISBN', 'Title', 'Author'],
[
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'],
new TableSeparator(),
array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
),
['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'],
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
],
'box-double',
<<<'TABLE'
╔═══════════════╤══════════════════════════╤══════════════════╗
@@ -178,15 +178,15 @@ TABLE
╚═══════════════╧══════════════════════════╧══════════════════╝
TABLE
),
array(
array('ISBN', 'Title'),
array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
array('9971-5-0210-0'),
array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
),
],
[
['ISBN', 'Title'],
[
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
['9971-5-0210-0'],
['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'],
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
],
'default',
<<<'TABLE'
+---------------+--------------------------+------------------+
@@ -199,15 +199,15 @@ TABLE
+---------------+--------------------------+------------------+
TABLE
),
array(
array(),
array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
array('9971-5-0210-0'),
array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
),
],
[
[],
[
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
['9971-5-0210-0'],
['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'],
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
],
'default',
<<<'TABLE'
+---------------+--------------------------+------------------+
@@ -218,15 +218,15 @@ TABLE
+---------------+--------------------------+------------------+
TABLE
),
array(
array('ISBN', 'Title', 'Author'),
array(
array('99921-58-10-7', "Divine\nComedy", 'Dante Alighieri'),
array('9971-5-0210-2', "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."),
array('9971-5-0210-2', "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."),
array('960-425-059-0', 'The Lord of the Rings', "J. R. R.\nTolkien"),
),
],
[
['ISBN', 'Title', 'Author'],
[
['99921-58-10-7', "Divine\nComedy", 'Dante Alighieri'],
['9971-5-0210-2', "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."],
['9971-5-0210-2', "Harry Potter\nand the Chamber of Secrets", "Rowling\nJoanne K."],
['960-425-059-0', 'The Lord of the Rings', "J. R. R.\nTolkien"],
],
'default',
<<<'TABLE'
+---------------+----------------------------+-----------------+
@@ -243,10 +243,10 @@ TABLE
+---------------+----------------------------+-----------------+
TABLE
),
array(
array('ISBN', 'Title'),
array(),
],
[
['ISBN', 'Title'],
[],
'default',
<<<'TABLE'
+------+-------+
@@ -254,19 +254,19 @@ TABLE
+------+-------+
TABLE
),
array(
array(),
array(),
],
[
[],
[],
'default',
'',
),
'Cell text with tags used for Output styling' => array(
array('ISBN', 'Title', 'Author'),
array(
array('<info>99921-58-10-7</info>', '<error>Divine Comedy</error>', '<fg=blue;bg=white>Dante Alighieri</fg=blue;bg=white>'),
array('9971-5-0210-0', 'A Tale of Two Cities', '<info>Charles Dickens</>'),
),
],
'Cell text with tags used for Output styling' => [
['ISBN', 'Title', 'Author'],
[
['<info>99921-58-10-7</info>', '<error>Divine Comedy</error>', '<fg=blue;bg=white>Dante Alighieri</fg=blue;bg=white>'],
['9971-5-0210-0', 'A Tale of Two Cities', '<info>Charles Dickens</>'],
],
'default',
<<<'TABLE'
+---------------+----------------------+-----------------+
@@ -277,13 +277,13 @@ TABLE
+---------------+----------------------+-----------------+
TABLE
),
'Cell text with tags not used for Output styling' => array(
array('ISBN', 'Title', 'Author'),
array(
array('<strong>99921-58-10-700</strong>', '<f>Divine Com</f>', 'Dante Alighieri'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
),
],
'Cell text with tags not used for Output styling' => [
['ISBN', 'Title', 'Author'],
[
['<strong>99921-58-10-700</strong>', '<f>Divine Com</f>', 'Dante Alighieri'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'],
],
'default',
<<<'TABLE'
+----------------------------------+----------------------+-----------------+
@@ -294,28 +294,28 @@ TABLE
+----------------------------------+----------------------+-----------------+
TABLE
),
'Cell with colspan' => array(
array('ISBN', 'Title', 'Author'),
array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
],
'Cell with colspan' => [
['ISBN', 'Title', 'Author'],
[
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
new TableSeparator(),
array(new TableCell('Divine Comedy(Dante Alighieri)', array('colspan' => 3))),
[new TableCell('Divine Comedy(Dante Alighieri)', ['colspan' => 3])],
new TableSeparator(),
array(
new TableCell('Arduino: A Quick-Start Guide', array('colspan' => 2)),
[
new TableCell('Arduino: A Quick-Start Guide', ['colspan' => 2]),
'Mark Schmidt',
),
],
new TableSeparator(),
array(
[
'9971-5-0210-0',
new TableCell("A Tale of \nTwo Cities", array('colspan' => 2)),
),
new TableCell("A Tale of \nTwo Cities", ['colspan' => 2]),
],
new TableSeparator(),
array(
new TableCell('Cupiditate dicta atque porro, tempora exercitationem modi animi nulla nemo vel nihil!', array('colspan' => 3)),
),
),
[
new TableCell('Cupiditate dicta atque porro, tempora exercitationem modi animi nulla nemo vel nihil!', ['colspan' => 3]),
],
],
'default',
<<<'TABLE'
+-------------------------------+-------------------------------+-----------------------------+
@@ -334,21 +334,21 @@ TABLE
+-------------------------------+-------------------------------+-----------------------------+
TABLE
),
'Cell with rowspan' => array(
array('ISBN', 'Title', 'Author'),
array(
array(
new TableCell('9971-5-0210-0', array('rowspan' => 3)),
new TableCell('Divine Comedy', array('rowspan' => 2)),
],
'Cell with rowspan' => [
['ISBN', 'Title', 'Author'],
[
[
new TableCell('9971-5-0210-0', ['rowspan' => 3]),
new TableCell('Divine Comedy', ['rowspan' => 2]),
'Dante Alighieri',
),
array(),
array("The Lord of \nthe Rings", "J. R. \nR. Tolkien"),
],
[],
["The Lord of \nthe Rings", "J. R. \nR. Tolkien"],
new TableSeparator(),
array('80-902734-1-6', new TableCell("And Then \nThere \nWere None", array('rowspan' => 3)), 'Agatha Christie'),
array('80-902734-1-7', 'Test'),
),
['80-902734-1-6', new TableCell("And Then \nThere \nWere None", ['rowspan' => 3]), 'Agatha Christie'],
['80-902734-1-7', 'Test'],
],
'default',
<<<'TABLE'
+---------------+---------------+-----------------+
@@ -365,23 +365,23 @@ TABLE
+---------------+---------------+-----------------+
TABLE
),
'Cell with rowspan and colspan' => array(
array('ISBN', 'Title', 'Author'),
array(
array(
new TableCell('9971-5-0210-0', array('rowspan' => 2, 'colspan' => 2)),
],
'Cell with rowspan and colspan' => [
['ISBN', 'Title', 'Author'],
[
[
new TableCell('9971-5-0210-0', ['rowspan' => 2, 'colspan' => 2]),
'Dante Alighieri',
),
array('Charles Dickens'),
],
['Charles Dickens'],
new TableSeparator(),
array(
[
'Dante Alighieri',
new TableCell('9971-5-0210-0', array('rowspan' => 3, 'colspan' => 2)),
),
array('J. R. R. Tolkien'),
array('J. R. R'),
),
new TableCell('9971-5-0210-0', ['rowspan' => 3, 'colspan' => 2]),
],
['J. R. R. Tolkien'],
['J. R. R'],
],
'default',
<<<'TABLE'
+------------------+---------+-----------------+
@@ -396,27 +396,27 @@ TABLE
+------------------+---------+-----------------+
TABLE
),
'Cell with rowspan and colspan contains new line break' => array(
array('ISBN', 'Title', 'Author'),
array(
array(
new TableCell("9971\n-5-\n021\n0-0", array('rowspan' => 2, 'colspan' => 2)),
],
'Cell with rowspan and colspan contains new line break' => [
['ISBN', 'Title', 'Author'],
[
[
new TableCell("9971\n-5-\n021\n0-0", ['rowspan' => 2, 'colspan' => 2]),
'Dante Alighieri',
),
array('Charles Dickens'),
],
['Charles Dickens'],
new TableSeparator(),
array(
[
'Dante Alighieri',
new TableCell("9971\n-5-\n021\n0-0", array('rowspan' => 2, 'colspan' => 2)),
),
array('Charles Dickens'),
new TableCell("9971\n-5-\n021\n0-0", ['rowspan' => 2, 'colspan' => 2]),
],
['Charles Dickens'],
new TableSeparator(),
array(
new TableCell("9971\n-5-\n021\n0-0", array('rowspan' => 2, 'colspan' => 2)),
new TableCell("Dante \nAlighieri", array('rowspan' => 2, 'colspan' => 1)),
),
),
[
new TableCell("9971\n-5-\n021\n0-0", ['rowspan' => 2, 'colspan' => 2]),
new TableCell("Dante \nAlighieri", ['rowspan' => 2, 'colspan' => 1]),
],
],
'default',
<<<'TABLE'
+-----------------+-------+-----------------+
@@ -439,21 +439,21 @@ TABLE
+-----------------+-------+-----------------+
TABLE
),
'Cell with rowspan and colspan without using TableSeparator' => array(
array('ISBN', 'Title', 'Author'),
array(
array(
new TableCell("9971\n-5-\n021\n0-0", array('rowspan' => 2, 'colspan' => 2)),
],
'Cell with rowspan and colspan without using TableSeparator' => [
['ISBN', 'Title', 'Author'],
[
[
new TableCell("9971\n-5-\n021\n0-0", ['rowspan' => 2, 'colspan' => 2]),
'Dante Alighieri',
),
array('Charles Dickens'),
array(
],
['Charles Dickens'],
[
'Dante Alighieri',
new TableCell("9971\n-5-\n021\n0-0", array('rowspan' => 2, 'colspan' => 2)),
),
array('Charles Dickens'),
),
new TableCell("9971\n-5-\n021\n0-0", ['rowspan' => 2, 'colspan' => 2]),
],
['Charles Dickens'],
],
'default',
<<<'TABLE'
+-----------------+-------+-----------------+
@@ -470,17 +470,17 @@ TABLE
+-----------------+-------+-----------------+
TABLE
),
'Cell with rowspan and colspan with separator inside a rowspan' => array(
array('ISBN', 'Author'),
array(
array(
new TableCell('9971-5-0210-0', array('rowspan' => 3, 'colspan' => 1)),
],
'Cell with rowspan and colspan with separator inside a rowspan' => [
['ISBN', 'Author'],
[
[
new TableCell('9971-5-0210-0', ['rowspan' => 3, 'colspan' => 1]),
'Dante Alighieri',
),
array(new TableSeparator()),
array('Charles Dickens'),
),
],
[new TableSeparator()],
['Charles Dickens'],
],
'default',
<<<'TABLE'
+---------------+-----------------+
@@ -492,13 +492,13 @@ TABLE
+---------------+-----------------+
TABLE
),
'Multiple header lines' => array(
array(
array(new TableCell('Main title', array('colspan' => 3))),
array('ISBN', 'Title', 'Author'),
),
array(),
],
'Multiple header lines' => [
[
[new TableCell('Main title', ['colspan' => 3])],
['ISBN', 'Title', 'Author'],
],
[],
'default',
<<<'TABLE'
+------+-------+--------+
@@ -508,17 +508,17 @@ TABLE
+------+-------+--------+
TABLE
),
'Row with multiple cells' => array(
array(),
array(
array(
new TableCell('1', array('colspan' => 3)),
new TableCell('2', array('colspan' => 2)),
new TableCell('3', array('colspan' => 2)),
new TableCell('4', array('colspan' => 2)),
),
),
],
'Row with multiple cells' => [
[],
[
[
new TableCell('1', ['colspan' => 3]),
new TableCell('2', ['colspan' => 2]),
new TableCell('3', ['colspan' => 2]),
new TableCell('4', ['colspan' => 2]),
],
],
'default',
<<<'TABLE'
+---+--+--+---+--+---+--+---+--+
@@ -526,22 +526,22 @@ TABLE
+---+--+--+---+--+---+--+---+--+
TABLE
),
'Coslpan and table cells with comment style' => array(
array(
new TableCell('<comment>Long Title</comment>', array('colspan' => 3)),
),
array(
array(
new TableCell('9971-5-0210-0', array('colspan' => 3)),
),
],
'Coslpan and table cells with comment style' => [
[
new TableCell('<comment>Long Title</comment>', ['colspan' => 3]),
],
[
[
new TableCell('9971-5-0210-0', ['colspan' => 3]),
],
new TableSeparator(),
array(
[
'Dante Alighieri',
'J. R. R. Tolkien',
'J. R. R',
),
),
],
],
'default',
<<<TABLE
+-----------------+------------------+---------+
@@ -555,22 +555,22 @@ TABLE
TABLE
,
true,
),
'Row with formatted cells containing a newline' => array(
array(),
array(
array(
new TableCell('<error>Dont break'."\n".'here</error>', array('colspan' => 2)),
),
],
'Row with formatted cells containing a newline' => [
[],
[
[
new TableCell('<error>Dont break'."\n".'here</error>', ['colspan' => 2]),
],
new TableSeparator(),
array(
[
'foo',
new TableCell('<error>Dont break'."\n".'here</error>', array('rowspan' => 2)),
),
array(
new TableCell('<error>Dont break'."\n".'here</error>', ['rowspan' => 2]),
],
[
'bar',
),
),
],
],
'default',
<<<'TABLE'
+-------+------------+
@@ -584,16 +584,16 @@ TABLE
TABLE
,
true,
),
);
],
];
}
public function testRenderMultiByte()
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('■■'))
->setRows(array(array(1234)))
->setHeaders(['■■'])
->setRows([[1234]])
->setStyle('default')
;
$table->render();
@@ -615,7 +615,7 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table->setRows(array(array(new TableCell(12345))));
$table->setRows([[new TableCell(12345)]]);
$table->render();
$expected =
@@ -633,7 +633,7 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table->setRows(array(array(new TableCell(12345.01))));
$table->setRows([[new TableCell(12345.01)]]);
$table->render();
$expected =
@@ -659,8 +659,8 @@ TABLE;
Table::setStyleDefinition('dotfull', $style);
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('Foo'))
->setRows(array(array('Bar')))
->setHeaders(['Foo'])
->setRows([['Bar']])
->setStyle('dotfull');
$table->render();
@@ -681,14 +681,14 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('Foo'))
->setRows(array(
array('Bar1'),
->setHeaders(['Foo'])
->setRows([
['Bar1'],
new TableSeparator(),
array('Bar2'),
['Bar2'],
new TableSeparator(),
array('Bar3'),
));
['Bar3'],
]);
$table->render();
$expected =
@@ -713,9 +713,9 @@ TABLE;
public function testRenderMultiCalls()
{
$table = new Table($output = $this->getOutputStream());
$table->setRows(array(
array(new TableCell('foo', array('colspan' => 2))),
));
$table->setRows([
[new TableCell('foo', ['colspan' => 2])],
]);
$table->render();
$table->render();
$table->render();
@@ -741,11 +741,11 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'),
));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'],
]);
$style = new TableStyle();
$style->setPadType(STR_PAD_LEFT);
@@ -775,10 +775,10 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', array(), 'Dante Alighieri', '9.95'),
));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', [], 'Dante Alighieri', '9.95'],
]);
$table->render();
}
@@ -787,11 +787,11 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'),
))
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'],
])
->setColumnWidth(0, 15)
->setColumnWidth(3, 10);
@@ -819,12 +819,12 @@ TABLE;
{
$table = new Table($output = $this->getOutputStream());
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'),
))
->setColumnWidths(array(15, 0, -1, 10));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'],
])
->setColumnWidths([15, 0, -1, 10]);
$style = new TableStyle();
$style->setPadType(STR_PAD_LEFT);
@@ -848,19 +848,19 @@ TABLE;
public function testSectionOutput()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream(true);
$output = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
$table = new Table($output);
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
]);
$table->render();
$table->appendRow(array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'));
$table->appendRow(['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25']);
$expected =
<<<TABLE
@@ -883,17 +883,17 @@ TABLE;
public function testSectionOutputDoesntClearIfTableIsntRendered()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream(true);
$output = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
$table = new Table($output);
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
]);
$table->appendRow(array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'));
$table->appendRow(['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25']);
$expected =
<<<TABLE
@@ -911,19 +911,19 @@ TABLE;
public function testSectionOutputWithoutDecoration()
{
$sections = array();
$sections = [];
$stream = $this->getOutputStream();
$output = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
$table = new Table($output);
$table
->setHeaders(array('ISBN', 'Title', 'Author', 'Price'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'),
));
->setHeaders(['ISBN', 'Title', 'Author', 'Price'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri', '9.95'],
]);
$table->render();
$table->appendRow(array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'));
$table->appendRow(['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25']);
$expected =
<<<TABLE
@@ -952,7 +952,7 @@ TABLE;
{
$table = new Table($this->getOutputStream());
$table->appendRow(array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25'));
$table->appendRow(['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens', '139.25']);
}
/**
@@ -982,13 +982,13 @@ TABLE;
(new Table($output = $this->getOutputStream()))
->setHeaderTitle($headerTitle)
->setFooterTitle($footerTitle)
->setHeaders(array('ISBN', 'Title', 'Author'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
array('9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'),
array('960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'),
array('80-902734-1-6', 'And Then There Were None', 'Agatha Christie'),
))
->setHeaders(['ISBN', 'Title', 'Author'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
['9971-5-0210-0', 'A Tale of Two Cities', 'Charles Dickens'],
['960-425-059-0', 'The Lord of the Rings', 'J. R. R. Tolkien'],
['80-902734-1-6', 'And Then There Were None', 'Agatha Christie'],
])
->setStyle($style)
->render()
;
@@ -998,8 +998,8 @@ TABLE;
public function renderSetTitle()
{
return array(
array(
return [
[
'Books',
'Page 1/2',
'default',
@@ -1014,8 +1014,8 @@ TABLE;
+---------------+--------- Page 1/2 -------+------------------+
TABLE
),
array(
],
[
'Books',
'Page 1/2',
'box',
@@ -1030,8 +1030,8 @@ TABLE
└───────────────┴───────── Page 1/2 ───────┴──────────────────┘
TABLE
),
array(
],
[
'Boooooooooooooooooooooooooooooooooooooooooooooooooooooooks',
'Page 1/999999999999999999999999999999999999999999999999999',
'default',
@@ -1046,17 +1046,17 @@ TABLE
+- Page 1/99999999999999999999999999999999999999999999999... -+
TABLE
),
);
],
];
}
public function testColumnMaxWidths()
{
$table = new Table($output = $this->getOutputStream());
$table
->setRows(array(
array('Divine Comedy', 'A Tale of Two Cities', 'The Lord of the Rings', 'And Then There Were None'),
))
->setRows([
['Divine Comedy', 'A Tale of Two Cities', 'The Lord of the Rings', 'And Then There Were None'],
])
->setColumnMaxWidth(1, 5)
->setColumnMaxWidth(2, 10)
->setColumnMaxWidth(3, 15);
@@ -1072,6 +1072,26 @@ TABLE
| | ities | | |
+---------------+-------+------------+-----------------+
TABLE;
$this->assertEquals($expected, $this->getOutputContent($output));
}
public function testColumnMaxWidthsWithTrailingBackslash()
{
(new Table($output = $this->getOutputStream()))
->setColumnMaxWidth(0, 5)
->setRows([['1234\6']])
->render()
;
$expected =
<<<'TABLE'
+-------+
| 1234\ |
| 6 |
+-------+
TABLE;
$this->assertEquals($expected, $this->getOutputContent($output));
@@ -1089,12 +1109,12 @@ TABLE;
$table = new Table($output = $this->getOutputStream());
$table->setStyle($boxed);
$table
->setHeaders(array('ISBN', 'Title', 'Author'))
->setRows(array(
array('99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'),
->setHeaders(['ISBN', 'Title', 'Author'])
->setRows([
['99921-58-10-7', 'Divine Comedy', 'Dante Alighieri'],
new TableSeparator(),
array(new TableCell('This value spans 3 columns.', array('colspan' => 3))),
))
[new TableCell('This value spans 3 columns.', ['colspan' => 3])],
])
;
$table->render();
@@ -1124,4 +1144,56 @@ TABLE;
return str_replace(PHP_EOL, "\n", stream_get_contents($output->getStream()));
}
public function testWithColspanAndMaxWith(): void
{
$table = new Table($output = $this->getOutputStream());
$table->setColumnMaxWidth(0, 15);
$table->setColumnMaxWidth(1, 15);
$table->setColumnMaxWidth(2, 15);
$table->setRows([
[new TableCell('Lorem ipsum dolor sit amet, <fg=white;bg=green>consectetur</> adipiscing elit, <fg=white;bg=red>sed</> do <fg=white;bg=red>eiusmod</> tempor', ['colspan' => 3])],
new TableSeparator(),
[new TableCell('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor', ['colspan' => 3])],
new TableSeparator(),
[new TableCell('Lorem ipsum <fg=white;bg=red>dolor</> sit amet, consectetur ', ['colspan' => 2]), 'hello world'],
new TableSeparator(),
['hello <fg=white;bg=green>world</>', new TableCell('Lorem ipsum dolor sit amet, <fg=white;bg=green>consectetur</> adipiscing elit', ['colspan' => 2])],
new TableSeparator(),
['hello ', new TableCell('world', ['colspan' => 1]), 'Lorem ipsum dolor sit amet, consectetur'],
new TableSeparator(),
['Symfony ', new TableCell('Test', ['colspan' => 1]), 'Lorem <fg=white;bg=green>ipsum</> dolor sit amet, consectetur'],
])
;
$table->render();
$expected =
<<<TABLE
+-----------------+-----------------+-----------------+
| Lorem ipsum dolor sit amet, consectetur adipi |
| scing elit, sed do eiusmod tempor |
+-----------------+-----------------+-----------------+
| Lorem ipsum dolor sit amet, consectetur adipi |
| scing elit, sed do eiusmod tempor |
+-----------------+-----------------+-----------------+
| Lorem ipsum dolor sit amet, co | hello world |
| nsectetur | |
+-----------------+-----------------+-----------------+
| hello world | Lorem ipsum dolor sit amet, co |
| | nsectetur adipiscing elit |
+-----------------+-----------------+-----------------+
| hello | world | Lorem ipsum dol |
| | | or sit amet, co |
| | | nsectetur |
+-----------------+-----------------+-----------------+
| Symfony | Test | Lorem ipsum dol |
| | | or sit amet, co |
| | | nsectetur |
+-----------------+-----------------+-----------------+
TABLE;
$this->assertSame($expected, $this->getOutputContent($output));
}
}

View File

@@ -21,23 +21,23 @@ class ArgvInputTest extends TestCase
{
public function testConstructor()
{
$_SERVER['argv'] = array('cli.php', 'foo');
$_SERVER['argv'] = ['cli.php', 'foo'];
$input = new ArgvInput();
$r = new \ReflectionObject($input);
$p = $r->getProperty('tokens');
$p->setAccessible(true);
$this->assertEquals(array('foo'), $p->getValue($input), '__construct() automatically get its input from the argv server variable');
$this->assertEquals(['foo'], $p->getValue($input), '__construct() automatically get its input from the argv server variable');
}
public function testParseArguments()
{
$input = new ArgvInput(array('cli.php', 'foo'));
$input->bind(new InputDefinition(array(new InputArgument('name'))));
$this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments');
$input = new ArgvInput(['cli.php', 'foo']);
$input->bind(new InputDefinition([new InputArgument('name')]));
$this->assertEquals(['name' => 'foo'], $input->getArguments(), '->parse() parses required arguments');
$input->bind(new InputDefinition(array(new InputArgument('name'))));
$this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() is stateless');
$input->bind(new InputDefinition([new InputArgument('name')]));
$this->assertEquals(['name' => 'foo'], $input->getArguments(), '->parse() is stateless');
}
/**
@@ -53,128 +53,128 @@ class ArgvInputTest extends TestCase
public function provideOptions()
{
return array(
array(
array('cli.php', '--foo'),
array(new InputOption('foo')),
array('foo' => true),
return [
[
['cli.php', '--foo'],
[new InputOption('foo')],
['foo' => true],
'->parse() parses long options without a value',
),
array(
array('cli.php', '--foo=bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
array('foo' => 'bar'),
],
[
['cli.php', '--foo=bar'],
[new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)],
['foo' => 'bar'],
'->parse() parses long options with a required value (with a = separator)',
),
array(
array('cli.php', '--foo', 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
array('foo' => 'bar'),
],
[
['cli.php', '--foo', 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)],
['foo' => 'bar'],
'->parse() parses long options with a required value (with a space separator)',
),
array(
array('cli.php', '--foo='),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
array('foo' => ''),
],
[
['cli.php', '--foo='],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)],
['foo' => ''],
'->parse() parses long options with optional value which is empty (with a = separator) as empty string',
),
array(
array('cli.php', '--foo=', 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)),
array('foo' => ''),
],
[
['cli.php', '--foo=', 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)],
['foo' => ''],
'->parse() parses long options with optional value without value specified or an empty string (with a = separator) followed by an argument as empty string',
),
array(
array('cli.php', 'bar', '--foo'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)),
array('foo' => null),
],
[
['cli.php', 'bar', '--foo'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)],
['foo' => null],
'->parse() parses long options with optional value which is empty (with a = separator) preceded by an argument',
),
array(
array('cli.php', '--foo', '', 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)),
array('foo' => ''),
],
[
['cli.php', '--foo', '', 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)],
['foo' => ''],
'->parse() parses long options with optional value which is empty as empty string even followed by an argument',
),
array(
array('cli.php', '--foo'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
array('foo' => null),
],
[
['cli.php', '--foo'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)],
['foo' => null],
'->parse() parses long options with optional value specified with no separator and no value as null',
),
array(
array('cli.php', '-f'),
array(new InputOption('foo', 'f')),
array('foo' => true),
],
[
['cli.php', '-f'],
[new InputOption('foo', 'f')],
['foo' => true],
'->parse() parses short options without a value',
),
array(
array('cli.php', '-fbar'),
array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
array('foo' => 'bar'),
],
[
['cli.php', '-fbar'],
[new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)],
['foo' => 'bar'],
'->parse() parses short options with a required value (with no separator)',
),
array(
array('cli.php', '-f', 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)),
array('foo' => 'bar'),
],
[
['cli.php', '-f', 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)],
['foo' => 'bar'],
'->parse() parses short options with a required value (with a space separator)',
),
array(
array('cli.php', '-f', ''),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
array('foo' => ''),
],
[
['cli.php', '-f', ''],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)],
['foo' => ''],
'->parse() parses short options with an optional empty value',
),
array(
array('cli.php', '-f', '', 'foo'),
array(new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)),
array('foo' => ''),
],
[
['cli.php', '-f', '', 'foo'],
[new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)],
['foo' => ''],
'->parse() parses short options with an optional empty value followed by an argument',
),
array(
array('cli.php', '-f', '', '-b'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')),
array('foo' => '', 'bar' => true),
],
[
['cli.php', '-f', '', '-b'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')],
['foo' => '', 'bar' => true],
'->parse() parses short options with an optional empty value followed by an option',
),
array(
array('cli.php', '-f', '-b', 'foo'),
array(new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')),
array('foo' => null, 'bar' => true),
],
[
['cli.php', '-f', '-b', 'foo'],
[new InputArgument('name'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b')],
['foo' => null, 'bar' => true],
'->parse() parses short options with an optional value which is not present',
),
array(
array('cli.php', '-fb'),
array(new InputOption('foo', 'f'), new InputOption('bar', 'b')),
array('foo' => true, 'bar' => true),
],
[
['cli.php', '-fb'],
[new InputOption('foo', 'f'), new InputOption('bar', 'b')],
['foo' => true, 'bar' => true],
'->parse() parses short options when they are aggregated as a single one',
),
array(
array('cli.php', '-fb', 'bar'),
array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_REQUIRED)),
array('foo' => true, 'bar' => 'bar'),
],
[
['cli.php', '-fb', 'bar'],
[new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_REQUIRED)],
['foo' => true, 'bar' => 'bar'],
'->parse() parses short options when they are aggregated as a single one and the last one has a required value',
),
array(
array('cli.php', '-fb', 'bar'),
array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
array('foo' => true, 'bar' => 'bar'),
],
[
['cli.php', '-fb', 'bar'],
[new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)],
['foo' => true, 'bar' => 'bar'],
'->parse() parses short options when they are aggregated as a single one and the last one has an optional value',
),
array(
array('cli.php', '-fbbar'),
array(new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
array('foo' => true, 'bar' => 'bar'),
],
[
['cli.php', '-fbbar'],
[new InputOption('foo', 'f'), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)],
['foo' => true, 'bar' => 'bar'],
'->parse() parses short options when they are aggregated as a single one and the last one has an optional value with no separator',
),
array(
array('cli.php', '-fbbar'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)),
array('foo' => 'bbar', 'bar' => null),
],
[
['cli.php', '-fbbar'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputOption('bar', 'b', InputOption::VALUE_OPTIONAL)],
['foo' => 'bbar', 'bar' => null],
'->parse() parses short options when they are aggregated as a single one and one of them takes a value',
),
);
],
];
}
/**
@@ -195,162 +195,170 @@ class ArgvInputTest extends TestCase
public function provideInvalidInput()
{
return array(
array(
array('cli.php', '--foo'),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
return [
[
['cli.php', '--foo'],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)]),
'The "--foo" option requires a value.',
),
array(
array('cli.php', '-f'),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
],
[
['cli.php', '-f'],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)]),
'The "--foo" option requires a value.',
),
array(
array('cli.php', '-ffoo'),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))),
],
[
['cli.php', '-ffoo'],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_NONE)]),
'The "-o" option does not exist.',
),
array(
array('cli.php', '--foo=bar'),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))),
],
[
['cli.php', '--foo=bar'],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_NONE)]),
'The "--foo" option does not accept a value.',
),
array(
array('cli.php', 'foo', 'bar'),
],
[
['cli.php', 'foo', 'bar'],
new InputDefinition(),
'No arguments expected, got "foo".',
),
array(
array('cli.php', 'foo', 'bar'),
new InputDefinition(array(new InputArgument('number'))),
],
[
['cli.php', 'foo', 'bar'],
new InputDefinition([new InputArgument('number')]),
'Too many arguments, expected arguments "number".',
),
array(
array('cli.php', 'foo', 'bar', 'zzz'),
new InputDefinition(array(new InputArgument('number'), new InputArgument('county'))),
],
[
['cli.php', 'foo', 'bar', 'zzz'],
new InputDefinition([new InputArgument('number'), new InputArgument('county')]),
'Too many arguments, expected arguments "number" "county".',
),
array(
array('cli.php', '--foo'),
],
[
['cli.php', '--foo'],
new InputDefinition(),
'The "--foo" option does not exist.',
),
array(
array('cli.php', '-f'),
],
[
['cli.php', '-f'],
new InputDefinition(),
'The "-f" option does not exist.',
),
array(
array('cli.php', '-1'),
new InputDefinition(array(new InputArgument('number'))),
],
[
['cli.php', '-1'],
new InputDefinition([new InputArgument('number')]),
'The "-1" option does not exist.',
),
array(
array('cli.php', '-fЩ'),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_NONE))),
],
[
['cli.php', '-fЩ'],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_NONE)]),
'The "-Щ" option does not exist.',
),
);
],
];
}
public function testParseArrayArgument()
{
$input = new ArgvInput(array('cli.php', 'foo', 'bar', 'baz', 'bat'));
$input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::IS_ARRAY))));
$input = new ArgvInput(['cli.php', 'foo', 'bar', 'baz', 'bat']);
$input->bind(new InputDefinition([new InputArgument('name', InputArgument::IS_ARRAY)]));
$this->assertEquals(array('name' => array('foo', 'bar', 'baz', 'bat')), $input->getArguments(), '->parse() parses array arguments');
$this->assertEquals(['name' => ['foo', 'bar', 'baz', 'bat']], $input->getArguments(), '->parse() parses array arguments');
}
public function testParseArrayOption()
{
$input = new ArgvInput(array('cli.php', '--name=foo', '--name=bar', '--name=baz'));
$input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));
$input = new ArgvInput(['cli.php', '--name=foo', '--name=bar', '--name=baz']);
$input->bind(new InputDefinition([new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY)]));
$this->assertEquals(array('name' => array('foo', 'bar', 'baz')), $input->getOptions(), '->parse() parses array options ("--option=value" syntax)');
$this->assertEquals(['name' => ['foo', 'bar', 'baz']], $input->getOptions(), '->parse() parses array options ("--option=value" syntax)');
$input = new ArgvInput(array('cli.php', '--name', 'foo', '--name', 'bar', '--name', 'baz'));
$input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));
$this->assertEquals(array('name' => array('foo', 'bar', 'baz')), $input->getOptions(), '->parse() parses array options ("--option value" syntax)');
$input = new ArgvInput(['cli.php', '--name', 'foo', '--name', 'bar', '--name', 'baz']);
$input->bind(new InputDefinition([new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY)]));
$this->assertEquals(['name' => ['foo', 'bar', 'baz']], $input->getOptions(), '->parse() parses array options ("--option value" syntax)');
$input = new ArgvInput(array('cli.php', '--name=foo', '--name=bar', '--name='));
$input->bind(new InputDefinition(array(new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY))));
$this->assertSame(array('name' => array('foo', 'bar', '')), $input->getOptions(), '->parse() parses empty array options as null ("--option=value" syntax)');
$input = new ArgvInput(['cli.php', '--name=foo', '--name=bar', '--name=']);
$input->bind(new InputDefinition([new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY)]));
$this->assertSame(['name' => ['foo', 'bar', '']], $input->getOptions(), '->parse() parses empty array options as null ("--option=value" syntax)');
$input = new ArgvInput(array('cli.php', '--name', 'foo', '--name', 'bar', '--name', '--anotherOption'));
$input->bind(new InputDefinition(array(
$input = new ArgvInput(['cli.php', '--name', 'foo', '--name', 'bar', '--name', '--anotherOption']);
$input->bind(new InputDefinition([
new InputOption('name', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY),
new InputOption('anotherOption', null, InputOption::VALUE_NONE),
)));
$this->assertSame(array('name' => array('foo', 'bar', null), 'anotherOption' => true), $input->getOptions(), '->parse() parses empty array options ("--option value" syntax)');
]));
$this->assertSame(['name' => ['foo', 'bar', null], 'anotherOption' => true], $input->getOptions(), '->parse() parses empty array options ("--option value" syntax)');
}
public function testParseNegativeNumberAfterDoubleDash()
{
$input = new ArgvInput(array('cli.php', '--', '-1'));
$input->bind(new InputDefinition(array(new InputArgument('number'))));
$this->assertEquals(array('number' => '-1'), $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');
$input = new ArgvInput(['cli.php', '--', '-1']);
$input->bind(new InputDefinition([new InputArgument('number')]));
$this->assertEquals(['number' => '-1'], $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');
$input = new ArgvInput(array('cli.php', '-f', 'bar', '--', '-1'));
$input->bind(new InputDefinition(array(new InputArgument('number'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL))));
$this->assertEquals(array('foo' => 'bar'), $input->getOptions(), '->parse() parses arguments with leading dashes as options before having encountered a double-dash sequence');
$this->assertEquals(array('number' => '-1'), $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');
$input = new ArgvInput(['cli.php', '-f', 'bar', '--', '-1']);
$input->bind(new InputDefinition([new InputArgument('number'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)]));
$this->assertEquals(['foo' => 'bar'], $input->getOptions(), '->parse() parses arguments with leading dashes as options before having encountered a double-dash sequence');
$this->assertEquals(['number' => '-1'], $input->getArguments(), '->parse() parses arguments with leading dashes as arguments after having encountered a double-dash sequence');
}
public function testParseEmptyStringArgument()
{
$input = new ArgvInput(array('cli.php', '-f', 'bar', ''));
$input->bind(new InputDefinition(array(new InputArgument('empty'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL))));
$input = new ArgvInput(['cli.php', '-f', 'bar', '']);
$input->bind(new InputDefinition([new InputArgument('empty'), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)]));
$this->assertEquals(array('empty' => ''), $input->getArguments(), '->parse() parses empty string arguments');
$this->assertEquals(['empty' => ''], $input->getArguments(), '->parse() parses empty string arguments');
}
public function testGetFirstArgument()
{
$input = new ArgvInput(array('cli.php', '-fbbar'));
$input = new ArgvInput(['cli.php', '-fbbar']);
$this->assertNull($input->getFirstArgument(), '->getFirstArgument() returns null when there is no arguments');
$input = new ArgvInput(array('cli.php', '-fbbar', 'foo'));
$input = new ArgvInput(['cli.php', '-fbbar', 'foo']);
$this->assertEquals('foo', $input->getFirstArgument(), '->getFirstArgument() returns the first argument from the raw input');
$input = new ArgvInput(['cli.php', '--foo', 'fooval', 'bar']);
$input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('arg')]));
$this->assertSame('bar', $input->getFirstArgument());
$input = new ArgvInput(['cli.php', '-bf', 'fooval', 'argval']);
$input->bind(new InputDefinition([new InputOption('bar', 'b', InputOption::VALUE_NONE), new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('arg')]));
$this->assertSame('argval', $input->getFirstArgument());
}
public function testHasParameterOption()
{
$input = new ArgvInput(array('cli.php', '-f', 'foo'));
$input = new ArgvInput(['cli.php', '-f', 'foo']);
$this->assertTrue($input->hasParameterOption('-f'), '->hasParameterOption() returns true if the given short option is in the raw input');
$input = new ArgvInput(array('cli.php', '-etest'));
$input = new ArgvInput(['cli.php', '-etest']);
$this->assertTrue($input->hasParameterOption('-e'), '->hasParameterOption() returns true if the given short option is in the raw input');
$this->assertFalse($input->hasParameterOption('-s'), '->hasParameterOption() returns true if the given short option is in the raw input');
$input = new ArgvInput(array('cli.php', '--foo', 'foo'));
$input = new ArgvInput(['cli.php', '--foo', 'foo']);
$this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if the given short option is in the raw input');
$input = new ArgvInput(array('cli.php', 'foo'));
$input = new ArgvInput(['cli.php', 'foo']);
$this->assertFalse($input->hasParameterOption('--foo'), '->hasParameterOption() returns false if the given short option is not in the raw input');
$input = new ArgvInput(array('cli.php', '--foo=bar'));
$input = new ArgvInput(['cli.php', '--foo=bar']);
$this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if the given option with provided value is in the raw input');
}
public function testHasParameterOptionOnlyOptions()
{
$input = new ArgvInput(array('cli.php', '-f', 'foo'));
$input = new ArgvInput(['cli.php', '-f', 'foo']);
$this->assertTrue($input->hasParameterOption('-f', true), '->hasParameterOption() returns true if the given short option is in the raw input');
$input = new ArgvInput(array('cli.php', '--foo', '--', 'foo'));
$input = new ArgvInput(['cli.php', '--foo', '--', 'foo']);
$this->assertTrue($input->hasParameterOption('--foo', true), '->hasParameterOption() returns true if the given long option is in the raw input');
$input = new ArgvInput(array('cli.php', '--foo=bar', 'foo'));
$input = new ArgvInput(['cli.php', '--foo=bar', 'foo']);
$this->assertTrue($input->hasParameterOption('--foo', true), '->hasParameterOption() returns true if the given long option with provided value is in the raw input');
$input = new ArgvInput(array('cli.php', '--', '--foo'));
$input = new ArgvInput(['cli.php', '--', '--foo']);
$this->assertFalse($input->hasParameterOption('--foo', true), '->hasParameterOption() returns false if the given option is in the raw input but after an end of options signal');
}
public function testHasParameterOptionEdgeCasesAndLimitations()
{
$input = new ArgvInput(array('cli.php', '-fh'));
$input = new ArgvInput(['cli.php', '-fh']);
// hasParameterOption does not know if the previous short option, -f,
// takes a value or not. If -f takes a value, then -fh does NOT include
// -h; Otherwise it does. Since we do not know which short options take
@@ -368,7 +376,7 @@ class ArgvInputTest extends TestCase
// However, this is not supported.
$this->assertFalse($input->hasParameterOption('-hf'), '->hasParameterOption() returns true if the given short option is in the raw input');
$input = new ArgvInput(array('cli.php', '-f', '-h'));
$input = new ArgvInput(['cli.php', '-f', '-h']);
// If hasParameterOption('-fh') is supported for 'cli.php -fh', then
// one might also expect that it should also be supported for
// 'cli.php -f -h'. However, this is not supported.
@@ -377,23 +385,23 @@ class ArgvInputTest extends TestCase
public function testNoWarningOnInvalidParameterOption()
{
$input = new ArgvInput(array('cli.php', '-edev'));
$input = new ArgvInput(['cli.php', '-edev']);
$this->assertTrue($input->hasParameterOption(array('-e', '')));
$this->assertTrue($input->hasParameterOption(['-e', '']));
// No warning thrown
$this->assertFalse($input->hasParameterOption(array('-m', '')));
$this->assertFalse($input->hasParameterOption(['-m', '']));
$this->assertEquals('dev', $input->getParameterOption(array('-e', '')));
$this->assertEquals('dev', $input->getParameterOption(['-e', '']));
// No warning thrown
$this->assertFalse($input->getParameterOption(array('-m', '')));
$this->assertFalse($input->getParameterOption(['-m', '']));
}
public function testToString()
{
$input = new ArgvInput(array('cli.php', '-f', 'foo'));
$input = new ArgvInput(['cli.php', '-f', 'foo']);
$this->assertEquals('-f foo', (string) $input);
$input = new ArgvInput(array('cli.php', '-f', '--bar=foo', 'a b c d', "A\nB'C"));
$input = new ArgvInput(['cli.php', '-f', '--bar=foo', 'a b c d', "A\nB'C"]);
$this->assertEquals('-f --bar=foo '.escapeshellarg('a b c d').' '.escapeshellarg("A\nB'C"), (string) $input);
}
@@ -408,51 +416,51 @@ class ArgvInputTest extends TestCase
public function provideGetParameterOptionValues()
{
return array(
array(array('app/console', 'foo:bar'), '-e', 'default', false, 'default'),
array(array('app/console', 'foo:bar', '-e', 'dev'), '-e', 'default', false, 'dev'),
array(array('app/console', 'foo:bar', '--env=dev'), '--env', 'default', false, 'dev'),
array(array('app/console', 'foo:bar', '-e', 'dev'), array('-e', '--env'), 'default', false, 'dev'),
array(array('app/console', 'foo:bar', '--env=dev'), array('-e', '--env'), 'default', false, 'dev'),
array(array('app/console', 'foo:bar', '--env=dev', '--en=1'), array('--en'), 'default', false, '1'),
array(array('app/console', 'foo:bar', '--env=dev', '', '--en=1'), array('--en'), 'default', false, '1'),
array(array('app/console', 'foo:bar', '--env', 'val'), '--env', 'default', false, 'val'),
array(array('app/console', 'foo:bar', '--env', 'val', '--dummy'), '--env', 'default', false, 'val'),
array(array('app/console', 'foo:bar', '--', '--env=dev'), '--env', 'default', false, 'dev'),
array(array('app/console', 'foo:bar', '--', '--env=dev'), '--env', 'default', true, 'default'),
);
return [
[['app/console', 'foo:bar'], '-e', 'default', false, 'default'],
[['app/console', 'foo:bar', '-e', 'dev'], '-e', 'default', false, 'dev'],
[['app/console', 'foo:bar', '--env=dev'], '--env', 'default', false, 'dev'],
[['app/console', 'foo:bar', '-e', 'dev'], ['-e', '--env'], 'default', false, 'dev'],
[['app/console', 'foo:bar', '--env=dev'], ['-e', '--env'], 'default', false, 'dev'],
[['app/console', 'foo:bar', '--env=dev', '--en=1'], ['--en'], 'default', false, '1'],
[['app/console', 'foo:bar', '--env=dev', '', '--en=1'], ['--en'], 'default', false, '1'],
[['app/console', 'foo:bar', '--env', 'val'], '--env', 'default', false, 'val'],
[['app/console', 'foo:bar', '--env', 'val', '--dummy'], '--env', 'default', false, 'val'],
[['app/console', 'foo:bar', '--', '--env=dev'], '--env', 'default', false, 'dev'],
[['app/console', 'foo:bar', '--', '--env=dev'], '--env', 'default', true, 'default'],
];
}
public function testParseSingleDashAsArgument()
{
$input = new ArgvInput(array('cli.php', '-'));
$input->bind(new InputDefinition(array(new InputArgument('file'))));
$this->assertEquals(array('file' => '-'), $input->getArguments(), '->parse() parses single dash as an argument');
$input = new ArgvInput(['cli.php', '-']);
$input->bind(new InputDefinition([new InputArgument('file')]));
$this->assertEquals(['file' => '-'], $input->getArguments(), '->parse() parses single dash as an argument');
}
public function testParseOptionWithValueOptionalGivenEmptyAndRequiredArgument()
{
$input = new ArgvInput(array('cli.php', '--foo=', 'bar'));
$input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED))));
$this->assertEquals(array('foo' => null), $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->parse() parses required arguments');
$input = new ArgvInput(['cli.php', '--foo=', 'bar']);
$input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)]));
$this->assertEquals(['foo' => null], $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(['name' => 'bar'], $input->getArguments(), '->parse() parses required arguments');
$input = new ArgvInput(array('cli.php', '--foo=0', 'bar'));
$input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED))));
$this->assertEquals(array('foo' => '0'), $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->parse() parses required arguments');
$input = new ArgvInput(['cli.php', '--foo=0', 'bar']);
$input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::REQUIRED)]));
$this->assertEquals(['foo' => '0'], $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(['name' => 'bar'], $input->getArguments(), '->parse() parses required arguments');
}
public function testParseOptionWithValueOptionalGivenEmptyAndOptionalArgument()
{
$input = new ArgvInput(array('cli.php', '--foo=', 'bar'));
$input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::OPTIONAL))));
$this->assertEquals(array('foo' => null), $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->parse() parses optional arguments');
$input = new ArgvInput(['cli.php', '--foo=', 'bar']);
$input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::OPTIONAL)]));
$this->assertEquals(['foo' => null], $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(['name' => 'bar'], $input->getArguments(), '->parse() parses optional arguments');
$input = new ArgvInput(array('cli.php', '--foo=0', 'bar'));
$input->bind(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::OPTIONAL))));
$this->assertEquals(array('foo' => '0'), $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->parse() parses optional arguments');
$input = new ArgvInput(['cli.php', '--foo=0', 'bar']);
$input->bind(new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL), new InputArgument('name', InputArgument::OPTIONAL)]));
$this->assertEquals(['foo' => '0'], $input->getOptions(), '->parse() parses optional options with empty value as null');
$this->assertEquals(['name' => 'bar'], $input->getArguments(), '->parse() parses optional arguments');
}
}

View File

@@ -21,47 +21,47 @@ class ArrayInputTest extends TestCase
{
public function testGetFirstArgument()
{
$input = new ArrayInput(array());
$input = new ArrayInput([]);
$this->assertNull($input->getFirstArgument(), '->getFirstArgument() returns null if no argument were passed');
$input = new ArrayInput(array('name' => 'Fabien'));
$input = new ArrayInput(['name' => 'Fabien']);
$this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument');
$input = new ArrayInput(array('--foo' => 'bar', 'name' => 'Fabien'));
$input = new ArrayInput(['--foo' => 'bar', 'name' => 'Fabien']);
$this->assertEquals('Fabien', $input->getFirstArgument(), '->getFirstArgument() returns the first passed argument');
}
public function testHasParameterOption()
{
$input = new ArrayInput(array('name' => 'Fabien', '--foo' => 'bar'));
$input = new ArrayInput(['name' => 'Fabien', '--foo' => 'bar']);
$this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters');
$this->assertFalse($input->hasParameterOption('--bar'), '->hasParameterOption() returns false if an option is not present in the passed parameters');
$input = new ArrayInput(array('--foo'));
$input = new ArrayInput(['--foo']);
$this->assertTrue($input->hasParameterOption('--foo'), '->hasParameterOption() returns true if an option is present in the passed parameters');
$input = new ArrayInput(array('--foo', '--', '--bar'));
$input = new ArrayInput(['--foo', '--', '--bar']);
$this->assertTrue($input->hasParameterOption('--bar'), '->hasParameterOption() returns true if an option is present in the passed parameters');
$this->assertFalse($input->hasParameterOption('--bar', true), '->hasParameterOption() returns false if an option is present in the passed parameters after an end of options signal');
}
public function testGetParameterOption()
{
$input = new ArrayInput(array('name' => 'Fabien', '--foo' => 'bar'));
$input = new ArrayInput(['name' => 'Fabien', '--foo' => 'bar']);
$this->assertEquals('bar', $input->getParameterOption('--foo'), '->getParameterOption() returns the option of specified name');
$this->assertEquals('default', $input->getParameterOption('--bar', 'default'), '->getParameterOption() returns the default value if an option is not present in the passed parameters');
$input = new ArrayInput(array('Fabien', '--foo' => 'bar'));
$input = new ArrayInput(['Fabien', '--foo' => 'bar']);
$this->assertEquals('bar', $input->getParameterOption('--foo'), '->getParameterOption() returns the option of specified name');
$input = new ArrayInput(array('--foo', '--', '--bar' => 'woop'));
$input = new ArrayInput(['--foo', '--', '--bar' => 'woop']);
$this->assertEquals('woop', $input->getParameterOption('--bar'), '->getParameterOption() returns the correct value if an option is present in the passed parameters');
$this->assertEquals('default', $input->getParameterOption('--bar', 'default', true), '->getParameterOption() returns the default value if an option is present in the passed parameters after an end of options signal');
}
public function testParseArguments()
{
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name')]));
$this->assertEquals(array('name' => 'foo'), $input->getArguments(), '->parse() parses required arguments');
$this->assertEquals(['name' => 'foo'], $input->getArguments(), '->parse() parses required arguments');
}
/**
@@ -76,50 +76,50 @@ class ArrayInputTest extends TestCase
public function provideOptions()
{
return array(
array(
array('--foo' => 'bar'),
array(new InputOption('foo')),
array('foo' => 'bar'),
return [
[
['--foo' => 'bar'],
[new InputOption('foo')],
['foo' => 'bar'],
'->parse() parses long options',
),
array(
array('--foo' => 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
array('foo' => 'bar'),
],
[
['--foo' => 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')],
['foo' => 'bar'],
'->parse() parses long options with a default value',
),
array(
array(),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
array('foo' => 'default'),
],
[
[],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')],
['foo' => 'default'],
'->parse() uses the default value for long options with value optional which are not passed',
),
array(
array('--foo' => null),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
array('foo' => null),
],
[
['--foo' => null],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')],
['foo' => null],
'->parse() parses long options with a default value',
),
array(
array('-f' => 'bar'),
array(new InputOption('foo', 'f')),
array('foo' => 'bar'),
],
[
['-f' => 'bar'],
[new InputOption('foo', 'f')],
['foo' => 'bar'],
'->parse() parses short options',
),
array(
array('--' => null, '-f' => 'bar'),
array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')),
array('foo' => 'default'),
],
[
['--' => null, '-f' => 'bar'],
[new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL, '', 'default')],
['foo' => 'default'],
'->parse() does not parse opts after an end of options signal',
),
array(
array('--' => null),
array(),
array(),
],
[
['--' => null],
[],
[],
'->parse() does not choke on end of options signal',
),
);
],
];
}
/**
@@ -139,39 +139,39 @@ class ArrayInputTest extends TestCase
public function provideInvalidInput()
{
return array(
array(
array('foo' => 'foo'),
new InputDefinition(array(new InputArgument('name'))),
return [
[
['foo' => 'foo'],
new InputDefinition([new InputArgument('name')]),
'The "foo" argument does not exist.',
),
array(
array('--foo' => null),
new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))),
],
[
['--foo' => null],
new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)]),
'The "--foo" option requires a value.',
),
array(
array('--foo' => 'foo'),
],
[
['--foo' => 'foo'],
new InputDefinition(),
'The "--foo" option does not exist.',
),
array(
array('-o' => 'foo'),
],
[
['-o' => 'foo'],
new InputDefinition(),
'The "-o" option does not exist.',
),
);
],
];
}
public function testToString()
{
$input = new ArrayInput(array('-f' => null, '-b' => 'bar', '--foo' => 'b a z', '--lala' => null, 'test' => 'Foo', 'test2' => "A\nB'C"));
$input = new ArrayInput(['-f' => null, '-b' => 'bar', '--foo' => 'b a z', '--lala' => null, 'test' => 'Foo', 'test2' => "A\nB'C"]);
$this->assertEquals('-f -b=bar --foo='.escapeshellarg('b a z').' --lala Foo '.escapeshellarg("A\nB'C"), (string) $input);
$input = new ArrayInput(array('-b' => array('bval_1', 'bval_2'), '--f' => array('fval_1', 'fval_2')));
$input = new ArrayInput(['-b' => ['bval_1', 'bval_2'], '--f' => ['fval_1', 'fval_2']]);
$this->assertSame('-b=bval_1 -b=bval_2 --f=fval_1 --f=fval_2', (string) $input);
$input = new ArrayInput(array('array_arg' => array('val_1', 'val_2')));
$input = new ArrayInput(['array_arg' => ['val_1', 'val_2']]);
$this->assertSame('val_1 val_2', (string) $input);
}
}

View File

@@ -77,8 +77,8 @@ class InputArgumentTest extends TestCase
$this->assertEquals('another', $argument->getDefault(), '->setDefault() changes the default value');
$argument = new InputArgument('foo', InputArgument::OPTIONAL | InputArgument::IS_ARRAY);
$argument->setDefault(array(1, 2));
$this->assertEquals(array(1, 2), $argument->getDefault(), '->setDefault() changes the default value');
$argument->setDefault([1, 2]);
$this->assertEquals([1, 2], $argument->getDefault(), '->setDefault() changes the default value');
}
/**

View File

@@ -35,10 +35,10 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$this->assertEquals(array(), $definition->getArguments(), '__construct() creates a new InputDefinition object');
$this->assertEquals([], $definition->getArguments(), '__construct() creates a new InputDefinition object');
$definition = new InputDefinition(array($this->foo, $this->bar));
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '__construct() takes an array of InputArgument objects as its first argument');
$definition = new InputDefinition([$this->foo, $this->bar]);
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getArguments(), '__construct() takes an array of InputArgument objects as its first argument');
}
public function testConstructorOptions()
@@ -46,10 +46,10 @@ class InputDefinitionTest extends TestCase
$this->initializeOptions();
$definition = new InputDefinition();
$this->assertEquals(array(), $definition->getOptions(), '__construct() creates a new InputDefinition object');
$this->assertEquals([], $definition->getOptions(), '__construct() creates a new InputDefinition object');
$definition = new InputDefinition(array($this->foo, $this->bar));
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '__construct() takes an array of InputOption objects as its first argument');
$definition = new InputDefinition([$this->foo, $this->bar]);
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getOptions(), '__construct() takes an array of InputOption objects as its first argument');
}
public function testSetArguments()
@@ -57,11 +57,11 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$definition->setArguments(array($this->foo));
$this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->setArguments() sets the array of InputArgument objects');
$definition->setArguments(array($this->bar));
$definition->setArguments([$this->foo]);
$this->assertEquals(['foo' => $this->foo], $definition->getArguments(), '->setArguments() sets the array of InputArgument objects');
$definition->setArguments([$this->bar]);
$this->assertEquals(array('bar' => $this->bar), $definition->getArguments(), '->setArguments() clears all InputArgument objects');
$this->assertEquals(['bar' => $this->bar], $definition->getArguments(), '->setArguments() clears all InputArgument objects');
}
public function testAddArguments()
@@ -69,10 +69,10 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$definition->addArguments(array($this->foo));
$this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->addArguments() adds an array of InputArgument objects');
$definition->addArguments(array($this->bar));
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '->addArguments() does not clear existing InputArgument objects');
$definition->addArguments([$this->foo]);
$this->assertEquals(['foo' => $this->foo], $definition->getArguments(), '->addArguments() adds an array of InputArgument objects');
$definition->addArguments([$this->bar]);
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getArguments(), '->addArguments() does not clear existing InputArgument objects');
}
public function testAddArgument()
@@ -81,9 +81,9 @@ class InputDefinitionTest extends TestCase
$definition = new InputDefinition();
$definition->addArgument($this->foo);
$this->assertEquals(array('foo' => $this->foo), $definition->getArguments(), '->addArgument() adds a InputArgument object');
$this->assertEquals(['foo' => $this->foo], $definition->getArguments(), '->addArgument() adds a InputArgument object');
$definition->addArgument($this->bar);
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getArguments(), '->addArgument() adds a InputArgument object');
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getArguments(), '->addArgument() adds a InputArgument object');
}
/**
@@ -130,7 +130,7 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$definition->addArguments(array($this->foo));
$definition->addArguments([$this->foo]);
$this->assertEquals($this->foo, $definition->getArgument('foo'), '->getArgument() returns a InputArgument by its name');
}
@@ -143,7 +143,7 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$definition->addArguments(array($this->foo));
$definition->addArguments([$this->foo]);
$definition->getArgument('bar');
}
@@ -152,7 +152,7 @@ class InputDefinitionTest extends TestCase
$this->initializeArguments();
$definition = new InputDefinition();
$definition->addArguments(array($this->foo));
$definition->addArguments([$this->foo]);
$this->assertTrue($definition->hasArgument('foo'), '->hasArgument() returns true if a InputArgument exists for the given name');
$this->assertFalse($definition->hasArgument('bar'), '->hasArgument() returns false if a InputArgument exists for the given name');
@@ -182,28 +182,28 @@ class InputDefinitionTest extends TestCase
public function testGetArgumentDefaults()
{
$definition = new InputDefinition(array(
$definition = new InputDefinition([
new InputArgument('foo1', InputArgument::OPTIONAL),
new InputArgument('foo2', InputArgument::OPTIONAL, '', 'default'),
new InputArgument('foo3', InputArgument::OPTIONAL | InputArgument::IS_ARRAY),
// new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', array(1, 2)),
));
$this->assertEquals(array('foo1' => null, 'foo2' => 'default', 'foo3' => array()), $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');
// new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', [1, 2]),
]);
$this->assertEquals(['foo1' => null, 'foo2' => 'default', 'foo3' => []], $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');
$definition = new InputDefinition(array(
new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', array(1, 2)),
));
$this->assertEquals(array('foo4' => array(1, 2)), $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');
$definition = new InputDefinition([
new InputArgument('foo4', InputArgument::OPTIONAL | InputArgument::IS_ARRAY, '', [1, 2]),
]);
$this->assertEquals(['foo4' => [1, 2]], $definition->getArgumentDefaults(), '->getArgumentDefaults() return the default values for each argument');
}
public function testSetOptions()
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->setOptions() sets the array of InputOption objects');
$definition->setOptions(array($this->bar));
$this->assertEquals(array('bar' => $this->bar), $definition->getOptions(), '->setOptions() clears all InputOption objects');
$definition = new InputDefinition([$this->foo]);
$this->assertEquals(['foo' => $this->foo], $definition->getOptions(), '->setOptions() sets the array of InputOption objects');
$definition->setOptions([$this->bar]);
$this->assertEquals(['bar' => $this->bar], $definition->getOptions(), '->setOptions() clears all InputOption objects');
}
/**
@@ -214,8 +214,8 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition->setOptions(array($this->bar));
$definition = new InputDefinition([$this->foo]);
$definition->setOptions([$this->bar]);
$definition->getOptionForShortcut('f');
}
@@ -223,10 +223,10 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->addOptions() adds an array of InputOption objects');
$definition->addOptions(array($this->bar));
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '->addOptions() does not clear existing InputOption objects');
$definition = new InputDefinition([$this->foo]);
$this->assertEquals(['foo' => $this->foo], $definition->getOptions(), '->addOptions() adds an array of InputOption objects');
$definition->addOptions([$this->bar]);
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getOptions(), '->addOptions() does not clear existing InputOption objects');
}
public function testAddOption()
@@ -235,9 +235,9 @@ class InputDefinitionTest extends TestCase
$definition = new InputDefinition();
$definition->addOption($this->foo);
$this->assertEquals(array('foo' => $this->foo), $definition->getOptions(), '->addOption() adds a InputOption object');
$this->assertEquals(['foo' => $this->foo], $definition->getOptions(), '->addOption() adds a InputOption object');
$definition->addOption($this->bar);
$this->assertEquals(array('foo' => $this->foo, 'bar' => $this->bar), $definition->getOptions(), '->addOption() adds a InputOption object');
$this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getOptions(), '->addOption() adds a InputOption object');
}
/**
@@ -270,7 +270,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$this->assertEquals($this->foo, $definition->getOption('foo'), '->getOption() returns a InputOption by its name');
}
@@ -282,7 +282,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$definition->getOption('bar');
}
@@ -290,7 +290,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$this->assertTrue($definition->hasOption('foo'), '->hasOption() returns true if a InputOption exists for the given name');
$this->assertFalse($definition->hasOption('bar'), '->hasOption() returns false if a InputOption exists for the given name');
}
@@ -299,7 +299,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$this->assertTrue($definition->hasShortcut('f'), '->hasShortcut() returns true if a InputOption exists for the given shortcut');
$this->assertFalse($definition->hasShortcut('b'), '->hasShortcut() returns false if a InputOption exists for the given shortcut');
}
@@ -308,7 +308,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$this->assertEquals($this->foo, $definition->getOptionForShortcut('f'), '->getOptionForShortcut() returns a InputOption by its shortcut');
}
@@ -316,7 +316,7 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->multi));
$definition = new InputDefinition([$this->multi]);
$this->assertEquals($this->multi, $definition->getOptionForShortcut('m'), '->getOptionForShortcut() returns a InputOption by its shortcut');
$this->assertEquals($this->multi, $definition->getOptionForShortcut('mmm'), '->getOptionForShortcut() returns a InputOption by its shortcut');
}
@@ -329,30 +329,30 @@ class InputDefinitionTest extends TestCase
{
$this->initializeOptions();
$definition = new InputDefinition(array($this->foo));
$definition = new InputDefinition([$this->foo]);
$definition->getOptionForShortcut('l');
}
public function testGetOptionDefaults()
{
$definition = new InputDefinition(array(
$definition = new InputDefinition([
new InputOption('foo1', null, InputOption::VALUE_NONE),
new InputOption('foo2', null, InputOption::VALUE_REQUIRED),
new InputOption('foo3', null, InputOption::VALUE_REQUIRED, '', 'default'),
new InputOption('foo4', null, InputOption::VALUE_OPTIONAL),
new InputOption('foo5', null, InputOption::VALUE_OPTIONAL, '', 'default'),
new InputOption('foo6', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY),
new InputOption('foo7', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, '', array(1, 2)),
));
$defaults = array(
new InputOption('foo7', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, '', [1, 2]),
]);
$defaults = [
'foo1' => false,
'foo2' => null,
'foo3' => 'default',
'foo4' => null,
'foo5' => 'default',
'foo6' => array(),
'foo7' => array(1, 2),
);
'foo6' => [],
'foo7' => [1, 2],
];
$this->assertSame($defaults, $definition->getOptionDefaults(), '->getOptionDefaults() returns the default values for all options');
}
@@ -366,25 +366,25 @@ class InputDefinitionTest extends TestCase
public function getGetSynopsisData()
{
return array(
array(new InputDefinition(array(new InputOption('foo'))), '[--foo]', 'puts optional options in square brackets'),
array(new InputDefinition(array(new InputOption('foo', 'f'))), '[-f|--foo]', 'separates shortcut with a pipe'),
array(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_REQUIRED))), '[-f|--foo FOO]', 'uses shortcut as value placeholder'),
array(new InputDefinition(array(new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL))), '[-f|--foo [FOO]]', 'puts optional values in square brackets'),
return [
[new InputDefinition([new InputOption('foo')]), '[--foo]', 'puts optional options in square brackets'],
[new InputDefinition([new InputOption('foo', 'f')]), '[-f|--foo]', 'separates shortcut with a pipe'],
[new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_REQUIRED)]), '[-f|--foo FOO]', 'uses shortcut as value placeholder'],
[new InputDefinition([new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL)]), '[-f|--foo [FOO]]', 'puts optional values in square brackets'],
array(new InputDefinition(array(new InputArgument('foo', InputArgument::REQUIRED))), '<foo>', 'puts arguments in angle brackets'),
array(new InputDefinition(array(new InputArgument('foo'))), '[<foo>]', 'puts optional arguments in square brackets'),
array(new InputDefinition(array(new InputArgument('foo'), new InputArgument('bar'))), '[<foo> [<bar>]]', 'chains optional arguments inside brackets'),
array(new InputDefinition(array(new InputArgument('foo', InputArgument::IS_ARRAY))), '[<foo>...]', 'uses an ellipsis for array arguments'),
array(new InputDefinition(array(new InputArgument('foo', InputArgument::REQUIRED | InputArgument::IS_ARRAY))), '<foo>...', 'uses an ellipsis for required array arguments'),
[new InputDefinition([new InputArgument('foo', InputArgument::REQUIRED)]), '<foo>', 'puts arguments in angle brackets'],
[new InputDefinition([new InputArgument('foo')]), '[<foo>]', 'puts optional arguments in square brackets'],
[new InputDefinition([new InputArgument('foo'), new InputArgument('bar')]), '[<foo> [<bar>]]', 'chains optional arguments inside brackets'],
[new InputDefinition([new InputArgument('foo', InputArgument::IS_ARRAY)]), '[<foo>...]', 'uses an ellipsis for array arguments'],
[new InputDefinition([new InputArgument('foo', InputArgument::REQUIRED | InputArgument::IS_ARRAY)]), '<foo>...', 'uses an ellipsis for required array arguments'],
array(new InputDefinition(array(new InputOption('foo'), new InputArgument('foo', InputArgument::REQUIRED))), '[--foo] [--] <foo>', 'puts [--] between options and arguments'),
);
[new InputDefinition([new InputOption('foo'), new InputArgument('foo', InputArgument::REQUIRED)]), '[--foo] [--] <foo>', 'puts [--] between options and arguments'],
];
}
public function testGetShortSynopsis()
{
$definition = new InputDefinition(array(new InputOption('foo'), new InputOption('bar'), new InputArgument('cat')));
$definition = new InputDefinition([new InputOption('foo'), new InputOption('bar'), new InputArgument('cat')]);
$this->assertEquals('[options] [--] [<cat>]', $definition->getSynopsis(true), '->getSynopsis(true) groups options in [options]');
}

View File

@@ -39,7 +39,7 @@ class InputOptionTest extends TestCase
$this->assertEquals('f', $option->getShortcut(), '__construct() can take a shortcut as its second argument');
$option = new InputOption('foo', '-f|-ff|fff');
$this->assertEquals('f|ff|fff', $option->getShortcut(), '__construct() removes the leading - of the shortcuts');
$option = new InputOption('foo', array('f', 'ff', '-fff'));
$option = new InputOption('foo', ['f', 'ff', '-fff']);
$this->assertEquals('f|ff|fff', $option->getShortcut(), '__construct() removes the leading - of the shortcuts');
$option = new InputOption('foo');
$this->assertNull($option->getShortcut(), '__construct() makes the shortcut null by default');
@@ -132,7 +132,7 @@ class InputOptionTest extends TestCase
$this->assertNull($option->getDefault(), '->getDefault() returns null if no default value is configured');
$option = new InputOption('foo', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY);
$this->assertEquals(array(), $option->getDefault(), '->getDefault() returns an empty array if option is an array');
$this->assertEquals([], $option->getDefault(), '->getDefault() returns an empty array if option is an array');
$option = new InputOption('foo', null, InputOption::VALUE_NONE);
$this->assertFalse($option->getDefault(), '->getDefault() returns false if the option does not take a value');
@@ -147,8 +147,8 @@ class InputOptionTest extends TestCase
$this->assertEquals('another', $option->getDefault(), '->setDefault() changes the default value');
$option = new InputOption('foo', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY);
$option->setDefault(array(1, 2));
$this->assertEquals(array(1, 2), $option->getDefault(), '->setDefault() changes the default value');
$option->setDefault([1, 2]);
$this->assertEquals([1, 2], $option->getDefault(), '->setDefault() changes the default value');
}
/**

View File

@@ -21,30 +21,30 @@ class InputTest extends TestCase
{
public function testConstructor()
{
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name')]));
$this->assertEquals('foo', $input->getArgument('name'), '->__construct() takes a InputDefinition as an argument');
}
public function testOptions()
{
$input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'))));
$input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name')]));
$this->assertEquals('foo', $input->getOption('name'), '->getOption() returns the value for the given option');
$input->setOption('name', 'bar');
$this->assertEquals('bar', $input->getOption('name'), '->setOption() sets the value for a given option');
$this->assertEquals(array('name' => 'bar'), $input->getOptions(), '->getOptions() returns all option values');
$this->assertEquals(['name' => 'bar'], $input->getOptions(), '->getOptions() returns all option values');
$input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
$input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')]));
$this->assertEquals('default', $input->getOption('bar'), '->getOption() returns the default value for optional options');
$this->assertEquals(array('name' => 'foo', 'bar' => 'default'), $input->getOptions(), '->getOptions() returns all option values, even optional ones');
$this->assertEquals(['name' => 'foo', 'bar' => 'default'], $input->getOptions(), '->getOptions() returns all option values, even optional ones');
$input = new ArrayInput(array('--name' => 'foo', '--bar' => ''), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
$input = new ArrayInput(['--name' => 'foo', '--bar' => ''], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')]));
$this->assertEquals('', $input->getOption('bar'), '->getOption() returns null for options explicitly passed without value (or an empty value)');
$this->assertEquals(array('name' => 'foo', 'bar' => ''), $input->getOptions(), '->getOptions() returns all option values.');
$this->assertEquals(['name' => 'foo', 'bar' => ''], $input->getOptions(), '->getOptions() returns all option values.');
$input = new ArrayInput(array('--name' => 'foo', '--bar' => null), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
$input = new ArrayInput(['--name' => 'foo', '--bar' => null], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')]));
$this->assertNull($input->getOption('bar'), '->getOption() returns null for options explicitly passed without value (or an empty value)');
$this->assertEquals(array('name' => 'foo', 'bar' => null), $input->getOptions(), '->getOptions() returns all option values');
$this->assertEquals(['name' => 'foo', 'bar' => null], $input->getOptions(), '->getOptions() returns all option values');
}
/**
@@ -53,7 +53,7 @@ class InputTest extends TestCase
*/
public function testSetInvalidOption()
{
$input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
$input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')]));
$input->setOption('foo', 'bar');
}
@@ -63,22 +63,22 @@ class InputTest extends TestCase
*/
public function testGetInvalidOption()
{
$input = new ArrayInput(array('--name' => 'foo'), new InputDefinition(array(new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default'))));
$input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')]));
$input->getOption('foo');
}
public function testArguments()
{
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name')]));
$this->assertEquals('foo', $input->getArgument('name'), '->getArgument() returns the value for the given argument');
$input->setArgument('name', 'bar');
$this->assertEquals('bar', $input->getArgument('name'), '->setArgument() sets the value for a given argument');
$this->assertEquals(array('name' => 'bar'), $input->getArguments(), '->getArguments() returns all argument values');
$this->assertEquals(['name' => 'bar'], $input->getArguments(), '->getArguments() returns all argument values');
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')]));
$this->assertEquals('default', $input->getArgument('bar'), '->getArgument() returns the default value for optional arguments');
$this->assertEquals(array('name' => 'foo', 'bar' => 'default'), $input->getArguments(), '->getArguments() returns all argument values, even optional ones');
$this->assertEquals(['name' => 'foo', 'bar' => 'default'], $input->getArguments(), '->getArguments() returns all argument values, even optional ones');
}
/**
@@ -87,7 +87,7 @@ class InputTest extends TestCase
*/
public function testSetInvalidArgument()
{
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')]));
$input->setArgument('foo', 'bar');
}
@@ -97,7 +97,7 @@ class InputTest extends TestCase
*/
public function testGetInvalidArgument()
{
$input = new ArrayInput(array('name' => 'foo'), new InputDefinition(array(new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default'))));
$input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')]));
$input->getArgument('foo');
}
@@ -107,8 +107,8 @@ class InputTest extends TestCase
*/
public function testValidateWithMissingArguments()
{
$input = new ArrayInput(array());
$input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::REQUIRED))));
$input = new ArrayInput([]);
$input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED)]));
$input->validate();
}
@@ -118,22 +118,22 @@ class InputTest extends TestCase
*/
public function testValidateWithMissingRequiredArguments()
{
$input = new ArrayInput(array('bar' => 'baz'));
$input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::REQUIRED), new InputArgument('bar', InputArgument::OPTIONAL))));
$input = new ArrayInput(['bar' => 'baz']);
$input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED), new InputArgument('bar', InputArgument::OPTIONAL)]));
$input->validate();
}
public function testValidate()
{
$input = new ArrayInput(array('name' => 'foo'));
$input->bind(new InputDefinition(array(new InputArgument('name', InputArgument::REQUIRED))));
$input = new ArrayInput(['name' => 'foo']);
$input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED)]));
$this->assertNull($input->validate());
}
public function testSetGetInteractive()
{
$input = new ArrayInput(array());
$input = new ArrayInput([]);
$this->assertTrue($input->isInteractive(), '->isInteractive() returns whether the input should be interactive or not');
$input->setInteractive(false);
$this->assertFalse($input->isInteractive(), '->setInteractive() changes the interactive flag');
@@ -141,7 +141,7 @@ class InputTest extends TestCase
public function testSetGetStream()
{
$input = new ArrayInput(array());
$input = new ArrayInput([]);
$stream = fopen('php://memory', 'r+', false);
$input->setStream($stream);
$this->assertSame($stream, $input->getStream());

View File

@@ -33,7 +33,7 @@ class StringInputTest extends TestCase
public function testInputOptionWithGivenString()
{
$definition = new InputDefinition(
array(new InputOption('foo', null, InputOption::VALUE_REQUIRED))
[new InputOption('foo', null, InputOption::VALUE_REQUIRED)]
);
// call to bind
@@ -44,33 +44,33 @@ class StringInputTest extends TestCase
public function getTokenizeData()
{
return array(
array('', array(), '->tokenize() parses an empty string'),
array('foo', array('foo'), '->tokenize() parses arguments'),
array(' foo bar ', array('foo', 'bar'), '->tokenize() ignores whitespaces between arguments'),
array('"quoted"', array('quoted'), '->tokenize() parses quoted arguments'),
array("'quoted'", array('quoted'), '->tokenize() parses quoted arguments'),
array("'a\rb\nc\td'", array("a\rb\nc\td"), '->tokenize() parses whitespace chars in strings'),
array("'a'\r'b'\n'c'\t'd'", array('a', 'b', 'c', 'd'), '->tokenize() parses whitespace chars between args as spaces'),
array('\"quoted\"', array('"quoted"'), '->tokenize() parses escaped-quoted arguments'),
array("\'quoted\'", array('\'quoted\''), '->tokenize() parses escaped-quoted arguments'),
array('-a', array('-a'), '->tokenize() parses short options'),
array('-azc', array('-azc'), '->tokenize() parses aggregated short options'),
array('-awithavalue', array('-awithavalue'), '->tokenize() parses short options with a value'),
array('-a"foo bar"', array('-afoo bar'), '->tokenize() parses short options with a value'),
array('-a"foo bar""foo bar"', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
array('-a\'foo bar\'', array('-afoo bar'), '->tokenize() parses short options with a value'),
array('-a\'foo bar\'\'foo bar\'', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
array('-a\'foo bar\'"foo bar"', array('-afoo barfoo bar'), '->tokenize() parses short options with a value'),
array('--long-option', array('--long-option'), '->tokenize() parses long options'),
array('--long-option=foo', array('--long-option=foo'), '->tokenize() parses long options with a value'),
array('--long-option="foo bar"', array('--long-option=foo bar'), '->tokenize() parses long options with a value'),
array('--long-option="foo bar""another"', array('--long-option=foo baranother'), '->tokenize() parses long options with a value'),
array('--long-option=\'foo bar\'', array('--long-option=foo bar'), '->tokenize() parses long options with a value'),
array("--long-option='foo bar''another'", array('--long-option=foo baranother'), '->tokenize() parses long options with a value'),
array("--long-option='foo bar'\"another\"", array('--long-option=foo baranother'), '->tokenize() parses long options with a value'),
array('foo -a -ffoo --long bar', array('foo', '-a', '-ffoo', '--long', 'bar'), '->tokenize() parses when several arguments and options'),
);
return [
['', [], '->tokenize() parses an empty string'],
['foo', ['foo'], '->tokenize() parses arguments'],
[' foo bar ', ['foo', 'bar'], '->tokenize() ignores whitespaces between arguments'],
['"quoted"', ['quoted'], '->tokenize() parses quoted arguments'],
["'quoted'", ['quoted'], '->tokenize() parses quoted arguments'],
["'a\rb\nc\td'", ["a\rb\nc\td"], '->tokenize() parses whitespace chars in strings'],
["'a'\r'b'\n'c'\t'd'", ['a', 'b', 'c', 'd'], '->tokenize() parses whitespace chars between args as spaces'],
['\"quoted\"', ['"quoted"'], '->tokenize() parses escaped-quoted arguments'],
["\'quoted\'", ['\'quoted\''], '->tokenize() parses escaped-quoted arguments'],
['-a', ['-a'], '->tokenize() parses short options'],
['-azc', ['-azc'], '->tokenize() parses aggregated short options'],
['-awithavalue', ['-awithavalue'], '->tokenize() parses short options with a value'],
['-a"foo bar"', ['-afoo bar'], '->tokenize() parses short options with a value'],
['-a"foo bar""foo bar"', ['-afoo barfoo bar'], '->tokenize() parses short options with a value'],
['-a\'foo bar\'', ['-afoo bar'], '->tokenize() parses short options with a value'],
['-a\'foo bar\'\'foo bar\'', ['-afoo barfoo bar'], '->tokenize() parses short options with a value'],
['-a\'foo bar\'"foo bar"', ['-afoo barfoo bar'], '->tokenize() parses short options with a value'],
['--long-option', ['--long-option'], '->tokenize() parses long options'],
['--long-option=foo', ['--long-option=foo'], '->tokenize() parses long options with a value'],
['--long-option="foo bar"', ['--long-option=foo bar'], '->tokenize() parses long options with a value'],
['--long-option="foo bar""another"', ['--long-option=foo baranother'], '->tokenize() parses long options with a value'],
['--long-option=\'foo bar\'', ['--long-option=foo bar'], '->tokenize() parses long options with a value'],
["--long-option='foo bar''another'", ['--long-option=foo baranother'], '->tokenize() parses long options with a value'],
["--long-option='foo bar'\"another\"", ['--long-option=foo baranother'], '->tokenize() parses long options with a value'],
['foo -a -ffoo --long bar', ['foo', '-a', '-ffoo', '--long', 'bar'], '->tokenize() parses when several arguments and options'],
];
}
public function testToString()

View File

@@ -39,7 +39,7 @@ class ConsoleLoggerTest extends TestCase
{
$this->output = new DummyOutput(OutputInterface::VERBOSITY_VERBOSE);
return new ConsoleLogger($this->output, array(
return new ConsoleLogger($this->output, [
LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
@@ -48,7 +48,7 @@ class ConsoleLoggerTest extends TestCase
LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
LogLevel::INFO => OutputInterface::VERBOSITY_NORMAL,
LogLevel::DEBUG => OutputInterface::VERBOSITY_NORMAL,
));
]);
}
/**
@@ -64,7 +64,7 @@ class ConsoleLoggerTest extends TestCase
/**
* @dataProvider provideOutputMappingParams
*/
public function testOutputMapping($logLevel, $outputVerbosity, $isOutput, $addVerbosityLevelMap = array())
public function testOutputMapping($logLevel, $outputVerbosity, $isOutput, $addVerbosityLevelMap = [])
{
$out = new BufferedOutput($outputVerbosity);
$logger = new ConsoleLogger($out, $addVerbosityLevelMap);
@@ -75,22 +75,22 @@ class ConsoleLoggerTest extends TestCase
public function provideOutputMappingParams()
{
$quietMap = array(LogLevel::EMERGENCY => OutputInterface::VERBOSITY_QUIET);
$quietMap = [LogLevel::EMERGENCY => OutputInterface::VERBOSITY_QUIET];
return array(
array(LogLevel::EMERGENCY, OutputInterface::VERBOSITY_NORMAL, true),
array(LogLevel::WARNING, OutputInterface::VERBOSITY_NORMAL, true),
array(LogLevel::INFO, OutputInterface::VERBOSITY_NORMAL, false),
array(LogLevel::DEBUG, OutputInterface::VERBOSITY_NORMAL, false),
array(LogLevel::INFO, OutputInterface::VERBOSITY_VERBOSE, false),
array(LogLevel::INFO, OutputInterface::VERBOSITY_VERY_VERBOSE, true),
array(LogLevel::DEBUG, OutputInterface::VERBOSITY_VERY_VERBOSE, false),
array(LogLevel::DEBUG, OutputInterface::VERBOSITY_DEBUG, true),
array(LogLevel::ALERT, OutputInterface::VERBOSITY_QUIET, false),
array(LogLevel::EMERGENCY, OutputInterface::VERBOSITY_QUIET, false),
array(LogLevel::ALERT, OutputInterface::VERBOSITY_QUIET, false, $quietMap),
array(LogLevel::EMERGENCY, OutputInterface::VERBOSITY_QUIET, true, $quietMap),
);
return [
[LogLevel::EMERGENCY, OutputInterface::VERBOSITY_NORMAL, true],
[LogLevel::WARNING, OutputInterface::VERBOSITY_NORMAL, true],
[LogLevel::INFO, OutputInterface::VERBOSITY_NORMAL, false],
[LogLevel::DEBUG, OutputInterface::VERBOSITY_NORMAL, false],
[LogLevel::INFO, OutputInterface::VERBOSITY_VERBOSE, false],
[LogLevel::INFO, OutputInterface::VERBOSITY_VERY_VERBOSE, true],
[LogLevel::DEBUG, OutputInterface::VERBOSITY_VERY_VERBOSE, false],
[LogLevel::DEBUG, OutputInterface::VERBOSITY_DEBUG, true],
[LogLevel::ALERT, OutputInterface::VERBOSITY_QUIET, false],
[LogLevel::EMERGENCY, OutputInterface::VERBOSITY_QUIET, false],
[LogLevel::ALERT, OutputInterface::VERBOSITY_QUIET, false, $quietMap],
[LogLevel::EMERGENCY, OutputInterface::VERBOSITY_QUIET, true, $quietMap],
];
}
public function testHasErrored()
@@ -117,28 +117,28 @@ class ConsoleLoggerTest extends TestCase
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, array('user' => 'Bob'));
$logger->log($level, $message, array('user' => 'Bob'));
$logger->{$level}($message, ['user' => 'Bob']);
$logger->log($level, $message, ['user' => 'Bob']);
$expected = array(
$expected = [
$level.' message of level '.$level.' with context: Bob',
$level.' message of level '.$level.' with context: Bob',
);
];
$this->assertEquals($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
return [
LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
];
}
/**
@@ -153,56 +153,56 @@ class ConsoleLoggerTest extends TestCase
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
$expected = array('info {Message {nothing} Bob Bar a}');
$expected = ['info {Message {nothing} Bob Bar a}'];
$this->assertEquals($expected, $this->getLogs());
}
public function testObjectCastToString()
{
if (method_exists($this, 'createPartialMock')) {
$dummy = $this->createPartialMock('Symfony\Component\Console\Tests\Logger\DummyTest', array('__toString'));
$dummy = $this->createPartialMock('Symfony\Component\Console\Tests\Logger\DummyTest', ['__toString']);
} else {
$dummy = $this->getMock('Symfony\Component\Console\Tests\Logger\DummyTest', array('__toString'));
$dummy = $this->getMock('Symfony\Component\Console\Tests\Logger\DummyTest', ['__toString']);
}
$dummy->method('__toString')->will($this->returnValue('DUMMY'));
$this->getLogger()->warning($dummy);
$expected = array('warning DUMMY');
$expected = ['warning DUMMY'];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextCanContainAnything()
{
$context = array(
$context = [
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => new DummyTest()),
'nested' => ['with object' => new DummyTest()],
'object' => new \DateTime(),
'resource' => fopen('php://memory', 'r'),
);
];
$this->getLogger()->warning('Crazy context data', $context);
$expected = array('warning Crazy context data');
$expected = ['warning Crazy context data'];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$logger->warning('Random message', ['exception' => 'oops']);
$logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
$expected = array(
$expected = [
'warning Random message',
'critical Uncaught Exception!',
);
];
$this->assertEquals($expected, $this->getLogs());
}
}

Some files were not shown because too many files have changed in this diff Show More