Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Console] Misuse of ArgvInput with arrays needs a better error handling #53836

Closed
@symfonyaml

Description

@symfonyaml

Symfony version(s) affected

5.4

Description

Misuse of ArgvInput with array in $argv returns different PHP fatal errors, instead of some DX with a nice exception explaining the situation.

The misuse :

$argv = [
    'script',
    ['array'], // <------ this is the misuse bit
];
$input = ArgvInput($argv);

Calling bind() method :

Uncaught TypeError: Argument 1 passed to ArgvInput::parseToken() must be of the type string, array given

Calling hasParameterOption() or getParameterOption() methods :

Uncaught TypeError: Argument 1 passed to str_starts_with() must be of the type string or null, array given

How to reproduce

  • Create a new directory
    mkdir ./reproduce-error-argv-input-bug
    cd ./reproduce-error-argv-input-bug
    
  • Install the symfony/console repo
    composer require symfony/console
    
  • Create the PHP script test.php to throw the error
    <?php
    require_once __DIR__.'/vendor/autoload.php';
    $argv = [
        'script',
        ['array'], // <------ this is the misuse bit
    ];
    $input = new \Symfony\Component\Console\Input\ArgvInput($argv);
    $inputDefinition = new \Symfony\Component\Console\Input\InputDefinition();
    // comment any of the following method calls to get the errors :
    // error 1 (Argument 1 passed to ArgvInput::parseToken() must be of the type string, array given)
    $input->bind($inputDefinition);
    // error 2 (Argument 1 passed to str_starts_with() must be of the type string or null, array given)
    $input->hasParameterOption(['--ansi'], true);
    $input->getParameterOption(['--ansi']);
  • Run the PHP script
    php test.php
    

Possible Solution

Maybe we should prevent to pass array values in the ArgvInput constructor like :

class ArgvInput extends Input
{
    public function __construct(array $argv = null, InputDefinition $definition = null)
    {
        $argv = $argv ?? $_SERVER['argv'] ?? [];

        if (array_filter($argv, 'is_array')) {
            throw new RuntimeException('Argument values expected to be scalars, got array.');
        }
    }
    // ...

Additional Context

There is a kind of related issue with ArrayInput by @niklaswolf : #52580

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions