Search code examples
command-linecommandsymfony4

Symfony 4 Component Process pass arguments for command


Symfony Component Process

/**
     * @param array          $command The command to run and its arguments listed as separate entries
     * @param string|null    $cwd     The working directory or null to use the working dir of the current PHP process
     * @param array|null     $env     The environment variables or null to use the same environment as the current PHP process
     * @param mixed|null     $input   The input as stream resource, scalar or \Traversable, or null for no input
     * @param int|float|null $timeout The timeout in seconds or null to disable
     *
     * @throws LogicException When proc_open is not installed
     */
    public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
    { .. }

I have created a command and I use the component Process in my controller.
When I try to run Process I get a ProcessFailException
The command "app:load-file foo bar foobar" failed
Exit Code: 1(General error)
.. ErrorOutput: The filename, directory name, or volume label syntax is incorrect

use Symfony\Component\Process\Process;

..
public function loadFile(KernelInterface $kernel) 
{
   $argument1 = 'foo';
   $argument2 = 'bar';
   $argument3 = 'foobar';
   $rootDir = $kernel->getProjectDir();
   $process = new Process(array(
      $rootDir . '/bin/console app:load-file',
      $argument1,
      $argument2,
      $argument3
   ));
   
   $process->mustRun();
}

What is the correct syntax to run the command from the controller ?
/* *@param array $command The command to run and its arguments listed as separate entries
public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60) { .. }


Solution

  • $cwd is the second parameter of the constructor.

       $argument1 = 'foo';
       $argument2 = 'bar';
       $argument3 = 'foobar';
       $rootDir = $kernel->getProjectDir();
       $process = new Process(
          "bin/console app:load-file $argument1 $argument2 $argument3",
          $rootDir
       );
    
       try {
          $process->mustRun();
       } catch(ProcessFailedException $e) {
          echo $e->getMessage();
       }