composer update

This commit is contained in:
Manish Verma
2018-12-05 10:50:52 +05:30
parent 9eabcacfa7
commit 4addd1e9c6
3328 changed files with 156676 additions and 138988 deletions

View File

@@ -1,6 +1,15 @@
CHANGELOG
=========
4.2.0
-----
* added the `Process::fromShellCommandline()` to run commands in a shell wrapper
* deprecated passing a command as string when creating a `Process` instance
* deprecated the `Process::setCommandline()` and the `PhpProcess::setPhpBinary()` methods
* added the `Process::waitUntil()` method to wait for the process only for a
specific output, then continue the normal execution of your application
4.1.0
-----

View File

@@ -16,6 +16,6 @@ namespace Symfony\Component\Process\Exception;
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface ExceptionInterface
interface ExceptionInterface extends \Throwable
{
}

View File

@@ -20,7 +20,7 @@ use Symfony\Component\Process\Exception\RuntimeException;
*/
class InputStream implements \IteratorAggregate
{
/** @var null|callable */
/** @var callable|null */
private $onEmpty = null;
private $input = array();
private $open = true;
@@ -36,8 +36,8 @@ class InputStream implements \IteratorAggregate
/**
* Appends an input to the write buffer.
*
* @param resource|string|int|float|bool|\Traversable|null The input to append as scalar,
* stream resource or \Traversable
* @param resource|string|int|float|bool|\Traversable|null $input The input to append as scalar,
* stream resource or \Traversable
*/
public function write($input)
{
@@ -78,9 +78,7 @@ class InputStream implements \IteratorAggregate
$current = array_shift($this->input);
if ($current instanceof \Iterator) {
foreach ($current as $cur) {
yield $cur;
}
yield from $current;
} else {
yield $current;
}

View File

@@ -37,7 +37,14 @@ class PhpExecutableFinder
{
if ($php = getenv('PHP_BINARY')) {
if (!is_executable($php)) {
return false;
$command = '\\' === \DIRECTORY_SEPARATOR ? 'where' : 'command -v';
if ($php = strtok(exec($command.' '.escapeshellarg($php)), PHP_EOL)) {
if (!is_executable($php)) {
return false;
}
} else {
return false;
}
}
return $php;

View File

@@ -16,9 +16,9 @@ use Symfony\Component\Process\Exception\RuntimeException;
/**
* PhpProcess runs a PHP script in an independent process.
*
* $p = new PhpProcess('<?php echo "foo"; ?>');
* $p->run();
* print $p->getOutput()."\n";
* $p = new PhpProcess('<?php echo "foo"; ?>');
* $p->run();
* print $p->getOutput()."\n";
*
* @author Fabien Potencier <fabien@symfony.com>
*/
@@ -29,11 +29,12 @@ class PhpProcess extends Process
* @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 int $timeout The timeout in seconds
* @param array|null $php Path to the PHP binary to use with any additional arguments
*/
public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60)
public function __construct(string $script, string $cwd = null, array $env = null, int $timeout = 60, array $php = null)
{
$executableFinder = new PhpExecutableFinder();
if (false === $php = $executableFinder->find(false)) {
if (false === $php = $php ?? $executableFinder->find(false)) {
$php = null;
} else {
$php = array_merge(array($php), $executableFinder->findArguments());
@@ -51,9 +52,13 @@ class PhpProcess extends Process
/**
* Sets the path to the PHP binary to use.
*
* @deprecated since Symfony 4.2, use the $php argument of the constructor instead.
*/
public function setPhpBinary($php)
{
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the $php argument of the constructor instead.', __METHOD__), E_USER_DEPRECATED);
$this->setCommandLine($php);
}

View File

@@ -28,6 +28,7 @@ class WindowsPipes extends AbstractPipes
{
private $files = array();
private $fileHandles = array();
private $lockHandles = array();
private $readBytes = array(
Process::STDOUT => 0,
Process::STDERR => 0,
@@ -47,31 +48,33 @@ class WindowsPipes extends AbstractPipes
Process::STDOUT => Process::OUT,
Process::STDERR => Process::ERR,
);
$tmpCheck = false;
$tmpDir = sys_get_temp_dir();
$lastError = 'unknown reason';
set_error_handler(function ($type, $msg) use (&$lastError) { $lastError = $msg; });
for ($i = 0;; ++$i) {
foreach ($pipes as $pipe => $name) {
$file = sprintf('%s\\sf_proc_%02X.%s', $tmpDir, $i, $name);
if (file_exists($file) && !unlink($file)) {
continue 2;
}
$h = fopen($file, 'xb');
if (!$h) {
$error = $lastError;
if ($tmpCheck || $tmpCheck = unlink(tempnam(false, 'sf_check_'))) {
continue;
}
if (!$h = fopen($file.'.lock', 'w')) {
restore_error_handler();
throw new RuntimeException(sprintf('A temporary file could not be opened to write the process output: %s', $error));
throw new RuntimeException(sprintf('A temporary file could not be opened to write the process output: %s', $lastError));
}
if (!$h || !$this->fileHandles[$pipe] = fopen($file, 'rb')) {
if (!flock($h, LOCK_EX | LOCK_NB)) {
continue 2;
}
if (isset($this->files[$pipe])) {
unlink($this->files[$pipe]);
if (isset($this->lockHandles[$pipe])) {
flock($this->lockHandles[$pipe], LOCK_UN);
fclose($this->lockHandles[$pipe]);
}
$this->lockHandles[$pipe] = $h;
if (!fclose(fopen($file, 'w')) || !$h = fopen($file, 'r')) {
flock($this->lockHandles[$pipe], LOCK_UN);
fclose($this->lockHandles[$pipe]);
unset($this->lockHandles[$pipe]);
continue 2;
}
$this->fileHandles[$pipe] = $h;
$this->files[$pipe] = $file;
}
break;
@@ -85,7 +88,6 @@ class WindowsPipes extends AbstractPipes
public function __destruct()
{
$this->close();
$this->removeFiles();
}
/**
@@ -145,8 +147,11 @@ class WindowsPipes extends AbstractPipes
$read[$type] = $data;
}
if ($close) {
ftruncate($fileHandle, 0);
fclose($fileHandle);
unset($this->fileHandles[$type]);
flock($this->lockHandles[$type], LOCK_UN);
fclose($this->lockHandles[$type]);
unset($this->fileHandles[$type], $this->lockHandles[$type]);
}
}
@@ -175,22 +180,12 @@ class WindowsPipes extends AbstractPipes
public function close()
{
parent::close();
foreach ($this->fileHandles as $handle) {
foreach ($this->fileHandles as $type => $handle) {
ftruncate($handle, 0);
fclose($handle);
flock($this->lockHandles[$type], LOCK_UN);
fclose($this->lockHandles[$type]);
}
$this->fileHandles = array();
}
/**
* Removes temporary files.
*/
private function removeFiles()
{
foreach ($this->files as $filename) {
if (file_exists($filename)) {
@unlink($filename);
}
}
$this->files = array();
$this->fileHandles = $this->lockHandles = array();
}
}

View File

@@ -129,21 +129,25 @@ class Process implements \IteratorAggregate
);
/**
* @param string|array $commandline The command line to run
* @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
* @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 RuntimeException When proc_open is not installed
*/
public function __construct($commandline, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
public function __construct($command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
{
if (!\function_exists('proc_open')) {
throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
throw new LogicException('The Process class relies on proc_open, which is not available on your PHP installation.');
}
$this->commandline = $commandline;
if (!\is_array($command)) {
@trigger_error(sprintf('Passing a command as string when creating a "%s" instance is deprecated since Symfony 4.2, pass it as an array of its arguments instead, or use the "Process::fromShellCommandline()" constructor if you need features provided by the shell.', __CLASS__), E_USER_DEPRECATED);
}
$this->commandline = $command;
$this->cwd = $cwd;
// on Windows, if the cwd changed via chdir(), proc_open defaults to the dir where PHP was started
@@ -163,6 +167,35 @@ class Process implements \IteratorAggregate
$this->pty = false;
}
/**
* Creates a Process instance as a command-line to be run in a shell wrapper.
*
* Command-lines are parsed by the shell of your OS (/bin/sh on Unix-like, cmd.exe on Windows.)
* This allows using e.g. pipes or conditional execution. In this mode, signals are sent to the
* shell wrapper and not to your commands.
*
* In order to inject dynamic values into command-lines, we strongly recommend using placeholders.
* This will save escaping values, which is not portable nor secure anyway:
*
* $process = Process::fromShellCommandline('my_command "$MY_VAR"');
* $process->run(null, ['MY_VAR' => $theValue]);
*
* @param string $command The command line to pass to the shell of the OS
* @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 RuntimeException When proc_open is not installed
*/
public static function fromShellCommandline(string $command, string $cwd = null, array $env = null, $input = null, ?float $timeout = 60)
{
$process = new static(array(), $cwd, $env, $input, $timeout);
$process->commandline = $command;
return $process;
}
public function __destruct()
{
$this->stop(0);
@@ -374,7 +407,7 @@ class Process implements \IteratorAggregate
if (null !== $callback) {
if (!$this->processPipes->haveReadSupport()) {
$this->stop(0);
throw new \LogicException('Pass the callback to the Process::start method or enableOutput to use a callback with Process::wait');
throw new \LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::wait"');
}
$this->callback = $this->buildCallback($callback);
}
@@ -396,6 +429,51 @@ class Process implements \IteratorAggregate
return $this->exitcode;
}
/**
* Waits until the callback returns true.
*
* The callback receives the type of output (out or err) and some bytes
* from the output in real-time while writing the standard input to the process.
* It allows to have feedback from the independent process during execution.
*
* @throws RuntimeException When process timed out
* @throws LogicException When process is not yet started
*/
public function waitUntil(callable $callback): bool
{
$this->requireProcessIsStarted(__FUNCTION__);
$this->updateStatus(false);
if (!$this->processPipes->haveReadSupport()) {
$this->stop(0);
throw new \LogicException('Pass the callback to the "Process::start" method or call enableOutput to use a callback with "Process::waitUntil".');
}
$callback = $this->buildCallback($callback);
$ready = false;
while (true) {
$this->checkTimeout();
$running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$output = $this->processPipes->readAndWrite($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
foreach ($output as $type => $data) {
if (3 !== $type) {
$ready = $callback(self::STDOUT === $type ? self::OUT : self::ERR, $data) || $ready;
} elseif (!isset($this->fallbackStatus['signaled'])) {
$this->fallbackStatus['exitcode'] = (int) $data;
}
}
if ($ready) {
return true;
}
if (!$running) {
return false;
}
usleep(1000);
}
}
/**
* Returns the Pid (process identifier), if applicable.
*
@@ -651,7 +729,7 @@ class Process implements \IteratorAggregate
/**
* Returns the exit code returned by the process.
*
* @return null|int The exit status code, null if the Process is not terminated
* @return int|null The exit status code, null if the Process is not terminated
*/
public function getExitCode()
{
@@ -666,7 +744,7 @@ class Process implements \IteratorAggregate
* This method relies on the Unix exit code status standardization
* and might not be relevant for other operating systems.
*
* @return null|string A string representation for the exit status code, null if the Process is not terminated
* @return string|null A string representation for the exit status code, null if the Process is not terminated
*
* @see http://tldp.org/LDP/abs/html/exitcodes.html
* @see http://en.wikipedia.org/wiki/Unix_signal
@@ -823,7 +901,7 @@ class Process implements \IteratorAggregate
{
$timeoutMicro = microtime(true) + $timeout;
if ($this->isRunning()) {
// given `SIGTERM` may not be defined and that `proc_terminate` uses the constant value and not the constant itself, we use the same here
// given SIGTERM may not be defined and that "proc_terminate" uses the constant value and not the constant itself, we use the same here
$this->doSignal(15, false);
do {
usleep(1000);
@@ -892,9 +970,13 @@ class Process implements \IteratorAggregate
* @param string|array $commandline The command to execute
*
* @return self The current Process instance
*
* @deprecated since Symfony 4.2.
*/
public function setCommandLine($commandline)
{
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED);
$this->commandline = $commandline;
return $this;
@@ -1227,7 +1309,7 @@ class Process implements \IteratorAggregate
if ($this->outputDisabled) {
return function ($type, $data) use ($callback) {
if (null !== $callback) {
\call_user_func($callback, $type, $data);
return \call_user_func($callback, $type, $data);
}
};
}
@@ -1242,7 +1324,7 @@ class Process implements \IteratorAggregate
}
if (null !== $callback) {
\call_user_func($callback, $type, $data);
return \call_user_func($callback, $type, $data);
}
};
}
@@ -1392,8 +1474,8 @@ class Process implements \IteratorAggregate
$this->exitcode = null;
$this->fallbackStatus = array();
$this->processInformation = null;
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'wb+');
$this->stdout = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->stderr = fopen('php://temp/maxmemory:'.(1024 * 1024), 'w+b');
$this->process = null;
$this->latestSignal = null;
$this->status = self::STATUS_READY;
@@ -1442,7 +1524,7 @@ class Process implements \IteratorAggregate
}
if (!$ok) {
if ($throwException) {
throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
throw new RuntimeException(sprintf('Error while sending signal "%s".', $signal));
}
return false;
@@ -1516,7 +1598,7 @@ class Process implements \IteratorAggregate
}
/**
* Ensures the process is terminated, throws a LogicException if the process has a status different than `terminated`.
* Ensures the process is terminated, throws a LogicException if the process has a status different than "terminated".
*
* @throws LogicException if the process is not yet terminated
*/
@@ -1530,14 +1612,14 @@ class Process implements \IteratorAggregate
/**
* Escapes a string to be used as a shell argument.
*/
private function escapeArgument(string $argument): string
private function escapeArgument(?string $argument): string
{
if ('' === $argument || null === $argument) {
return '""';
}
if ('\\' !== \DIRECTORY_SEPARATOR) {
return "'".str_replace("'", "'\\''", $argument)."'";
}
if ('' === $argument = (string) $argument) {
return '""';
}
if (false !== strpos($argument, "\0")) {
$argument = str_replace("\0", '?', $argument);
}

View File

@@ -0,0 +1,26 @@
<?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.
*/
$outputs = array(
'First iteration output',
'Second iteration output',
'One more iteration output',
'This took more time',
'This one was sooooo slow',
);
$iterationTime = 10000;
foreach ($outputs as $output) {
usleep($iterationTime);
$iterationTime *= 10;
echo $output."\n";
}

View File

@@ -24,7 +24,7 @@ class ProcessFailedExceptionTest extends TestCase
*/
public function testProcessFailedExceptionThrowsException()
{
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful'))->setConstructorArgs(array('php'))->getMock();
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful'))->setConstructorArgs(array(array('php')))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(true));
@@ -52,7 +52,7 @@ class ProcessFailedExceptionTest extends TestCase
$errorOutput = 'FATAL: Unexpected error';
$workingDirectory = getcwd();
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'))->setConstructorArgs(array($cmd))->getMock();
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'))->setConstructorArgs(array(array($cmd)))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(false));
@@ -85,7 +85,7 @@ class ProcessFailedExceptionTest extends TestCase
$this->assertEquals(
"The command \"$cmd\" failed.\n\nExit Code: $exitCode($exitText)\n\nWorking directory: {$workingDirectory}\n\nOutput:\n================\n{$output}\n\nError Output:\n================\n{$errorOutput}",
$exception->getMessage()
str_replace("'php'", 'php', $exception->getMessage())
);
}
@@ -100,7 +100,7 @@ class ProcessFailedExceptionTest extends TestCase
$exitText = 'General error';
$workingDirectory = getcwd();
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'))->setConstructorArgs(array($cmd))->getMock();
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'))->setConstructorArgs(array(array($cmd)))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(false));
@@ -131,7 +131,7 @@ class ProcessFailedExceptionTest extends TestCase
$this->assertEquals(
"The command \"$cmd\" failed.\n\nExit Code: $exitCode($exitText)\n\nWorking directory: {$workingDirectory}",
$exception->getMessage()
str_replace("'php'", 'php', $exception->getMessage())
);
}
}

View File

@@ -55,13 +55,13 @@ class ProcessTest extends TestCase
{
try {
// Check that it works fine if the CWD exists
$cmd = new Process('echo test', __DIR__);
$cmd = new Process(array('echo', 'test'), __DIR__);
$cmd->run();
} catch (\Exception $e) {
$this->fail($e);
}
$cmd = new Process('echo test', __DIR__.'/notfound/');
$cmd = new Process(array('echo', 'test'), __DIR__.'/notfound/');
$cmd->run();
}
@@ -133,6 +133,30 @@ class ProcessTest extends TestCase
$this->assertLessThan(15, microtime(true) - $start);
}
public function testWaitUntilSpecificOutput()
{
$p = $this->getProcess(array(self::$phpBin, __DIR__.'/KillableProcessWithOutput.php'));
$p->start();
$start = microtime(true);
$completeOutput = '';
$result = $p->waitUntil(function ($type, $output) use (&$completeOutput) {
return false !== strpos($completeOutput .= $output, 'One more');
});
$this->assertTrue($result);
$this->assertLessThan(20, microtime(true) - $start);
$this->assertStringStartsWith("First iteration output\nSecond iteration output\nOne more", $completeOutput);
$p->stop();
}
public function testWaitUntilCanReturnFalse()
{
$p = $this->getProcess('echo foo');
$p->start();
$this->assertFalse($p->waitUntil(function () { return false; }));
}
public function testAllOutputIsActuallyReadOnTermination()
{
// this code will result in a maximum of 2 reads of 8192 bytes by calling
@@ -1436,12 +1460,12 @@ class ProcessTest extends TestCase
$p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
$p->run();
$this->assertSame($arg, $p->getOutput());
$this->assertSame((string) $arg, $p->getOutput());
}
public function testRawCommandLine()
{
$p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
$p = Process::fromShellCommandline(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
$p->run();
$expected = <<<EOTXT
@@ -1466,32 +1490,29 @@ EOTXT;
yield array("a!b\tc");
yield array('a\\\\"\\"');
yield array('éÉèÈàÀöä');
yield array(null);
yield array(1);
yield array(1.1);
}
public function testEnvArgument()
{
$env = array('FOO' => 'Foo', 'BAR' => 'Bar');
$cmd = '\\' === \DIRECTORY_SEPARATOR ? 'echo !FOO! !BAR! !BAZ!' : 'echo $FOO $BAR $BAZ';
$p = new Process($cmd, null, $env);
$p = Process::fromShellCommandline($cmd, null, $env);
$p->run(null, array('BAR' => 'baR', 'BAZ' => 'baZ'));
$this->assertSame('Foo baR baZ', rtrim($p->getOutput()));
$this->assertSame($env, $p->getEnv());
}
/**
* @param string $commandline
* @param null|string $cwd
* @param null|array $env
* @param null|string $input
* @param int $timeout
* @param array $options
*
* @return Process
*/
private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
private function getProcess($commandline, string $cwd = null, array $env = null, $input = null, ?int $timeout = 60): Process
{
$process = new Process($commandline, $cwd, $env, $input, $timeout);
if (\is_string($commandline)) {
$process = Process::fromShellCommandline($commandline, $cwd, $env, $input, $timeout);
} else {
$process = new Process($commandline, $cwd, $env, $input, $timeout);
}
$process->inheritEnvironmentVariables();
if (self::$process) {
@@ -1501,10 +1522,7 @@ EOTXT;
return self::$process = $process;
}
/**
* @return Process
*/
private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
private function getProcessForCode(string $code, string $cwd = null, array $env = null, $input = null, ?int $timeout = 60): Process
{
return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
}

View File

@@ -27,7 +27,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "4.1-dev"
"dev-master": "4.2-dev"
}
}
}

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/5.2/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"