Skip to content

[WIP][Process] Add commandline parameter binding support #12488

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletions src/Symfony/Component/Process/CommandLine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Process;

use Symfony\Component\Process\Exception\InvalidArgumentException;

/**
* @author Romain Neutron <imprec@gmail.com>
*
* @api
*/
class CommandLine
{
const DEFAULT_PLACEHOLDER = '{}';
private $commandLine;
private $placeholder;
private $disabled = false;

public function __construct($commandLine, $placeholder = self::DEFAULT_PLACEHOLDER)
{
$this->commandLine = (string) $commandLine;
$this->setPlaceholder($placeholder);
}

/**
* @return string
*
* @api
*/
public function getCommandLine()
{
return $this->commandLine;
}

/**
* @param string $commandLine
*
* @return CommandLine
*
* @api
*/
public function setCommandLine($commandLine)
{
$this->commandLine = $commandLine;

return $this;
}

/**
* @return string
*
* @api
*/
public function getPlaceholder()
{
return $this->placeholder;
}

/**
* @param string $placeholder
*
* @return CommandLine
*
* @throws InvalidArgumentException
*
* @api
*/
public function setPlaceholder($placeholder)
{
if (null !== $placeholder && 0 === strlen($placeholder)) {
throw new InvalidArgumentException('Invalid placeholder');
}

$this->placeholder = $placeholder;

return $this;
}

/**
* @param array $parameters
*
* @return string
*
* @throws InvalidArgumentException
*
* @api
*/
public function prepare(array $parameters)
{
if ($this->disabled) {
return $this->commandLine;
}

$placeholders = $this->countPlaceholders(array_filter(array_keys($parameters), function ($value) { return !is_numeric($value); }));

if (count($parameters) !== $placeholders) {
throw new InvalidArgumentException('Invalid number of bound parameters');
}

if (0 === $placeholders) {
return $this->commandLine;
}

$command = '';
$offset = 0;

foreach ($parameters as $key => $value) {
$placeholder = is_numeric($key) ? $this->placeholder : $key;

$pos = strpos($this->commandLine, $placeholder, $offset);
$command .= substr($this->commandLine, $offset, $pos - $offset);
$offset = $pos + strlen($placeholder);
$command .= $this->escape($value);
}
$command .= substr($this->commandLine, $offset);

return $command;
}

/**
* @internal
*/
public function disableArguments()
{
$this->disabled = true;
}

/**
* @param array $placeholders
*
* @return int
*/
private function countPlaceholders(array $placeholders)
{
if (null === $this->placeholder && 0 === count($placeholders)) {
return 0;
}

$total = preg_match_all('#' . preg_quote($this->placeholder, '#') . '#', $this->commandLine, $matches);

foreach ($placeholders as $placeholder) {
$total += preg_match_all('#' . preg_quote($placeholder, '#') . '#', $this->commandLine, $matches);
}

return $total;
}

/**
* @param string $string
*
* @return string
*/
private function escape($string)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO, this method is not needed. Use the static util directly

{
return ProcessUtils::escapeArgument($string);
}
}
6 changes: 3 additions & 3 deletions src/Symfony/Component/Process/PhpProcess.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,15 @@ public function setPhpBinary($php)
/**
* {@inheritdoc}
*/
public function start($callback = null)
public function start($callback = null, array $parameters = array())
{
if (null === $this->getCommandLine()) {
if ('' === $this->getCommandLine()) {
if (false === $php = $this->executableFinder->find()) {
throw new RuntimeException('Unable to find the PHP executable.');
}
$this->setCommandLine($php);
}

parent::start($callback);
parent::start($callback, $parameters);
}
}
43 changes: 28 additions & 15 deletions src/Symfony/Component/Process/Process.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class Process
const TIMEOUT_PRECISION = 0.2;

private $callback;
/** @var CommandLine */
private $commandline;
private $cwd;
private $env;
Expand Down Expand Up @@ -148,7 +149,7 @@ public function __construct($commandline, $cwd = null, array $env = null, $input
throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
}

$this->commandline = $commandline;
$this->setCommandLine($commandline);
$this->cwd = $cwd;

// on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
Expand Down Expand Up @@ -194,18 +195,20 @@ public function __clone()
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $parameters
*
* @return int The exit status code
*
* @throws RuntimeException When process can't be launched
* @throws RuntimeException When process stopped after receiving signal
* @throws LogicException In case a callback is provided and output has been disabled
* @throws InvalidArgumentException
*
* @api
*/
public function run($callback = null)
public function run($callback = null, array $parameters = array())
{
$this->start($callback);
$this->start($callback, $parameters);

return $this->wait();
}
Expand Down Expand Up @@ -253,14 +256,16 @@ public function mustRun($callback = null)
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $parameters
*
* @return Process The process itself
*
* @throws RuntimeException When process can't be launched
* @throws RuntimeException When process is already running
* @throws LogicException In case a callback is provided and output has been disabled
* @throws InvalidArgurmentException
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo here

*/
public function start($callback = null)
public function start($callback = null, array $parameters = array())
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
Expand All @@ -272,9 +277,8 @@ public function start($callback = null)
$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$descriptors = $this->getDescriptors();

$commandline = $this->commandline;
$commandline = $this->commandline->prepare($parameters);
list($descriptors, $commandline) = $this->getDescriptors($commandline);

if (defined('PHP_WINDOWS_VERSION_BUILD') && $this->enhanceWindowsCompatibility) {
$commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
Expand Down Expand Up @@ -310,22 +314,24 @@ public function start($callback = null)
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $parameters
*
* @return Process The new process
*
* @throws RuntimeException When process can't be launched
* @throws RuntimeException When process is already running
* @throws InvalidArgumentException
*
* @see start()
*/
public function restart($callback = null)
public function restart($callback = null, array $parameters = array())
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}

$process = clone $this;
$process->start($callback);
$process->start($callback, $parameters);

return $process;
}
Expand Down Expand Up @@ -843,11 +849,13 @@ public function addErrorOutput($line)
/**
* Gets the command line to be executed.
*
* @return string The command to execute
* @param bool $asObject
*
* @return string|CommandLine The command to execute
*/
public function getCommandLine()
public function getCommandLine($asObject = false)
{
return $this->commandline;
return $asObject ? $this->commandline : $this->commandline->getCommandLine();
}

/**
Expand All @@ -859,6 +867,9 @@ public function getCommandLine()
*/
public function setCommandLine($commandline)
{
if (!$commandline instanceof CommandLine) {
$commandline = new CommandLine($commandline);
}
$this->commandline = $commandline;

return $this;
Expand Down Expand Up @@ -1245,9 +1256,11 @@ public static function isPtySupported()
/**
* Creates the descriptors needed by the proc_open.
*
* @param string $commandline
*
* @return array
*/
private function getDescriptors()
private function getDescriptors($commandline)
{
if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->processPipes = WindowsPipes::create($this, $this->input);
Expand All @@ -1260,10 +1273,10 @@ private function getDescriptors()
// last exit code is output on the fourth pipe and caught to work around --enable-sigchild
$descriptors = array_merge($descriptors, array(array('pipe', 'w')));

$this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
$commandline = '('.$commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
}

return $descriptors;
return array($descriptors, $commandline);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ public function testProcessThrowsExceptionWhenExternallySignaled()

$termSignal = defined('SIGKILL') ? SIGKILL : 9;

$process = $this->getProcess('exec php -r "while (true) {}"');
$process = $this->getProcess('exec php -r "while (true) { }"');
$process->start();
posix_kill($process->getPid(), $termSignal);

Expand Down
31 changes: 31 additions & 0 deletions src/Symfony/Component/Process/Tests/CommandLineTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Symfony\Component\Process\Tests;

use Symfony\Component\Process\CommandLine;

class CommandLineTest extends \PHPUnit_Framework_TestCase
{
/**
* @dataProvider provideVariousCommandsAndParameters
*/
public function testCommandLinePrepare($commandLine, $placeholder, $parameters, $expected)
{
$commandLine = new CommandLine($commandLine, $placeholder);
$this->assertSame($expected, $commandLine->prepare($parameters));
}

public function provideVariousCommandsAndParameters()
{
return array(
array("{} | grep {}", CommandLine::DEFAULT_PLACEHOLDER, array('/usr/bin/ls', 'symfony'), "'/usr/bin/ls' | grep 'symfony'"),
array("## | grep ##", '##', array('/usr/bin/ls', 'symfony'), "'/usr/bin/ls' | grep 'symfony'"),
array("{ } | grep {}", CommandLine::DEFAULT_PLACEHOLDER, array('symfony'), "{ } | grep 'symfony'"),
array("exec {} | grep {} > symfony.log", CommandLine::DEFAULT_PLACEHOLDER, array('/usr/bin/ls', 'symfony'), "exec '/usr/bin/ls' | grep 'symfony' > symfony.log"),
array("exec ## | grep ## > symfony.log", '##', array('/usr/bin/ls', 'symfony'), "exec '/usr/bin/ls' | grep 'symfony' > symfony.log"),
array("exec Ê™ | grep Ê™ > symfony.log", 'Ê™', array('/usr/bin/ls', 'symfony'), "exec '/usr/bin/ls' | grep 'symfony' > symfony.log"),
array("exec {} | grep {} > symfony.log", CommandLine::DEFAULT_PLACEHOLDER, array('i\'m', 'symfony'), "exec 'i'\\''m' | grep 'symfony' > symfony.log"),
array("{} | grep {}", CommandLine::DEFAULT_PLACEHOLDER, array('/usr/bin/ls', 'symfony'), "'/usr/bin/ls' | grep 'symfony'"),
);
}
}