merged branch romainneutron/process-builder-prefix (PR #7584)

This PR was merged into the master branch.

Discussion
----------

[Process] Add ProcessBuilder::setPrefix method

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT

This introduce a new feature for the `ProcessBuilder` that allows to prefix all generated `Process` commands with a custom value.
This is mostly useful when dealing with binary drivers.

Use case :

```php
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;

class PhpDriver
{
    private $pb;

    public function __construct(ProcessBuilder $pb)
    {
        $this->pb = $pb;
    }

    public function getInfos()
    {
        return $this->execute('-i');
    }

    public function getVersion()
    {
        return $this->execute('-v');
    }

    private function execute(array $arguments)
    {
        return $this
            ->pb
            ->setArguments($arguments)
            ->createProcess()
            ->run()
            ->getOutput();
    }
}

$finder = new ExecutableFinder();

$pb = new ProcessBuilder();
$pb->setPrefix($finder->find('php'));

$driver = new PhpDriver($pb);
$driver->getVersion();
$driver->getInfos();
```

Commits
-------

cab53ee Add ProcessBuilder::setPrefix method
This commit is contained in:
Fabien Potencier 2013-04-20 18:25:02 +02:00
commit 6290220f0a
2 changed files with 31 additions and 1 deletions

View File

@ -28,6 +28,7 @@ class ProcessBuilder
private $timeout;
private $options;
private $inheritEnv;
private $prefix;
public function __construct(array $arguments = array())
{
@ -58,6 +59,22 @@ class ProcessBuilder
return $this;
}
/**
* Adds an unescaped prefix to the command string.
*
* The prefix is preserved when reseting arguments.
*
* @param string $prefix A command prefix
*
* @return ProcessBuilder
*/
public function setPrefix($prefix)
{
$this->prefix = $prefix;
return $this;
}
/**
* @param array $arguments
*
@ -143,7 +160,8 @@ class ProcessBuilder
$options = $this->options;
$script = implode(' ', array_map('escapeshellarg', $this->arguments));
$script = ($this->prefix ? escapeshellarg($this->prefix) . ' ' : '')
. implode(' ', array_map('escapeshellarg', $this->arguments));
if ($this->inheritEnv) {
$env = $this->env ? $this->env + $_ENV : null;

View File

@ -115,4 +115,16 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$this->assertContains("second", $proc->getCommandLine());
}
public function testPrefixIsPrependedToAllGeneratedProcess()
{
$pb = new ProcessBuilder();
$pb->setPrefix('/usr/bin/php');
$proc = $pb->setArguments(array('-v'))->getProcess();
$this->assertEquals("'/usr/bin/php' '-v'", $proc->getCommandLine());
$proc = $pb->setArguments(array('-i'))->getProcess();
$this->assertEquals("'/usr/bin/php' '-i'", $proc->getCommandLine());
}
}