Laravel version update

Laravel version update
This commit is contained in:
Manish Verma
2018-08-06 18:48:58 +05:30
parent d143048413
commit 126fbb0255
13678 changed files with 1031482 additions and 778530 deletions

View File

@@ -1,6 +1,23 @@
CHANGELOG
=========
3.4.0
-----
* deprecated the ProcessBuilder class
* deprecated calling `Process::start()` without setting a valid working directory beforehand (via `setWorkingDirectory()` or constructor)
3.3.0
-----
* added command line arrays in the `Process` class
* added `$env` argument to `Process::start()`, `run()`, `mustRun()` and `restart()` methods
* deprecated the `ProcessUtils::escapeArgument()` method
* deprecated not inheriting environment variables
* deprecated configuring `proc_open()` options
* deprecated configuring enhanced Windows compatibility
* deprecated configuring enhanced sigchild compatibility
2.5.0
-----

View File

@@ -45,12 +45,12 @@ class ProcessTimedOutException extends RuntimeException
public function isGeneralTimeout()
{
return $this->timeoutType === self::TYPE_GENERAL;
return self::TYPE_GENERAL === $this->timeoutType;
}
public function isIdleTimeout()
{
return $this->timeoutType === self::TYPE_IDLE;
return self::TYPE_IDLE === $this->timeoutType;
}
public function getExceededTimeout()

View File

@@ -23,8 +23,6 @@ class ExecutableFinder
/**
* Replaces default suffixes of executable.
*
* @param array $suffixes
*/
public function setSuffixes(array $suffixes)
{
@@ -60,7 +58,7 @@ class ExecutableFinder
if (@is_dir($path)) {
$dirs[] = $path;
} else {
if (basename($path) == $name && is_executable($path)) {
if (basename($path) == $name && @is_executable($path)) {
return $path;
}
}
@@ -73,13 +71,13 @@ class ExecutableFinder
}
$suffixes = array('');
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$pathExt = getenv('PATHEXT');
$suffixes = $pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes;
$suffixes = array_merge($pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes, $suffixes);
}
foreach ($suffixes as $suffix) {
foreach ($dirs as $dir) {
if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === DIRECTORY_SEPARATOR || is_executable($file))) {
if (@is_file($file = $dir.\DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === \DIRECTORY_SEPARATOR || @is_executable($file))) {
return $file;
}
}

92
vendor/symfony/process/InputStream.php vendored Normal file
View File

@@ -0,0 +1,92 @@
<?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\RuntimeException;
/**
* Provides a way to continuously write to the input of a Process until the InputStream is closed.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class InputStream implements \IteratorAggregate
{
/** @var null|callable */
private $onEmpty = null;
private $input = array();
private $open = true;
/**
* Sets a callback that is called when the write buffer becomes empty.
*/
public function onEmpty(callable $onEmpty = null)
{
$this->onEmpty = $onEmpty;
}
/**
* 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
*/
public function write($input)
{
if (null === $input) {
return;
}
if ($this->isClosed()) {
throw new RuntimeException(sprintf('%s is closed', static::class));
}
$this->input[] = ProcessUtils::validateInput(__METHOD__, $input);
}
/**
* Closes the write buffer.
*/
public function close()
{
$this->open = false;
}
/**
* Tells whether the write buffer is closed or not.
*/
public function isClosed()
{
return !$this->open;
}
public function getIterator()
{
$this->open = true;
while ($this->open || $this->input) {
if (!$this->input) {
yield '';
continue;
}
$current = array_shift($this->input);
if ($current instanceof \Iterator) {
foreach ($current as $cur) {
yield $cur;
}
} else {
yield $current;
}
if (!$this->input && $this->open && null !== $onEmpty = $this->onEmpty) {
$this->write($onEmpty($this));
}
}
}
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2004-2016 Fabien Potencier
Copyright (c) 2004-2018 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -39,17 +39,17 @@ class PhpExecutableFinder
$args = $includeArgs && $args ? ' '.implode(' ', $args) : '';
// HHVM support
if (defined('HHVM_VERSION')) {
if (\defined('HHVM_VERSION')) {
return (getenv('PHP_BINARY') ?: PHP_BINARY).$args;
}
// PHP_BINARY return the current sapi executable
if (PHP_BINARY && in_array(PHP_SAPI, array('cli', 'cli-server', 'phpdbg')) && is_file(PHP_BINARY)) {
if (PHP_BINARY && \in_array(\PHP_SAPI, array('cli', 'cli-server', 'phpdbg'), true)) {
return PHP_BINARY.$args;
}
if ($php = getenv('PHP_PATH')) {
if (!is_executable($php)) {
if (!@is_executable($php)) {
return false;
}
@@ -57,13 +57,17 @@ class PhpExecutableFinder
}
if ($php = getenv('PHP_PEAR_PHP_BIN')) {
if (is_executable($php)) {
if (@is_executable($php)) {
return $php;
}
}
if (@is_executable($php = PHP_BINDIR.('\\' === \DIRECTORY_SEPARATOR ? '\\php.exe' : '/php'))) {
return $php;
}
$dirs = array(PHP_BINDIR);
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$dirs[] = 'C:\xampp\php\\';
}
@@ -79,9 +83,9 @@ class PhpExecutableFinder
{
$arguments = array();
if (defined('HHVM_VERSION')) {
if (\defined('HHVM_VERSION')) {
$arguments[] = '--php';
} elseif ('phpdbg' === PHP_SAPI) {
} elseif ('phpdbg' === \PHP_SAPI) {
$arguments[] = '-qrr';
}

View File

@@ -25,32 +25,29 @@ use Symfony\Component\Process\Exception\RuntimeException;
class PhpProcess extends Process
{
/**
* Constructor.
*
* @param string $script The PHP script to run (as a string)
* @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 $options An array of options for proc_open
*/
public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = array())
public function __construct($script, $cwd = null, array $env = null, $timeout = 60, array $options = null)
{
$executableFinder = new PhpExecutableFinder();
if (false === $php = $executableFinder->find()) {
if (false === $php = $executableFinder->find(false)) {
$php = null;
} else {
$php = array_merge(array($php), $executableFinder->findArguments());
}
if ('phpdbg' === PHP_SAPI) {
if ('phpdbg' === \PHP_SAPI) {
$file = tempnam(sys_get_temp_dir(), 'dbg');
file_put_contents($file, $script);
register_shutdown_function('unlink', $file);
$php .= ' '.ProcessUtils::escapeArgument($file);
$php[] = $file;
$script = null;
}
if ('\\' !== DIRECTORY_SEPARATOR && null !== $php) {
// exec is mandatory to deal with sending a signal to the process
// see https://github.com/symfony/symfony/issues/5030 about prepending
// command with exec
$php = 'exec '.$php;
if (null !== $options) {
@trigger_error(sprintf('The $options parameter of the %s constructor is deprecated since Symfony 3.3 and will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
}
parent::__construct($php, $cwd, $env, $script, $timeout, $options);
@@ -67,12 +64,13 @@ class PhpProcess extends Process
/**
* {@inheritdoc}
*/
public function start(callable $callback = null)
public function start(callable $callback = null/*, array $env = array()*/)
{
if (null === $this->getCommandLine()) {
throw new RuntimeException('Unable to find the PHP executable.');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
parent::start($callback);
parent::start($callback, $env);
}
}

View File

@@ -11,6 +11,8 @@
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Exception\InvalidArgumentException;
/**
* @author Romain Neutron <imprec@gmail.com>
*
@@ -18,21 +20,21 @@ namespace Symfony\Component\Process\Pipes;
*/
abstract class AbstractPipes implements PipesInterface
{
/** @var array */
public $pipes = array();
/** @var string */
private $inputBuffer = '';
/** @var resource|null */
private $input;
/** @var bool */
private $blocked = true;
private $lastError;
/**
* @param resource|string|int|float|bool|\Iterator|null $input
*/
public function __construct($input)
{
if (is_resource($input)) {
if (\is_resource($input) || $input instanceof \Iterator) {
$this->input = $input;
} elseif (is_string($input)) {
} elseif (\is_string($input)) {
$this->inputBuffer = $input;
} else {
$this->inputBuffer = (string) $input;
@@ -57,10 +59,11 @@ abstract class AbstractPipes implements PipesInterface
*/
protected function hasSystemCallBeenInterrupted()
{
$lastError = error_get_last();
$lastError = $this->lastError;
$this->lastError = null;
// stream_select returns false when the `select` system call is interrupted by an incoming signal
return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
return null !== $lastError && false !== stripos($lastError, 'interrupted system call');
}
/**
@@ -75,7 +78,7 @@ abstract class AbstractPipes implements PipesInterface
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, 0);
}
if (null !== $this->input) {
if (\is_resource($this->input)) {
stream_set_blocking($this->input, 0);
}
@@ -84,6 +87,8 @@ abstract class AbstractPipes implements PipesInterface
/**
* Writes input to stdin.
*
* @throws InvalidArgumentException When an input iterator yields a non supported value
*/
protected function write()
{
@@ -91,11 +96,32 @@ abstract class AbstractPipes implements PipesInterface
return;
}
$input = $this->input;
if ($input instanceof \Iterator) {
if (!$input->valid()) {
$input = null;
} elseif (\is_resource($input = $input->current())) {
stream_set_blocking($input, 0);
} elseif (!isset($this->inputBuffer[0])) {
if (!\is_string($input)) {
if (!is_scalar($input)) {
throw new InvalidArgumentException(sprintf('%s yielded a value of type "%s", but only scalars and stream resources are supported', \get_class($this->input), \gettype($input)));
}
$input = (string) $input;
}
$this->inputBuffer = $input;
$this->input->next();
$input = null;
} else {
$input = null;
}
}
$r = $e = array();
$w = array($this->pipes[0]);
// let's have a look if something changed in streams
if (false === $n = @stream_select($r, $w, $e, 0, 0)) {
if (false === @stream_select($r, $w, $e, 0, 0)) {
return;
}
@@ -123,21 +149,30 @@ abstract class AbstractPipes implements PipesInterface
}
}
if (feof($input)) {
// no more data to read on input resource
// use an empty buffer in the next reads
$this->input = null;
if ($this->input instanceof \Iterator) {
$this->input->next();
} else {
$this->input = null;
}
}
}
}
// no input to read on resource, buffer is empty
if (null === $this->input && !isset($this->inputBuffer[0])) {
if (!isset($this->inputBuffer[0]) && !($this->input instanceof \Iterator ? $this->input->valid() : $this->input)) {
$this->input = null;
fclose($this->pipes[0]);
unset($this->pipes[0]);
}
if (!$w) {
} elseif (!$w) {
return array($this->pipes[0]);
}
}
/**
* @internal
*/
public function handleError($type, $msg)
{
$this->lastError = $msg;
}
}

View File

@@ -53,6 +53,13 @@ interface PipesInterface
*/
public function areOpen();
/**
* Returns if pipes are able to read output.
*
* @return bool
*/
public function haveReadSupport();
/**
* Closes file handles and pipes.
*/

View File

@@ -22,18 +22,15 @@ use Symfony\Component\Process\Process;
*/
class UnixPipes extends AbstractPipes
{
/** @var bool */
private $ttyMode;
/** @var bool */
private $ptyMode;
/** @var bool */
private $disableOutput;
private $haveReadSupport;
public function __construct($ttyMode, $ptyMode, $input, $disableOutput)
public function __construct($ttyMode, $ptyMode, $input, $haveReadSupport)
{
$this->ttyMode = (bool) $ttyMode;
$this->ptyMode = (bool) $ptyMode;
$this->disableOutput = (bool) $disableOutput;
$this->haveReadSupport = (bool) $haveReadSupport;
parent::__construct($input);
}
@@ -48,7 +45,7 @@ class UnixPipes extends AbstractPipes
*/
public function getDescriptors()
{
if ($this->disableOutput) {
if (!$this->haveReadSupport) {
$nullstream = fopen('/dev/null', 'c');
return array(
@@ -102,7 +99,9 @@ class UnixPipes extends AbstractPipes
unset($r[0]);
// let's have a look if something changed in streams
if (($r || $w) && false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
set_error_handler(array($this, 'handleError'));
if (($r || $w) && false === stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
restore_error_handler();
// if a system call has been interrupted, forget about it, let's try again
// otherwise, an error occurred, let's reset pipes
if (!$this->hasSystemCallBeenInterrupted()) {
@@ -111,6 +110,7 @@ class UnixPipes extends AbstractPipes
return $read;
}
restore_error_handler();
foreach ($r as $pipe) {
// prior PHP 5.4 the array passed to stream_select is modified and
@@ -120,7 +120,7 @@ class UnixPipes extends AbstractPipes
do {
$data = fread($pipe, self::CHUNK_SIZE);
$read[$type] .= $data;
} while (isset($data[0]));
} while (isset($data[0]) && ($close || isset($data[self::CHUNK_SIZE - 1])));
if (!isset($read[$type][0])) {
unset($read[$type]);
@@ -135,6 +135,14 @@ class UnixPipes extends AbstractPipes
return $read;
}
/**
* {@inheritdoc}
*/
public function haveReadSupport()
{
return $this->haveReadSupport;
}
/**
* {@inheritdoc}
*/
@@ -142,17 +150,4 @@ class UnixPipes extends AbstractPipes
{
return (bool) $this->pipes;
}
/**
* Creates a new UnixPipes instance.
*
* @param Process $process
* @param string|resource $input
*
* @return UnixPipes
*/
public static function create(Process $process, $input)
{
return new static($process->isTty(), $process->isPty(), $input, $process->isOutputDisabled());
}
}

View File

@@ -11,8 +11,8 @@
namespace Symfony\Component\Process\Pipes;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\Process;
/**
* WindowsPipes implementation uses temporary files as handles.
@@ -26,23 +26,19 @@ use Symfony\Component\Process\Exception\RuntimeException;
*/
class WindowsPipes extends AbstractPipes
{
/** @var array */
private $files = array();
/** @var array */
private $fileHandles = array();
/** @var array */
private $readBytes = array(
Process::STDOUT => 0,
Process::STDERR => 0,
);
/** @var bool */
private $disableOutput;
private $haveReadSupport;
public function __construct($disableOutput, $input)
public function __construct($input, $haveReadSupport)
{
$this->disableOutput = (bool) $disableOutput;
$this->haveReadSupport = (bool) $haveReadSupport;
if (!$this->disableOutput) {
if ($this->haveReadSupport) {
// Fix for PHP bug #51800: reading from STDOUT pipe hangs forever on Windows if the output is too big.
// Workaround for this problem is to use temporary files instead of pipes on Windows platform.
//
@@ -51,9 +47,10 @@ class WindowsPipes extends AbstractPipes
Process::STDOUT => Process::OUT,
Process::STDERR => Process::ERR,
);
$tmpCheck = false;
$tmpDir = sys_get_temp_dir();
$error = 'unknown reason';
set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
$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);
@@ -61,7 +58,11 @@ class WindowsPipes extends AbstractPipes
continue 2;
}
$h = fopen($file, 'xb');
if (!$h && false === strpos($error, 'File exists')) {
if (!$h) {
$error = $lastError;
if ($tmpCheck || $tmpCheck = unlink(tempnam(false, 'sf_check_'))) {
continue;
}
restore_error_handler();
throw new RuntimeException(sprintf('A temporary file could not be opened to write the process output: %s', $error));
}
@@ -92,7 +93,7 @@ class WindowsPipes extends AbstractPipes
*/
public function getDescriptors()
{
if ($this->disableOutput) {
if (!$this->haveReadSupport) {
$nullstream = fopen('NUL', 'c');
return array(
@@ -140,7 +141,7 @@ class WindowsPipes extends AbstractPipes
$data = stream_get_contents($fileHandle, -1, $this->readBytes[$type]);
if (isset($data[0])) {
$this->readBytes[$type] += strlen($data);
$this->readBytes[$type] += \strlen($data);
$read[$type] = $data;
}
if ($close) {
@@ -152,6 +153,14 @@ class WindowsPipes extends AbstractPipes
return $read;
}
/**
* {@inheritdoc}
*/
public function haveReadSupport()
{
return $this->haveReadSupport;
}
/**
* {@inheritdoc}
*/
@@ -172,19 +181,6 @@ class WindowsPipes extends AbstractPipes
$this->fileHandles = array();
}
/**
* Creates a new WindowsPipes instance.
*
* @param Process $process The process
* @param $input
*
* @return WindowsPipes
*/
public static function create(Process $process, $input)
{
return new static($process->isOutputDisabled(), $input);
}
/**
* Removes temporary files.
*/

View File

@@ -27,7 +27,7 @@ use Symfony\Component\Process\Pipes\WindowsPipes;
* @author Fabien Potencier <fabien@symfony.com>
* @author Romain Neutron <imprec@gmail.com>
*/
class Process
class Process implements \IteratorAggregate
{
const ERR = 'err';
const OUT = 'out';
@@ -43,7 +43,13 @@ class Process
// Timeout Precision in seconds.
const TIMEOUT_PRECISION = 0.2;
const ITER_NON_BLOCKING = 1; // By default, iterating over outputs is a blocking call, use this flag to make it non-blocking
const ITER_KEEP_OUTPUT = 2; // By default, outputs are cleared while iterating, use this flag to keep them in memory
const ITER_SKIP_OUT = 4; // Use this flag to skip STDOUT while iterating
const ITER_SKIP_ERR = 8; // Use this flag to skip STDERR while iterating
private $callback;
private $hasCallback = false;
private $commandline;
private $cwd;
private $env;
@@ -52,7 +58,7 @@ class Process
private $lastOutputTime;
private $timeout;
private $idleTimeout;
private $options;
private $options = array('suppress_errors' => true);
private $exitcode;
private $fallbackStatus = array();
private $processInformation;
@@ -67,6 +73,7 @@ class Process
private $incrementalErrorOutputOffset = 0;
private $tty;
private $pty;
private $inheritEnv = false;
private $useFileHandles = false;
/** @var PipesInterface */
@@ -80,8 +87,6 @@ class Process
* Exit codes translation table.
*
* User-defined errors must use exit codes in the 64-113 range.
*
* @var array
*/
public static $exitCodes = array(
0 => 'OK',
@@ -127,20 +132,18 @@ class Process
);
/**
* Constructor.
*
* @param string $commandline The command line to run
* @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 string|null $input The input
* @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 $options An array of options for proc_open
*
* @throws RuntimeException When proc_open is not installed
*/
public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = null)
{
if (!function_exists('proc_open')) {
if (!\function_exists('proc_open')) {
throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
}
@@ -151,7 +154,7 @@ class Process
// on Gnu/Linux, PHP builds with --enable-maintainer-zts are also affected
// @see : https://bugs.php.net/bug.php?id=51800
// @see : https://bugs.php.net/bug.php?id=50524
if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
if (null === $this->cwd && (\defined('ZEND_THREAD_SAFE') || '\\' === \DIRECTORY_SEPARATOR)) {
$this->cwd = getcwd();
}
if (null !== $env) {
@@ -160,11 +163,13 @@ class Process
$this->setInput($input);
$this->setTimeout($timeout);
$this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
$this->useFileHandles = '\\' === \DIRECTORY_SEPARATOR;
$this->pty = false;
$this->enhanceWindowsCompatibility = true;
$this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
$this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
$this->enhanceSigchildCompatibility = '\\' !== \DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
if (null !== $options) {
@trigger_error(sprintf('The $options parameter of the %s constructor is deprecated since Symfony 3.3 and will be removed in 4.0.', __CLASS__), E_USER_DEPRECATED);
$this->options = array_replace($this->options, $options);
}
}
public function __destruct()
@@ -189,16 +194,20 @@ class Process
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $env An array of additional env vars to set when running the process
*
* @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
*
* @final since version 3.3
*/
public function run($callback = null)
public function run($callback = null/*, array $env = array()*/)
{
$this->start($callback);
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
$this->start($callback, $env);
return $this->wait();
}
@@ -210,19 +219,23 @@ class Process
* exits with a non-zero exit code.
*
* @param callable|null $callback
* @param array $env An array of additional env vars to set when running the process
*
* @return self
*
* @throws RuntimeException if PHP was compiled with --enable-sigchild and the enhanced sigchild compatibility mode is not enabled
* @throws ProcessFailedException if the process didn't terminate successfully
*
* @final since version 3.3
*/
public function mustRun(callable $callback = null)
public function mustRun(callable $callback = null/*, array $env = array()*/)
{
if (!$this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
if (0 !== $this->run($callback)) {
if (0 !== $this->run($callback, $env)) {
throw new ProcessFailedException($this);
}
@@ -243,53 +256,94 @@ class Process
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $env An array of additional env vars to set when running the process
*
* @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
*/
public function start(callable $callback = null)
public function start(callable $callback = null/*, array $env = array()*/)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
if ($this->outputDisabled && null !== $callback) {
throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
if (2 <= \func_num_args()) {
$env = func_get_arg(1);
} else {
if (__CLASS__ !== static::class) {
$r = new \ReflectionMethod($this, __FUNCTION__);
if (__CLASS__ !== $r->getDeclaringClass()->getName() && (2 > $r->getNumberOfParameters() || 'env' !== $r->getParameters()[1]->name)) {
@trigger_error(sprintf('The %s::start() method expects a second "$env" argument since Symfony 3.3. It will be made mandatory in 4.0.', static::class), E_USER_DEPRECATED);
}
}
$env = null;
}
$this->resetProcessData();
$this->starttime = $this->lastOutputTime = microtime(true);
$this->callback = $this->buildCallback($callback);
$this->hasCallback = null !== $callback;
$descriptors = $this->getDescriptors();
$inheritEnv = $this->inheritEnv;
$commandline = $this->commandline;
if (\is_array($commandline = $this->commandline)) {
$commandline = implode(' ', array_map(array($this, 'escapeArgument'), $commandline));
if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
$commandline = 'cmd /V:ON /E:ON /D /C "('.$commandline.')';
foreach ($this->processPipes->getFiles() as $offset => $filename) {
$commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
if ('\\' !== \DIRECTORY_SEPARATOR) {
// exec is mandatory to deal with sending a signal to the process
$commandline = 'exec '.$commandline;
}
$commandline .= '"';
}
if (!isset($this->options['bypass_shell'])) {
$this->options['bypass_shell'] = true;
if (null === $env) {
$env = $this->env;
} else {
if ($this->env) {
$env += $this->env;
}
$inheritEnv = true;
}
if (null !== $env && $inheritEnv) {
$env += $this->getDefaultEnv();
} elseif (null !== $env) {
@trigger_error('Not inheriting environment variables is deprecated since Symfony 3.3 and will always happen in 4.0. Set "Process::inheritEnvironmentVariables()" to true instead.', E_USER_DEPRECATED);
} else {
$env = $this->getDefaultEnv();
}
if ('\\' === \DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
$this->options['bypass_shell'] = true;
$commandline = $this->prepareWindowsCommandLine($commandline, $env);
} elseif (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
// last exit code is output on the fourth pipe and caught to work around --enable-sigchild
$descriptors[3] = array('pipe', 'w');
// See https://unix.stackexchange.com/questions/71205/background-process-pipe-input
$commandline = '{ ('.$this->commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
$commandline = '{ ('.$commandline.') <&3 3<&- 3>/dev/null & } 3<&0;';
$commandline .= 'pid=$!; echo $pid >&3; wait $pid; code=$?; echo $code >&3; exit $code';
// Workaround for the bug, when PTS functionality is enabled.
// @see : https://bugs.php.net/69442
$ptsWorkaround = fopen(__FILE__, 'r');
}
if (\defined('HHVM_VERSION')) {
$envPairs = $env;
} else {
$envPairs = array();
foreach ($env as $k => $v) {
if (false !== $v) {
$envPairs[] = $k.'='.$v;
}
}
}
$this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
if (!is_dir($this->cwd)) {
@trigger_error('The provided cwd does not exist. Command is currently ran against getcwd(). This behavior is deprecated since Symfony 3.4 and will be removed in 4.0.', E_USER_DEPRECATED);
}
if (!is_resource($this->process)) {
$this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $envPairs, $this->options);
if (!\is_resource($this->process)) {
throw new RuntimeException('Unable to launch a new process.');
}
$this->status = self::STATUS_STARTED;
@@ -313,22 +367,26 @@ class Process
*
* @param callable|null $callback A PHP callback to run whenever there is some
* output available on STDOUT or STDERR
* @param array $env An array of additional env vars to set when running the process
*
* @return Process The new process
* @return $this
*
* @throws RuntimeException When process can't be launched
* @throws RuntimeException When process is already running
*
* @see start()
*
* @final since version 3.3
*/
public function restart(callable $callback = null)
public function restart(callable $callback = null/*, array $env = array()*/)
{
if ($this->isRunning()) {
throw new RuntimeException('Process is already running');
}
$env = 1 < \func_num_args() ? func_get_arg(1) : null;
$process = clone $this;
$process->start($callback);
$process->start($callback, $env);
return $process;
}
@@ -353,14 +411,19 @@ class Process
$this->requireProcessIsStarted(__FUNCTION__);
$this->updateStatus(false);
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');
}
$this->callback = $this->buildCallback($callback);
}
do {
$this->checkTimeout();
$running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$this->readPipes($running, '\\' !== DIRECTORY_SEPARATOR || !$running);
$running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
$this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
} while ($running);
while ($this->isRunning()) {
@@ -389,7 +452,7 @@ class Process
*
* @param int $signal A valid POSIX signal (see http://www.php.net/manual/en/pcntl.constants.php)
*
* @return Process
* @return $this
*
* @throws LogicException In case the process is not running
* @throws RuntimeException In case --enable-sigchild is activated and the process can't be killed
@@ -405,7 +468,7 @@ class Process
/**
* Disables fetching output and error output from the underlying process.
*
* @return Process
* @return $this
*
* @throws RuntimeException In case the process is already running
* @throws LogicException if an idle timeout is set
@@ -427,7 +490,7 @@ class Process
/**
* Enables fetching output and error output from the underlying process.
*
* @return Process
* @return $this
*
* @throws RuntimeException In case the process is already running
*/
@@ -496,10 +559,67 @@ class Process
return $latest;
}
/**
* Returns an iterator to the output of the process, with the output type as keys (Process::OUT/ERR).
*
* @param int $flags A bit field of Process::ITER_* flags
*
* @throws LogicException in case the output has been disabled
* @throws LogicException In case the process is not started
*
* @return \Generator
*/
public function getIterator($flags = 0)
{
$this->readPipesForOutput(__FUNCTION__, false);
$clearOutput = !(self::ITER_KEEP_OUTPUT & $flags);
$blocking = !(self::ITER_NON_BLOCKING & $flags);
$yieldOut = !(self::ITER_SKIP_OUT & $flags);
$yieldErr = !(self::ITER_SKIP_ERR & $flags);
while (null !== $this->callback || ($yieldOut && !feof($this->stdout)) || ($yieldErr && !feof($this->stderr))) {
if ($yieldOut) {
$out = stream_get_contents($this->stdout, -1, $this->incrementalOutputOffset);
if (isset($out[0])) {
if ($clearOutput) {
$this->clearOutput();
} else {
$this->incrementalOutputOffset = ftell($this->stdout);
}
yield self::OUT => $out;
}
}
if ($yieldErr) {
$err = stream_get_contents($this->stderr, -1, $this->incrementalErrorOutputOffset);
if (isset($err[0])) {
if ($clearOutput) {
$this->clearErrorOutput();
} else {
$this->incrementalErrorOutputOffset = ftell($this->stderr);
}
yield self::ERR => $err;
}
}
if (!$blocking && !isset($out[0]) && !isset($err[0])) {
yield self::OUT => '';
}
$this->checkTimeout();
$this->readPipesForOutput(__FUNCTION__, $blocking);
}
}
/**
* Clears the process output.
*
* @return Process
* @return $this
*/
public function clearOutput()
{
@@ -558,7 +678,7 @@ class Process
/**
* Clears the process output.
*
* @return Process
* @return $this
*/
public function clearErrorOutput()
{
@@ -714,7 +834,7 @@ class Process
*/
public function isStarted()
{
return $this->status != self::STATUS_READY;
return self::STATUS_READY != $this->status;
}
/**
@@ -726,7 +846,7 @@ class Process
{
$this->updateStatus(false);
return $this->status == self::STATUS_TERMINATED;
return self::STATUS_TERMINATED == $this->status;
}
/**
@@ -819,13 +939,13 @@ class Process
*/
public function getCommandLine()
{
return $this->commandline;
return \is_array($this->commandline) ? implode(' ', array_map(array($this, 'escapeArgument'), $this->commandline)) : $this->commandline;
}
/**
* Sets the command line to be executed.
*
* @param string $commandline The command to execute
* @param string|array $commandline The command to execute
*
* @return self The current Process instance
*/
@@ -908,11 +1028,19 @@ class Process
*/
public function setTty($tty)
{
if ('\\' === DIRECTORY_SEPARATOR && $tty) {
if ('\\' === \DIRECTORY_SEPARATOR && $tty) {
throw new RuntimeException('TTY mode is not supported on Windows platform.');
}
if ($tty && (!file_exists('/dev/tty') || !is_readable('/dev/tty'))) {
throw new RuntimeException('TTY mode requires /dev/tty to be readable.');
if ($tty) {
static $isTtySupported;
if (null === $isTtySupported) {
$isTtySupported = (bool) @proc_open('echo 1 >/dev/null', array(array('file', '/dev/tty', 'r'), array('file', '/dev/tty', 'w'), array('file', '/dev/tty', 'w')), $pipes);
}
if (!$isTtySupported) {
throw new RuntimeException('TTY mode requires /dev/tty to be read/writable.');
}
}
$this->tty = (bool) $tty;
@@ -997,8 +1125,10 @@ class Process
/**
* Sets the environment variables.
*
* An environment variable value should be a string.
* Each environment variable value should be a string.
* If it is an array, the variable is ignored.
* If it is false or null, it will be removed when
* env vars are otherwise inherited.
*
* That happens in PHP when 'argv' is registered into
* the $_ENV array for instance.
@@ -1011,13 +1141,10 @@ class Process
{
// Process can not handle env values that are arrays
$env = array_filter($env, function ($value) {
return !is_array($value);
return !\is_array($value);
});
$this->env = array();
foreach ($env as $key => $value) {
$this->env[$key] = (string) $value;
}
$this->env = $env;
return $this;
}
@@ -1025,7 +1152,7 @@ class Process
/**
* Gets the Process input.
*
* @return null|string The Process input
* @return resource|string|\Iterator|null The Process input
*/
public function getInput()
{
@@ -1037,7 +1164,7 @@ class Process
*
* This content will be passed to the underlying process standard input.
*
* @param mixed $input The content
* @param string|int|float|bool|resource|\Traversable|null $input The content
*
* @return self The current Process instance
*
@@ -1058,9 +1185,13 @@ class Process
* Gets the options for proc_open.
*
* @return array The current options
*
* @deprecated since version 3.3, to be removed in 4.0.
*/
public function getOptions()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0.', __METHOD__), E_USER_DEPRECATED);
return $this->options;
}
@@ -1070,9 +1201,13 @@ class Process
* @param array $options The new options
*
* @return self The current Process instance
*
* @deprecated since version 3.3, to be removed in 4.0.
*/
public function setOptions(array $options)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0.', __METHOD__), E_USER_DEPRECATED);
$this->options = $options;
return $this;
@@ -1084,9 +1219,13 @@ class Process
* This is true by default.
*
* @return bool
*
* @deprecated since version 3.3, to be removed in 4.0. Enhanced Windows compatibility will always be enabled.
*/
public function getEnhanceWindowsCompatibility()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Enhanced Windows compatibility will always be enabled.', __METHOD__), E_USER_DEPRECATED);
return $this->enhanceWindowsCompatibility;
}
@@ -1096,9 +1235,13 @@ class Process
* @param bool $enhance
*
* @return self The current Process instance
*
* @deprecated since version 3.3, to be removed in 4.0. Enhanced Windows compatibility will always be enabled.
*/
public function setEnhanceWindowsCompatibility($enhance)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Enhanced Windows compatibility will always be enabled.', __METHOD__), E_USER_DEPRECATED);
$this->enhanceWindowsCompatibility = (bool) $enhance;
return $this;
@@ -1108,9 +1251,13 @@ class Process
* Returns whether sigchild compatibility mode is activated or not.
*
* @return bool
*
* @deprecated since version 3.3, to be removed in 4.0. Sigchild compatibility will always be enabled.
*/
public function getEnhanceSigchildCompatibility()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Sigchild compatibility will always be enabled.', __METHOD__), E_USER_DEPRECATED);
return $this->enhanceSigchildCompatibility;
}
@@ -1124,14 +1271,50 @@ class Process
* @param bool $enhance
*
* @return self The current Process instance
*
* @deprecated since version 3.3, to be removed in 4.0.
*/
public function setEnhanceSigchildCompatibility($enhance)
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Sigchild compatibility will always be enabled.', __METHOD__), E_USER_DEPRECATED);
$this->enhanceSigchildCompatibility = (bool) $enhance;
return $this;
}
/**
* Sets whether environment variables will be inherited or not.
*
* @param bool $inheritEnv
*
* @return self The current Process instance
*/
public function inheritEnvironmentVariables($inheritEnv = true)
{
if (!$inheritEnv) {
@trigger_error('Not inheriting environment variables is deprecated since Symfony 3.3 and will always happen in 4.0. Set "Process::inheritEnvironmentVariables()" to true instead.', E_USER_DEPRECATED);
}
$this->inheritEnv = (bool) $inheritEnv;
return $this;
}
/**
* Returns whether environment variables will be inherited or not.
*
* @return bool
*
* @deprecated since version 3.3, to be removed in 4.0. Environment variables will always be inherited.
*/
public function areEnvironmentVariablesInherited()
{
@trigger_error(sprintf('The %s() method is deprecated since Symfony 3.3 and will be removed in 4.0. Environment variables will always be inherited.', __METHOD__), E_USER_DEPRECATED);
return $this->inheritEnv;
}
/**
* Performs a check between the timeout definition and the time the process started.
*
@@ -1142,7 +1325,7 @@ class Process
*/
public function checkTimeout()
{
if ($this->status !== self::STATUS_STARTED) {
if (self::STATUS_STARTED !== $this->status) {
return;
}
@@ -1172,11 +1355,11 @@ class Process
return $result;
}
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
return $result = false;
}
return $result = (bool) @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
return $result = (bool) @proc_open('echo 1 >/dev/null', array(array('pty'), array('pty'), array('pty')), $pipes);
}
/**
@@ -1186,10 +1369,13 @@ class Process
*/
private function getDescriptors()
{
if ('\\' === DIRECTORY_SEPARATOR) {
$this->processPipes = WindowsPipes::create($this, $this->input);
if ($this->input instanceof \Iterator) {
$this->input->rewind();
}
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->processPipes = new WindowsPipes($this->input, !$this->outputDisabled || $this->hasCallback);
} else {
$this->processPipes = UnixPipes::create($this, $this->input);
$this->processPipes = new UnixPipes($this->isTty(), $this->isPty(), $this->input, !$this->outputDisabled || $this->hasCallback);
}
return $this->processPipes->getDescriptors();
@@ -1205,10 +1391,19 @@ class Process
*
* @return \Closure A PHP closure
*/
protected function buildCallback($callback)
protected function buildCallback(callable $callback = null)
{
if ($this->outputDisabled) {
return function ($type, $data) use ($callback) {
if (null !== $callback) {
\call_user_func($callback, $type, $data);
}
};
}
$out = self::OUT;
$callback = function ($type, $data) use ($callback, $out) {
return function ($type, $data) use ($callback, $out) {
if ($out == $type) {
$this->addOutput($data);
} else {
@@ -1216,11 +1411,9 @@ class Process
}
if (null !== $callback) {
call_user_func($callback, $type, $data);
\call_user_func($callback, $type, $data);
}
};
return $callback;
}
/**
@@ -1237,7 +1430,7 @@ class Process
$this->processInformation = proc_get_status($this->process);
$running = $this->processInformation['running'];
$this->readPipes($running && $blocking, '\\' !== DIRECTORY_SEPARATOR || !$running);
$this->readPipes($running && $blocking, '\\' !== \DIRECTORY_SEPARATOR || !$running);
if ($this->fallbackStatus && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
$this->processInformation = $this->fallbackStatus + $this->processInformation;
@@ -1259,7 +1452,7 @@ class Process
return self::$sigchild;
}
if (!function_exists('phpinfo') || defined('HHVM_VERSION')) {
if (!\function_exists('phpinfo') || \defined('HHVM_VERSION')) {
return self::$sigchild = false;
}
@@ -1272,11 +1465,12 @@ class Process
/**
* Reads pipes for the freshest output.
*
* @param $caller The name of the method that needs fresh outputs
* @param string $caller The name of the method that needs fresh outputs
* @param bool $blocking Whether to use blocking calls or not
*
* @throws LogicException in case output has been disabled or process is not started
*/
private function readPipesForOutput($caller)
private function readPipesForOutput($caller, $blocking = false)
{
if ($this->outputDisabled) {
throw new LogicException('Output has been disabled.');
@@ -1284,7 +1478,7 @@ class Process
$this->requireProcessIsStarted($caller);
$this->updateStatus(false);
$this->updateStatus($blocking);
}
/**
@@ -1322,7 +1516,7 @@ class Process
$callback = $this->callback;
foreach ($result as $type => $data) {
if (3 !== $type) {
$callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
$callback(self::STDOUT === $type ? self::OUT : self::ERR, $data);
} elseif (!isset($this->fallbackStatus['signaled'])) {
$this->fallbackStatus['exitcode'] = (int) $data;
}
@@ -1337,7 +1531,7 @@ class Process
private function close()
{
$this->processPipes->close();
if (is_resource($this->process)) {
if (\is_resource($this->process)) {
proc_close($this->process);
}
$this->exitcode = $this->processInformation['exitcode'];
@@ -1402,7 +1596,7 @@ class Process
return false;
}
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
exec(sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
if ($exitCode && $this->isRunning()) {
if ($throwException) {
@@ -1414,7 +1608,7 @@ class Process
} else {
if (!$this->enhanceSigchildCompatibility || !$this->isSigchildEnabled()) {
$ok = @proc_terminate($this->process, $signal);
} elseif (function_exists('posix_kill')) {
} elseif (\function_exists('posix_kill')) {
$ok = @posix_kill($pid, $signal);
} elseif ($ok = proc_open(sprintf('kill -%d %d', $signal, $pid), array(2 => array('pipe', 'w')), $pipes)) {
$ok = false === fgets($pipes[2]);
@@ -1436,12 +1630,58 @@ class Process
return true;
}
private function prepareWindowsCommandLine($cmd, array &$env)
{
$uid = uniqid('', true);
$varCount = 0;
$varCache = array();
$cmd = preg_replace_callback(
'/"(?:(
[^"%!^]*+
(?:
(?: !LF! | "(?:\^[%!^])?+" )
[^"%!^]*+
)++
) | [^"]*+ )"/x',
function ($m) use (&$env, &$varCache, &$varCount, $uid) {
if (!isset($m[1])) {
return $m[0];
}
if (isset($varCache[$m[0]])) {
return $varCache[$m[0]];
}
if (false !== strpos($value = $m[1], "\0")) {
$value = str_replace("\0", '?', $value);
}
if (false === strpbrk($value, "\"%!\n")) {
return '"'.$value.'"';
}
$value = str_replace(array('!LF!', '"^!"', '"^%"', '"^^"', '""'), array("\n", '!', '%', '^', '"'), $value);
$value = '"'.preg_replace('/(\\\\*)"/', '$1$1\\"', $value).'"';
$var = $uid.++$varCount;
$env[$var] = $value;
return $varCache[$m[0]] = '!'.$var.'!';
},
$cmd
);
$cmd = 'cmd /V:ON /E:ON /D /C ('.str_replace("\n", ' ', $cmd).')';
foreach ($this->processPipes->getFiles() as $offset => $filename) {
$cmd .= ' '.$offset.'>"'.$filename.'"';
}
return $cmd;
}
/**
* Ensures the process is running or terminated, throws a LogicException if the process has a not started.
*
* @param string $functionName The function name that was called
*
* @throws LogicException If the process has not run.
* @throws LogicException if the process has not run
*/
private function requireProcessIsStarted($functionName)
{
@@ -1455,7 +1695,7 @@ class Process
*
* @param string $functionName The function name that was called
*
* @throws LogicException If the process is not yet terminated.
* @throws LogicException if the process is not yet terminated
*/
private function requireProcessIsTerminated($functionName)
{
@@ -1463,4 +1703,49 @@ class Process
throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
}
}
/**
* Escapes a string to be used as a shell argument.
*
* @param string $argument The argument that will be escaped
*
* @return string The escaped argument
*/
private function escapeArgument($argument)
{
if ('\\' !== \DIRECTORY_SEPARATOR) {
return "'".str_replace("'", "'\\''", $argument)."'";
}
if ('' === $argument = (string) $argument) {
return '""';
}
if (false !== strpos($argument, "\0")) {
$argument = str_replace("\0", '?', $argument);
}
if (!preg_match('/[\/()%!^"<>&|\s]/', $argument)) {
return $argument;
}
$argument = preg_replace('/(\\\\+)$/', '$1$1', $argument);
return '"'.str_replace(array('"', '^', '%', '!', "\n"), array('""', '"^^"', '"^%"', '"^!"', '!LF!'), $argument).'"';
}
private function getDefaultEnv()
{
$env = array();
foreach ($_SERVER as $k => $v) {
if (\is_string($v) && false !== $v = getenv($k)) {
$env[$k] = $v;
}
}
foreach ($_ENV as $k => $v) {
if (\is_string($v)) {
$env[$k] = $v;
}
}
return $env;
}
}

View File

@@ -11,13 +11,15 @@
namespace Symfony\Component\Process;
@trigger_error(sprintf('The %s class is deprecated since Symfony 3.4 and will be removed in 4.0. Use the Process class instead.', ProcessBuilder::class), E_USER_DEPRECATED);
use Symfony\Component\Process\Exception\InvalidArgumentException;
use Symfony\Component\Process\Exception\LogicException;
/**
* Process builder.
*
* @author Kris Wallsmith <kris@symfony.com>
*
* @deprecated since version 3.4, to be removed in 4.0. Use the Process class instead.
*/
class ProcessBuilder
{
@@ -26,14 +28,12 @@ class ProcessBuilder
private $env = array();
private $input;
private $timeout = 60;
private $options = array();
private $options;
private $inheritEnv = true;
private $prefix = array();
private $outputDisabled = false;
/**
* Constructor.
*
* @param string[] $arguments An array of arguments
*/
public function __construct(array $arguments = array())
@@ -46,7 +46,7 @@ class ProcessBuilder
*
* @param string[] $arguments An array of arguments
*
* @return ProcessBuilder
* @return static
*/
public static function create(array $arguments = array())
{
@@ -58,7 +58,7 @@ class ProcessBuilder
*
* @param string $argument A command argument
*
* @return ProcessBuilder
* @return $this
*/
public function add($argument)
{
@@ -74,11 +74,11 @@ class ProcessBuilder
*
* @param string|array $prefix A command prefix or an array of command prefixes
*
* @return ProcessBuilder
* @return $this
*/
public function setPrefix($prefix)
{
$this->prefix = is_array($prefix) ? $prefix : array($prefix);
$this->prefix = \is_array($prefix) ? $prefix : array($prefix);
return $this;
}
@@ -91,7 +91,7 @@ class ProcessBuilder
*
* @param string[] $arguments
*
* @return ProcessBuilder
* @return $this
*/
public function setArguments(array $arguments)
{
@@ -105,7 +105,7 @@ class ProcessBuilder
*
* @param null|string $cwd The working directory
*
* @return ProcessBuilder
* @return $this
*/
public function setWorkingDirectory($cwd)
{
@@ -119,7 +119,7 @@ class ProcessBuilder
*
* @param bool $inheritEnv
*
* @return ProcessBuilder
* @return $this
*/
public function inheritEnvironmentVariables($inheritEnv = true)
{
@@ -137,7 +137,7 @@ class ProcessBuilder
* @param string $name The variable name
* @param null|string $value The variable value
*
* @return ProcessBuilder
* @return $this
*/
public function setEnv($name, $value)
{
@@ -155,7 +155,7 @@ class ProcessBuilder
*
* @param array $variables The variables
*
* @return ProcessBuilder
* @return $this
*/
public function addEnvironmentVariables(array $variables)
{
@@ -167,9 +167,9 @@ class ProcessBuilder
/**
* Sets the input of the process.
*
* @param mixed $input The input as a string
* @param resource|string|int|float|bool|\Traversable|null $input The input content
*
* @return ProcessBuilder
* @return $this
*
* @throws InvalidArgumentException In case the argument is invalid
*/
@@ -187,7 +187,7 @@ class ProcessBuilder
*
* @param float|null $timeout
*
* @return ProcessBuilder
* @return $this
*
* @throws InvalidArgumentException
*/
@@ -216,7 +216,7 @@ class ProcessBuilder
* @param string $name The option name
* @param string $value The option value
*
* @return ProcessBuilder
* @return $this
*/
public function setOption($name, $value)
{
@@ -228,7 +228,7 @@ class ProcessBuilder
/**
* Disables fetching output and error output from the underlying process.
*
* @return ProcessBuilder
* @return $this
*/
public function disableOutput()
{
@@ -240,7 +240,7 @@ class ProcessBuilder
/**
* Enables fetching output and error output from the underlying process.
*
* @return ProcessBuilder
* @return $this
*/
public function enableOutput()
{
@@ -258,23 +258,19 @@ class ProcessBuilder
*/
public function getProcess()
{
if (0 === count($this->prefix) && 0 === count($this->arguments)) {
if (0 === \count($this->prefix) && 0 === \count($this->arguments)) {
throw new LogicException('You must add() command arguments before calling getProcess().');
}
$options = $this->options;
$arguments = array_merge($this->prefix, $this->arguments);
$script = implode(' ', array_map(array(__NAMESPACE__.'\\ProcessUtils', 'escapeArgument'), $arguments));
$process = new Process($arguments, $this->cwd, $this->env, $this->input, $this->timeout, $this->options);
// to preserve the BC with symfony <3.3, we convert the array structure
// to a string structure to avoid the prefixing with the exec command
$process->setCommandLine($process->getCommandLine());
if ($this->inheritEnv) {
$env = array_replace($_ENV, $_SERVER, $this->env);
} else {
$env = $this->env;
$process->inheritEnvironmentVariables();
}
$process = new Process($script, $this->cwd, $env, $this->input, $this->timeout, $options);
if ($this->outputDisabled) {
$process->disableOutput();
}

View File

@@ -35,14 +35,18 @@ class ProcessUtils
* @param string $argument The argument that will be escaped
*
* @return string The escaped argument
*
* @deprecated since version 3.3, to be removed in 4.0. Use a command line array or give env vars to the `Process::start/run()` method instead.
*/
public static function escapeArgument($argument)
{
@trigger_error('The '.__METHOD__.'() method is deprecated since Symfony 3.3 and will be removed in 4.0. Use a command line array or give env vars to the Process::start/run() method instead.', E_USER_DEPRECATED);
//Fix for PHP bug #43784 escapeshellarg removes % from given string
//Fix for PHP bug #49446 escapeshellarg doesn't work on Windows
//@see https://bugs.php.net/bug.php?id=43784
//@see https://bugs.php.net/bug.php?id=49446
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
if ('' === $argument) {
return escapeshellarg($argument);
}
@@ -71,7 +75,7 @@ class ProcessUtils
return $escapedArgument;
}
return escapeshellarg($argument);
return "'".str_replace("'", "'\\''", $argument)."'";
}
/**
@@ -87,17 +91,26 @@ class ProcessUtils
public static function validateInput($caller, $input)
{
if (null !== $input) {
if (is_resource($input)) {
if (\is_resource($input)) {
return $input;
}
if (is_string($input)) {
if (\is_string($input)) {
return $input;
}
if (is_scalar($input)) {
return (string) $input;
}
if ($input instanceof Process) {
return $input->getIterator($input::ITER_SKIP_ERR);
}
if ($input instanceof \Iterator) {
return $input;
}
if ($input instanceof \Traversable) {
return new \IteratorIterator($input);
}
throw new InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller));
throw new InvalidArgumentException(sprintf('%s only accepts strings, Traversable objects or stream resources.', $caller));
}
return $input;
@@ -105,6 +118,6 @@ class ProcessUtils
private static function isSurroundedBy($arg, $char)
{
return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
return 2 < \strlen($arg) && $char === $arg[0] && $char === $arg[\strlen($arg) - 1];
}
}

View File

@@ -11,12 +11,13 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\ExecutableFinder;
/**
* @author Chris Smith <chris@cs278.org>
*/
class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
class ExecutableFinderTest extends TestCase
{
private $path;
@@ -40,7 +41,7 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
$this->markTestSkipped('Cannot test when open_basedir is set');
}
$this->setPath(dirname(PHP_BINARY));
$this->setPath(\dirname(PHP_BINARY));
$finder = new ExecutableFinder();
$result = $finder->find($this->getPhpBinaryName());
@@ -72,7 +73,7 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
$this->setPath('');
$extraDirs = array(dirname(PHP_BINARY));
$extraDirs = array(\dirname(PHP_BINARY));
$finder = new ExecutableFinder();
$result = $finder->find($this->getPhpBinaryName(), null, $extraDirs);
@@ -82,7 +83,7 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
public function testFindWithOpenBaseDir()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Cannot run test on windows');
}
@@ -90,7 +91,7 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
$this->markTestSkipped('Cannot test when open_basedir is set');
}
$this->iniSet('open_basedir', dirname(PHP_BINARY).(!defined('HHVM_VERSION') || HHVM_VERSION_ID >= 30800 ? PATH_SEPARATOR.'/' : ''));
$this->iniSet('open_basedir', \dirname(PHP_BINARY).(!\defined('HHVM_VERSION') || HHVM_VERSION_ID >= 30800 ? PATH_SEPARATOR.'/' : ''));
$finder = new ExecutableFinder();
$result = $finder->find($this->getPhpBinaryName());
@@ -103,12 +104,12 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
if (ini_get('open_basedir')) {
$this->markTestSkipped('Cannot test when open_basedir is set');
}
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Cannot run test on windows');
}
$this->setPath('');
$this->iniSet('open_basedir', PHP_BINARY.(!defined('HHVM_VERSION') || HHVM_VERSION_ID >= 30800 ? PATH_SEPARATOR.'/' : ''));
$this->iniSet('open_basedir', PHP_BINARY.(!\defined('HHVM_VERSION') || HHVM_VERSION_ID >= 30800 ? PATH_SEPARATOR.'/' : ''));
$finder = new ExecutableFinder();
$result = $finder->find($this->getPhpBinaryName(), false);
@@ -116,9 +117,39 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
$this->assertSamePath(PHP_BINARY, $result);
}
/**
* @requires PHP 5.4
*/
public function testFindBatchExecutableOnWindows()
{
if (ini_get('open_basedir')) {
$this->markTestSkipped('Cannot test when open_basedir is set');
}
if ('\\' !== \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Can be only tested on windows');
}
$target = tempnam(sys_get_temp_dir(), 'example-windows-executable');
touch($target);
touch($target.'.BAT');
$this->assertFalse(is_executable($target));
$this->setPath(sys_get_temp_dir());
$finder = new ExecutableFinder();
$result = $finder->find(basename($target), false);
unlink($target);
unlink($target.'.BAT');
$this->assertSamePath($target.'.BAT', $result);
}
private function assertSamePath($expected, $tested)
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals(strtolower($expected), strtolower($tested));
} else {
$this->assertEquals($expected, $tested);
@@ -127,6 +158,6 @@ class ExecutableFinderTest extends \PHPUnit_Framework_TestCase
private function getPhpBinaryName()
{
return basename(PHP_BINARY, '\\' === DIRECTORY_SEPARATOR ? '.exe' : '');
return basename(PHP_BINARY, '\\' === \DIRECTORY_SEPARATOR ? '.exe' : '');
}
}

View File

@@ -11,26 +11,27 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\PhpExecutableFinder;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase
class PhpExecutableFinderTest extends TestCase
{
/**
* tests find() with the constant PHP_BINARY.
*/
public function testFind()
{
if (defined('HHVM_VERSION')) {
if (\defined('HHVM_VERSION')) {
$this->markTestSkipped('Should not be executed in HHVM context.');
}
$f = new PhpExecutableFinder();
$current = PHP_BINARY;
$args = 'phpdbg' === PHP_SAPI ? ' -qrr' : '';
$args = 'phpdbg' === \PHP_SAPI ? ' -qrr' : '';
$this->assertEquals($current.$args, $f->find(), '::find() returns the executable PHP');
$this->assertEquals($current, $f->find(false), '::find() returns the executable PHP');
@@ -41,7 +42,7 @@ class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase
*/
public function testFindWithHHVM()
{
if (!defined('HHVM_VERSION')) {
if (!\defined('HHVM_VERSION')) {
$this->markTestSkipped('Should be executed in HHVM context.');
}
@@ -60,9 +61,9 @@ class PhpExecutableFinderTest extends \PHPUnit_Framework_TestCase
{
$f = new PhpExecutableFinder();
if (defined('HHVM_VERSION')) {
if (\defined('HHVM_VERSION')) {
$this->assertEquals($f->findArguments(), array('--php'), '::findArguments() returns HHVM arguments');
} elseif ('phpdbg' === PHP_SAPI) {
} elseif ('phpdbg' === \PHP_SAPI) {
$this->assertEquals($f->findArguments(), array('-qrr'), '::findArguments() returns phpdbg arguments');
} else {
$this->assertEquals($f->findArguments(), array(), '::findArguments() returns no arguments');

View File

@@ -11,10 +11,10 @@
namespace Symfony\Component\Process\Tests;
use Symfony\Component\Process\PhpExecutableFinder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\PhpProcess;
class PhpProcessTest extends \PHPUnit_Framework_TestCase
class PhpProcessTest extends TestCase
{
public function testNonBlockingWorks()
{
@@ -31,19 +31,18 @@ PHP
public function testCommandLine()
{
$process = new PhpProcess(<<<'PHP'
<?php echo 'foobar';
<?php echo phpversion().PHP_SAPI;
PHP
);
$commandLine = $process->getCommandLine();
$f = new PhpExecutableFinder();
$this->assertContains($f->find(), $commandLine, '::getCommandLine() returns the command line of PHP before start');
$process->start();
$this->assertContains($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after start');
$process->wait();
$this->assertContains($commandLine, $process->getCommandLine(), '::getCommandLine() returns the command line of PHP after wait');
$this->assertSame(PHP_VERSION.\PHP_SAPI, $process->getOutput());
}
}

View File

@@ -35,22 +35,22 @@ while ($read || $write) {
}
if (in_array(STDOUT, $w) && strlen($out) > 0) {
$written = fwrite(STDOUT, (binary) $out, 32768);
$written = fwrite(STDOUT, (string) $out, 32768);
if (false === $written) {
die(ERR_WRITE_FAILED);
}
$out = (binary) substr($out, $written);
$out = (string) substr($out, $written);
}
if (null === $read && '' === $out) {
$write = array_diff($write, array(STDOUT));
}
if (in_array(STDERR, $w) && strlen($err) > 0) {
$written = fwrite(STDERR, (binary) $err, 32768);
$written = fwrite(STDERR, (string) $err, 32768);
if (false === $written) {
die(ERR_WRITE_FAILED);
}
$err = (binary) substr($err, $written);
$err = (string) substr($err, $written);
}
if (null === $read && '' === $err) {
$write = array_diff($write, array(STDERR));

View File

@@ -11,23 +11,28 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\ProcessBuilder;
class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
/**
* @group legacy
*/
class ProcessBuilderTest extends TestCase
{
public function testInheritEnvironmentVars()
{
$_ENV['MY_VAR_1'] = 'foo';
$proc = ProcessBuilder::create()
->add('foo')
->getProcess();
unset($_ENV['MY_VAR_1']);
$this->assertTrue($proc->areEnvironmentVariablesInherited());
$env = $proc->getEnv();
$this->assertArrayHasKey('MY_VAR_1', $env);
$this->assertEquals('foo', $env['MY_VAR_1']);
$proc = ProcessBuilder::create()
->add('foo')
->inheritEnvironmentVariables(false)
->getProcess();
$this->assertFalse($proc->areEnvironmentVariablesInherited());
}
public function testAddEnvironmentVariables()
@@ -41,29 +46,12 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
->add('command')
->setEnv('foo', 'bar2')
->addEnvironmentVariables($env)
->inheritEnvironmentVariables(false)
->getProcess()
;
$this->assertSame($env, $proc->getEnv());
}
public function testProcessShouldInheritAndOverrideEnvironmentVars()
{
$_ENV['MY_VAR_1'] = 'foo';
$proc = ProcessBuilder::create()
->setEnv('MY_VAR_1', 'bar')
->add('foo')
->getProcess();
unset($_ENV['MY_VAR_1']);
$env = $proc->getEnv();
$this->assertArrayHasKey('MY_VAR_1', $env);
$this->assertEquals('bar', $env['MY_VAR_1']);
}
/**
* @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
*/
@@ -102,15 +90,15 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$pb->setPrefix('/usr/bin/php');
$proc = $pb->setArguments(array('-v'))->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" "-v"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" -v', $proc->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php' '-v'", $proc->getCommandLine());
}
$proc = $pb->setArguments(array('-i'))->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" "-i"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" -i', $proc->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php' '-i'", $proc->getCommandLine());
}
@@ -122,15 +110,15 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$pb->setPrefix(array('/usr/bin/php', 'composer.phar'));
$proc = $pb->setArguments(array('-v'))->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" "composer.phar" "-v"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" composer.phar -v', $proc->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php' 'composer.phar' '-v'", $proc->getCommandLine());
}
$proc = $pb->setArguments(array('-i'))->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" "composer.phar" "-i"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php" composer.phar -i', $proc->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php' 'composer.phar' '-i'", $proc->getCommandLine());
}
@@ -141,8 +129,8 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$pb = new ProcessBuilder(array('%path%', 'foo " bar', '%baz%baz'));
$proc = $pb->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertSame('^%"path"^% "foo \\" bar" "%baz%baz"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertSame('""^%"path"^%"" "foo "" bar" ""^%"baz"^%"baz"', $proc->getCommandLine());
} else {
$this->assertSame("'%path%' 'foo \" bar' '%baz%baz'", $proc->getCommandLine());
}
@@ -154,8 +142,8 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$pb->setPrefix('%prefix%');
$proc = $pb->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
$this->assertSame('^%"prefix"^% "arg"', $proc->getCommandLine());
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertSame('""^%"prefix"^%"" arg', $proc->getCommandLine());
} else {
$this->assertSame("'%prefix%' 'arg'", $proc->getCommandLine());
}
@@ -175,7 +163,7 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
->setPrefix('/usr/bin/php')
->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
@@ -187,7 +175,7 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
$process = ProcessBuilder::create(array('/usr/bin/php'))
->getProcess();
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->assertEquals('"/usr/bin/php"', $process->getCommandLine());
} else {
$this->assertEquals("'/usr/bin/php'", $process->getCommandLine());
@@ -215,11 +203,24 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
* @expectedExceptionMessage Symfony\Component\Process\ProcessBuilder::setInput only accepts strings or stream resources.
* @expectedExceptionMessage Symfony\Component\Process\ProcessBuilder::setInput only accepts strings, Traversable objects or stream resources.
*/
public function testInvalidInput()
{
$builder = ProcessBuilder::create();
$builder->setInput(array());
}
public function testDoesNotPrefixExec()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('This test cannot run on Windows.');
}
$builder = ProcessBuilder::create(array('command', '-v', 'ls'));
$process = $builder->getProcess();
$process->run();
$this->assertTrue($process->isSuccessful());
}
}

View File

@@ -11,31 +11,30 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Exception\ProcessFailedException;
/**
* @author Sebastian Marek <proofek@gmail.com>
*/
class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase
class ProcessFailedExceptionTest extends TestCase
{
/**
* tests ProcessFailedException throws exception if the process was successful.
*/
public function testProcessFailedExceptionThrowsException()
{
$process = $this->getMock(
'Symfony\Component\Process\Process',
array('isSuccessful'),
array('php')
);
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful'))->setConstructorArgs(array('php'))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(true));
$this->setExpectedException(
'\InvalidArgumentException',
'Expected a failed process, but the given process was successful.'
);
if (method_exists($this, 'expectException')) {
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Expected a failed process, but the given process was successful.');
} else {
$this->setExpectedException(\InvalidArgumentException::class, 'Expected a failed process, but the given process was successful.');
}
new ProcessFailedException($process);
}
@@ -53,11 +52,7 @@ class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase
$errorOutput = 'FATAL: Unexpected error';
$workingDirectory = getcwd();
$process = $this->getMock(
'Symfony\Component\Process\Process',
array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'),
array($cmd)
);
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'getOutput', 'getErrorOutput', 'getExitCode', 'getExitCodeText', 'isOutputDisabled', 'getWorkingDirectory'))->setConstructorArgs(array($cmd))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(false));
@@ -105,11 +100,7 @@ class ProcessFailedExceptionTest extends \PHPUnit_Framework_TestCase
$exitText = 'General error';
$workingDirectory = getcwd();
$process = $this->getMock(
'Symfony\Component\Process\Process',
array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'),
array($cmd)
);
$process = $this->getMockBuilder('Symfony\Component\Process\Process')->setMethods(array('isSuccessful', 'isOutputDisabled', 'getExitCode', 'getExitCodeText', 'getOutput', 'getErrorOutput', 'getWorkingDirectory'))->setConstructorArgs(array($cmd))->getMock();
$process->expects($this->once())
->method('isSuccessful')
->will($this->returnValue(false));

View File

@@ -11,9 +11,11 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Exception\RuntimeException;
use Symfony\Component\Process\InputStream;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Pipes\PipesInterface;
use Symfony\Component\Process\Process;
@@ -21,7 +23,7 @@ use Symfony\Component\Process\Process;
/**
* @author Robert Schönthal <seroscho@googlemail.com>
*/
class ProcessTest extends \PHPUnit_Framework_TestCase
class ProcessTest extends TestCase
{
private static $phpBin;
private static $process;
@@ -31,13 +33,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public static function setUpBeforeClass()
{
$phpBin = new PhpExecutableFinder();
self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === PHP_SAPI ? 'php' : $phpBin->find());
if ('\\' !== DIRECTORY_SEPARATOR) {
// exec is mandatory to deal with sending a signal to the process
// see https://github.com/symfony/symfony/issues/5030 about prepending
// command with exec
self::$phpBin = 'exec '.self::$phpBin;
}
self::$phpBin = getenv('SYMFONY_PROCESS_PHP_TEST_BINARY') ?: ('phpdbg' === \PHP_SAPI ? 'php' : $phpBin->find());
ob_start();
phpinfo(INFO_GENERAL);
@@ -52,13 +48,31 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
}
}
/**
* @group legacy
* @expectedDeprecation The provided cwd does not exist. Command is currently ran against getcwd(). This behavior is deprecated since Symfony 3.4 and will be removed in 4.0.
*/
public function testInvalidCwd()
{
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('False-positive on Windows/appveyor.');
}
// Check that it works fine if the CWD exists
$cmd = new Process('echo test', __DIR__);
$cmd->run();
$cmd = new Process('echo test', __DIR__.'/notfound/');
$cmd->run();
}
public function testThatProcessDoesNotThrowWarningDuringRun()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('This test is transient on Windows');
}
@trigger_error('Test Error', E_USER_NOTICE);
$process = $this->getProcess(self::$phpBin." -r 'sleep(3)'");
$process = $this->getProcessForCode('sleep(3)');
$process->run();
$actualError = error_get_last();
$this->assertEquals('Test Error', $actualError['message']);
@@ -101,7 +115,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testStopWithTimeoutIsActuallyWorking()
{
$p = $this->getProcess(self::$phpBin.' '.__DIR__.'/NonStopableProcess.php 30');
$p = $this->getProcess(array(self::$phpBin, __DIR__.'/NonStopableProcess.php', 30));
$p->start();
while (false === strpos($p->getOutput(), 'received')) {
@@ -127,7 +141,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$expectedOutputSize = PipesInterface::CHUNK_SIZE * 2 + 2;
$code = sprintf('echo str_repeat(\'*\', %d);', $expectedOutputSize);
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
$p = $this->getProcessForCode($code);
$p->start();
@@ -144,7 +158,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$o = $p->getOutput();
$this->assertEquals($expectedOutputSize, strlen($o));
$this->assertEquals($expectedOutputSize, \strlen($o));
}
public function testCallbacksAreExecutedWithStart()
@@ -166,7 +180,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testProcessResponses($expected, $getter, $code)
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
$p = $this->getProcessForCode($code);
$p->run();
$this->assertSame($expected, $p->$getter());
@@ -182,12 +196,12 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$expected = str_repeat(str_repeat('*', 1024), $size).'!';
$expectedLength = (1024 * $size) + 1;
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
$p = $this->getProcessForCode($code);
$p->setInput($expected);
$p->run();
$this->assertEquals($expectedLength, strlen($p->getOutput()));
$this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
$this->assertEquals($expectedLength, \strlen($p->getOutput()));
$this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
}
/**
@@ -202,14 +216,14 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
fwrite($stream, $expected);
rewind($stream);
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg($code)));
$p = $this->getProcessForCode($code);
$p->setInput($stream);
$p->run();
fclose($stream);
$this->assertEquals($expectedLength, strlen($p->getOutput()));
$this->assertEquals($expectedLength, strlen($p->getErrorOutput()));
$this->assertEquals($expectedLength, \strlen($p->getOutput()));
$this->assertEquals($expectedLength, \strlen($p->getErrorOutput()));
}
public function testLiveStreamAsInput()
@@ -218,7 +232,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
fwrite($stream, 'hello');
rewind($stream);
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('stream_copy_to_stream(STDIN, STDOUT);')));
$p = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
$p->setInput($stream);
$p->start(function ($type, $data) use ($stream) {
if ('hello' === $data) {
@@ -236,7 +250,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testSetInputWhileRunningThrowsAnException()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
$process = $this->getProcessForCode('sleep(30);');
$process->start();
try {
$process->setInput('foobar');
@@ -252,7 +266,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider provideInvalidInputValues
* @expectedException \Symfony\Component\Process\Exception\InvalidArgumentException
* @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings or stream resources.
* @expectedExceptionMessage Symfony\Component\Process\Process::setInput only accepts strings, Traversable objects or stream resources.
*/
public function testInvalidInput($value)
{
@@ -289,7 +303,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function chainedCommandsOutputProvider()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
return array(
array("2 \r\n2\r\n", '&&', '2'),
);
@@ -313,11 +327,24 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testCallbackIsExecutedForOutput()
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('echo \'foo\';')));
$p = $this->getProcessForCode('echo \'foo\';');
$called = false;
$p->run(function ($type, $buffer) use (&$called) {
$called = $buffer === 'foo';
$called = 'foo' === $buffer;
});
$this->assertTrue($called, 'The callback should be executed with the output');
}
public function testCallbackIsExecutedForOutputWheneverOutputIsDisabled()
{
$p = $this->getProcessForCode('echo \'foo\';');
$p->disableOutput();
$called = false;
$p->run(function ($type, $buffer) use (&$called) {
$called = 'foo' === $buffer;
});
$this->assertTrue($called, 'The callback should be executed with the output');
@@ -325,7 +352,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testGetErrorOutput()
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
$p->run();
$this->assertEquals(3, preg_match_all('/ERROR/', $p->getErrorOutput(), $matches));
@@ -333,7 +360,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testFlushErrorOutput()
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }')));
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\'php://stderr\', \'ERROR\'); $n++; }');
$p->run();
$p->clearErrorOutput();
@@ -347,7 +374,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
{
$lock = tempnam(sys_get_temp_dir(), __FUNCTION__);
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');')));
$p = $this->getProcessForCode('file_put_contents($s = \''.$uri.'\', \'foo\'); flock(fopen('.var_export($lock, true).', \'r\'), LOCK_EX); file_put_contents($s, \'bar\');');
$h = fopen($lock, 'w');
flock($h, LOCK_EX);
@@ -378,7 +405,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testGetOutput()
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }')));
$p = $this->getProcessForCode('$n = 0; while ($n < 3) { echo \' foo \'; $n++; }');
$p->run();
$this->assertEquals(3, preg_match_all('/foo/', $p->getOutput(), $matches));
@@ -386,7 +413,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testFlushOutput()
{
$p = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('$n=0;while ($n<3) {echo \' foo \';$n++;}')));
$p = $this->getProcessForCode('$n=0;while ($n<3) {echo \' foo \';$n++;}');
$p->run();
$p->clearOutput();
@@ -395,7 +422,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testZeroAsOutput()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
// see http://stackoverflow.com/questions/7105433/windows-batch-echo-without-new-line
$p = $this->getProcess('echo | set /p dummyName=0');
} else {
@@ -408,7 +435,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testExitCodeCommandFailed()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX exit code');
}
$this->skipIfNotEnhancedSigchild();
@@ -420,13 +447,16 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$this->assertGreaterThan(0, $process->getExitCode());
}
/**
* @group tty
*/
public function testTTYCommand()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not have /dev/tty support');
}
$process = $this->getProcess('echo "foo" >> /dev/null && '.self::$phpBin.' -r "usleep(100000);"');
$process = $this->getProcess('echo "foo" >> /dev/null && '.$this->getProcessForCode('usleep(100000);')->getCommandLine());
$process->setTty(true);
$process->start();
$this->assertTrue($process->isRunning());
@@ -435,9 +465,12 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$this->assertSame(Process::STATUS_TERMINATED, $process->getStatus());
}
/**
* @group tty
*/
public function testTTYCommandExitCode()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does have /dev/tty support');
}
$this->skipIfNotEnhancedSigchild();
@@ -455,7 +488,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testTTYInWindowsEnvironment()
{
if ('\\' !== DIRECTORY_SEPARATOR) {
if ('\\' !== \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('This test is for Windows platform only');
}
@@ -530,7 +563,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testStartIsNonBlocking()
{
$process = $this->getProcess(self::$phpBin.' -r "usleep(500000);"');
$process = $this->getProcessForCode('usleep(500000);');
$start = microtime(true);
$process->start();
$end = microtime(true);
@@ -542,14 +575,14 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
{
$process = $this->getProcess('echo foo');
$process->run();
$this->assertTrue(strlen($process->getOutput()) > 0);
$this->assertGreaterThan(0, \strlen($process->getOutput()));
}
public function testGetExitCodeIsNullOnStart()
{
$this->skipIfNotEnhancedSigchild();
$process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
$process = $this->getProcessForCode('usleep(100000);');
$this->assertNull($process->getExitCode());
$process->start();
$this->assertNull($process->getExitCode());
@@ -561,7 +594,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
{
$this->skipIfNotEnhancedSigchild();
$process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
$process = $this->getProcessForCode('usleep(100000);');
$process->run();
$this->assertEquals(0, $process->getExitCode());
$process->start();
@@ -581,7 +614,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testStatus()
{
$process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
$process = $this->getProcessForCode('usleep(100000);');
$this->assertFalse($process->isRunning());
$this->assertFalse($process->isStarted());
$this->assertFalse($process->isTerminated());
@@ -600,7 +633,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testStop()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(31);"');
$process = $this->getProcessForCode('sleep(31);');
$process->start();
$this->assertTrue($process->isRunning());
$process->stop();
@@ -620,7 +653,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
{
$this->skipIfNotEnhancedSigchild();
$process = $this->getProcess(self::$phpBin.' -r "usleep(100000);"');
$process = $this->getProcessForCode('usleep(100000);');
$process->start();
$this->assertFalse($process->isSuccessful());
@@ -634,14 +667,14 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
{
$this->skipIfNotEnhancedSigchild();
$process = $this->getProcess(self::$phpBin.' -r "throw new \Exception(\'BOUM\');"');
$process = $this->getProcessForCode('throw new \Exception(\'BOUM\');');
$process->run();
$this->assertFalse($process->isSuccessful());
}
public function testProcessIsNotSignaled()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
$this->skipIfNotEnhancedSigchild();
@@ -653,7 +686,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testProcessWithoutTermSignal()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
$this->skipIfNotEnhancedSigchild();
@@ -665,12 +698,12 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testProcessIsSignaledIfStopped()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('Windows does not support POSIX signals');
}
$this->skipIfNotEnhancedSigchild();
$process = $this->getProcess(self::$phpBin.' -r "sleep(32);"');
$process = $this->getProcessForCode('sleep(32);');
$process->start();
$process->stop();
$this->assertTrue($process->hasBeenSignaled());
@@ -683,12 +716,12 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testProcessThrowsExceptionWhenExternallySignaled()
{
if (!function_exists('posix_kill')) {
if (!\function_exists('posix_kill')) {
$this->markTestSkipped('Function posix_kill is required.');
}
$this->skipIfNotEnhancedSigchild(false);
$process = $this->getProcess(self::$phpBin.' -r "sleep(32.1)"');
$process = $this->getProcessForCode('sleep(32.1);');
$process->start();
posix_kill($process->getPid(), 9); // SIGKILL
@@ -697,7 +730,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testRestart()
{
$process1 = $this->getProcess(self::$phpBin.' -r "echo getmypid();"');
$process1 = $this->getProcessForCode('echo getmypid();');
$process1->run();
$process2 = $process1->restart();
@@ -706,8 +739,8 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
// Ensure that both processed finished and the output is numeric
$this->assertFalse($process1->isRunning());
$this->assertFalse($process2->isRunning());
$this->assertTrue(is_numeric($process1->getOutput()));
$this->assertTrue(is_numeric($process2->getOutput()));
$this->assertInternalType('numeric', $process1->getOutput());
$this->assertInternalType('numeric', $process2->getOutput());
// Ensure that restart returned a new process by check that the output is different
$this->assertNotEquals($process1->getOutput(), $process2->getOutput());
@@ -719,7 +752,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testRunProcessWithTimeout()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(30);"');
$process = $this->getProcessForCode('sleep(30);');
$process->setTimeout(0.1);
$start = microtime(true);
try {
@@ -733,6 +766,27 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
throw $e;
}
/**
* @expectedException \Symfony\Component\Process\Exception\ProcessTimedOutException
* @expectedExceptionMessage exceeded the timeout of 0.1 seconds.
*/
public function testIterateOverProcessWithTimeout()
{
$process = $this->getProcessForCode('sleep(30);');
$process->setTimeout(0.1);
$start = microtime(true);
try {
$process->start();
foreach ($process as $buffer);
$this->fail('A RuntimeException should have been raised');
} catch (RuntimeException $e) {
}
$this->assertLessThan(15, microtime(true) - $start);
throw $e;
}
public function testCheckTimeoutOnNonStartedProcess()
{
$process = $this->getProcess('echo foo');
@@ -752,7 +806,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testCheckTimeoutOnStartedProcess()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(33);"');
$process = $this->getProcessForCode('sleep(33);');
$process->setTimeout(0.1);
$process->start();
@@ -774,7 +828,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testIdleTimeout()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(34);"');
$process = $this->getProcessForCode('sleep(34);');
$process->setTimeout(60);
$process->setIdleTimeout(0.1);
@@ -791,7 +845,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testIdleTimeoutNotExceededWhenOutputIsSent()
{
$process = $this->getProcess(sprintf('%s -r %s', self::$phpBin, escapeshellarg('while (true) {echo \'foo \'; usleep(1000);}')));
$process = $this->getProcessForCode('while (true) {echo \'foo \'; usleep(1000);}');
$process->setTimeout(1);
$process->start();
@@ -817,7 +871,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testStartAfterATimeout()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(35);"');
$process = $this->getProcessForCode('sleep(35);');
$process->setTimeout(0.1);
try {
@@ -835,7 +889,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testGetPid()
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(36);"');
$process = $this->getProcessForCode('sleep(36);');
$process->start();
$this->assertGreaterThan(0, $process->getPid());
$process->stop(0);
@@ -859,7 +913,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testSignal()
{
$process = $this->getProcess(self::$phpBin.' '.__DIR__.'/SignalListener.php');
$process = $this->getProcess(array(self::$phpBin, __DIR__.'/SignalListener.php'));
$process->start();
while (false === strpos($process->getOutput(), 'Caught')) {
@@ -908,7 +962,14 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testMethodsThatNeedARunningProcess($method)
{
$process = $this->getProcess('foo');
$this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
if (method_exists($this, 'expectException')) {
$this->expectException('Symfony\Component\Process\Exception\LogicException');
$this->expectExceptionMessage(sprintf('Process must be started before calling %s.', $method));
} else {
$this->setExpectedException('Symfony\Component\Process\Exception\LogicException', sprintf('Process must be started before calling %s.', $method));
}
$process->{$method}();
}
@@ -925,12 +986,12 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider provideMethodsThatNeedATerminatedProcess
* @expectedException Symfony\Component\Process\Exception\LogicException
* @expectedException \Symfony\Component\Process\Exception\LogicException
* @expectedExceptionMessage Process must be terminated before calling
*/
public function testMethodsThatNeedATerminatedProcess($method)
{
$process = $this->getProcess(self::$phpBin.' -r "sleep(37);"');
$process = $this->getProcessForCode('sleep(37);');
$process->start();
try {
$process->{$method}();
@@ -959,11 +1020,11 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testWrongSignal($signal)
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
$this->markTestSkipped('POSIX signals do not work on Windows');
}
$process = $this->getProcess(self::$phpBin.' -r "sleep(38);"');
$process = $this->getProcessForCode('sleep(38);');
$process->start();
try {
$process->signal($signal);
@@ -999,7 +1060,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testDisableOutputWhileRunningThrowsException()
{
$p = $this->getProcess(self::$phpBin.' -r "sleep(39);"');
$p = $this->getProcessForCode('sleep(39);');
$p->start();
$p->disableOutput();
}
@@ -1010,7 +1071,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testEnableOutputWhileRunningThrowsException()
{
$p = $this->getProcess(self::$phpBin.' -r "sleep(40);"');
$p = $this->getProcessForCode('sleep(40);');
$p->disableOutput();
$p->start();
$p->enableOutput();
@@ -1055,29 +1116,6 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
$this->assertSame($process, $process->setIdleTimeout(null));
}
/**
* @dataProvider provideStartMethods
*/
public function testStartWithACallbackAndDisabledOutput($startMethod, $exception, $exceptionMessage)
{
$p = $this->getProcess('foo');
$p->disableOutput();
$this->setExpectedException($exception, $exceptionMessage);
if ('mustRun' === $startMethod) {
$this->skipIfNotEnhancedSigchild();
}
$p->{$startMethod}(function () {});
}
public function provideStartMethods()
{
return array(
array('start', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
array('run', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
array('mustRun', 'Symfony\Component\Process\Exception\LogicException', 'Output has been disabled, enable it to allow the use of a callback.'),
);
}
/**
* @dataProvider provideOutputFetchingMethods
* @expectedException \Symfony\Component\Process\Exception\LogicException
@@ -1085,7 +1123,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testGetOutputWhileDisabled($fetchMethod)
{
$p = $this->getProcess(self::$phpBin.' -r "sleep(41);"');
$p = $this->getProcessForCode('sleep(41);');
$p->disableOutput();
$p->start();
$p->{$fetchMethod}();
@@ -1103,7 +1141,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testStopTerminatesProcessCleanly()
{
$process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(42);"');
$process = $this->getProcessForCode('echo 123; sleep(42);');
$process->run(function () use ($process) {
$process->stop();
});
@@ -1112,7 +1150,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testKillSignalTerminatesProcessCleanly()
{
$process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(43);"');
$process = $this->getProcessForCode('echo 123; sleep(43);');
$process->run(function () use ($process) {
$process->signal(9); // SIGKILL
});
@@ -1121,7 +1159,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
public function testTermSignalTerminatesProcessCleanly()
{
$process = $this->getProcess(self::$phpBin.' -r "echo 123; sleep(44);"');
$process = $this->getProcessForCode('echo 123; sleep(44);');
$process->run(function () use ($process) {
$process->signal(15); // SIGTERM
});
@@ -1145,7 +1183,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
'include \''.__DIR__.'/PipeStdinInStdoutStdErrStreamSelect.php\';',
);
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
// Avoid XL buffers on Windows because of https://bugs.php.net/bug.php?id=65650
$sizes = array(1, 2, 4, 8);
} else {
@@ -1167,7 +1205,7 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*/
public function testIncrementalOutputDoesNotRequireAnotherCall($stream, $method)
{
$process = $this->getProcess(self::$phpBin.' -r '.escapeshellarg('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }'), null, null, null, null);
$process = $this->getProcessForCode('$n = 0; while ($n < 3) { file_put_contents(\''.$stream.'\', $n, 1); $n++; usleep(1000); }', null, null, null, null);
$process->start();
$result = '';
$limit = microtime(true) + 3;
@@ -1189,6 +1227,333 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
);
}
public function testIteratorInput()
{
$input = function () {
yield 'ping';
yield 'pong';
};
$process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);', null, null, $input());
$process->run();
$this->assertSame('pingpong', $process->getOutput());
}
public function testSimpleInputStream()
{
$input = new InputStream();
$process = $this->getProcessForCode('echo \'ping\'; echo fread(STDIN, 4); echo fread(STDIN, 4);');
$process->setInput($input);
$process->start(function ($type, $data) use ($input) {
if ('ping' === $data) {
$input->write('pang');
} elseif (!$input->isClosed()) {
$input->write('pong');
$input->close();
}
});
$process->wait();
$this->assertSame('pingpangpong', $process->getOutput());
}
public function testInputStreamWithCallable()
{
$i = 0;
$stream = fopen('php://memory', 'w+');
$stream = function () use ($stream, &$i) {
if ($i < 3) {
rewind($stream);
fwrite($stream, ++$i);
rewind($stream);
return $stream;
}
};
$input = new InputStream();
$input->onEmpty($stream);
$input->write($stream());
$process = $this->getProcessForCode('echo fread(STDIN, 3);');
$process->setInput($input);
$process->start(function ($type, $data) use ($input) {
$input->close();
});
$process->wait();
$this->assertSame('123', $process->getOutput());
}
public function testInputStreamWithGenerator()
{
$input = new InputStream();
$input->onEmpty(function ($input) {
yield 'pong';
$input->close();
});
$process = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
$process->setInput($input);
$process->start();
$input->write('ping');
$process->wait();
$this->assertSame('pingpong', $process->getOutput());
}
public function testInputStreamOnEmpty()
{
$i = 0;
$input = new InputStream();
$input->onEmpty(function () use (&$i) { ++$i; });
$process = $this->getProcessForCode('echo 123; echo fread(STDIN, 1); echo 456;');
$process->setInput($input);
$process->start(function ($type, $data) use ($input) {
if ('123' === $data) {
$input->close();
}
});
$process->wait();
$this->assertSame(0, $i, 'InputStream->onEmpty callback should be called only when the input *becomes* empty');
$this->assertSame('123456', $process->getOutput());
}
public function testIteratorOutput()
{
$input = new InputStream();
$process = $this->getProcessForCode('fwrite(STDOUT, 123); fwrite(STDERR, 234); flush(); usleep(10000); fwrite(STDOUT, fread(STDIN, 3)); fwrite(STDERR, 456);');
$process->setInput($input);
$process->start();
$output = array();
foreach ($process as $type => $data) {
$output[] = array($type, $data);
break;
}
$expectedOutput = array(
array($process::OUT, '123'),
);
$this->assertSame($expectedOutput, $output);
$input->write(345);
foreach ($process as $type => $data) {
$output[] = array($type, $data);
}
$this->assertSame('', $process->getOutput());
$this->assertFalse($process->isRunning());
$expectedOutput = array(
array($process::OUT, '123'),
array($process::ERR, '234'),
array($process::OUT, '345'),
array($process::ERR, '456'),
);
$this->assertSame($expectedOutput, $output);
}
public function testNonBlockingNorClearingIteratorOutput()
{
$input = new InputStream();
$process = $this->getProcessForCode('fwrite(STDOUT, fread(STDIN, 3));');
$process->setInput($input);
$process->start();
$output = array();
foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
$output[] = array($type, $data);
break;
}
$expectedOutput = array(
array($process::OUT, ''),
);
$this->assertSame($expectedOutput, $output);
$input->write(123);
foreach ($process->getIterator($process::ITER_NON_BLOCKING | $process::ITER_KEEP_OUTPUT) as $type => $data) {
if ('' !== $data) {
$output[] = array($type, $data);
}
}
$this->assertSame('123', $process->getOutput());
$this->assertFalse($process->isRunning());
$expectedOutput = array(
array($process::OUT, ''),
array($process::OUT, '123'),
);
$this->assertSame($expectedOutput, $output);
}
public function testChainedProcesses()
{
$p1 = $this->getProcessForCode('fwrite(STDERR, 123); fwrite(STDOUT, 456);');
$p2 = $this->getProcessForCode('stream_copy_to_stream(STDIN, STDOUT);');
$p2->setInput($p1);
$p1->start();
$p2->run();
$this->assertSame('123', $p1->getErrorOutput());
$this->assertSame('', $p1->getOutput());
$this->assertSame('', $p2->getErrorOutput());
$this->assertSame('456', $p2->getOutput());
}
public function testSetBadEnv()
{
$process = $this->getProcess('echo hello');
$process->setEnv(array('bad%%' => '123'));
$process->inheritEnvironmentVariables(true);
$process->run();
$this->assertSame('hello'.PHP_EOL, $process->getOutput());
$this->assertSame('', $process->getErrorOutput());
}
public function testEnvBackupDoesNotDeleteExistingVars()
{
putenv('existing_var=foo');
$_ENV['existing_var'] = 'foo';
$process = $this->getProcess('php -r "echo getenv(\'new_test_var\');"');
$process->setEnv(array('existing_var' => 'bar', 'new_test_var' => 'foo'));
$process->inheritEnvironmentVariables();
$process->run();
$this->assertSame('foo', $process->getOutput());
$this->assertSame('foo', getenv('existing_var'));
$this->assertFalse(getenv('new_test_var'));
putenv('existing_var');
unset($_ENV['existing_var']);
}
public function testEnvIsInherited()
{
$process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ', 'EMPTY' => ''));
putenv('FOO=BAR');
$_ENV['FOO'] = 'BAR';
$process->run();
$expected = array('BAR' => 'BAZ', 'EMPTY' => '', 'FOO' => 'BAR');
$env = array_intersect_key(unserialize($process->getOutput()), $expected);
$this->assertEquals($expected, $env);
putenv('FOO');
unset($_ENV['FOO']);
}
/**
* @group legacy
*/
public function testInheritEnvDisabled()
{
$process = $this->getProcessForCode('echo serialize($_SERVER);', null, array('BAR' => 'BAZ'));
putenv('FOO=BAR');
$_ENV['FOO'] = 'BAR';
$this->assertSame($process, $process->inheritEnvironmentVariables(false));
$this->assertFalse($process->areEnvironmentVariablesInherited());
$process->run();
$expected = array('BAR' => 'BAZ', 'FOO' => 'BAR');
$env = array_intersect_key(unserialize($process->getOutput()), $expected);
unset($expected['FOO']);
$this->assertSame($expected, $env);
putenv('FOO');
unset($_ENV['FOO']);
}
public function testGetCommandLine()
{
$p = new Process(array('/usr/bin/php'));
$expected = '\\' === \DIRECTORY_SEPARATOR ? '"/usr/bin/php"' : "'/usr/bin/php'";
$this->assertSame($expected, $p->getCommandLine());
}
/**
* @dataProvider provideEscapeArgument
*/
public function testEscapeArgument($arg)
{
$p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg));
$p->run();
$this->assertSame($arg, $p->getOutput());
}
/**
* @dataProvider provideEscapeArgument
* @group legacy
*/
public function testEscapeArgumentWhenInheritEnvDisabled($arg)
{
$p = new Process(array(self::$phpBin, '-r', 'echo $argv[1];', $arg), null, array('BAR' => 'BAZ'));
$p->inheritEnvironmentVariables(false);
$p->run();
$this->assertSame($arg, $p->getOutput());
}
public function testRawCommandLine()
{
$p = new Process(sprintf('"%s" -r %s "a" "" "b"', self::$phpBin, escapeshellarg('print_r($argv);')));
$p->run();
$expected = <<<EOTXT
Array
(
[0] => -
[1] => a
[2] =>
[3] => b
)
EOTXT;
$this->assertSame($expected, str_replace('Standard input code', '-', $p->getOutput()));
}
public function provideEscapeArgument()
{
yield array('a"b%c%');
yield array('a"b^c^');
yield array("a\nb'c");
yield array('a^b c!');
yield array("a!b\tc");
yield array('a\\\\"\\"');
yield array('éÉèÈàÀöä');
}
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->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
@@ -1199,9 +1564,10 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
*
* @return Process
*/
private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
private function getProcess($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60)
{
$process = new Process($commandline, $cwd, $env, $input, $timeout, $options);
$process = new Process($commandline, $cwd, $env, $input, $timeout);
$process->inheritEnvironmentVariables();
if (false !== $enhance = getenv('ENHANCE_SIGCHLD')) {
try {
@@ -1225,13 +1591,26 @@ class ProcessTest extends \PHPUnit_Framework_TestCase
return self::$process = $process;
}
/**
* @return Process
*/
private function getProcessForCode($code, $cwd = null, array $env = null, $input = null, $timeout = 60)
{
return $this->getProcess(array(self::$phpBin, '-r', $code), $cwd, $env, $input, $timeout);
}
private function skipIfNotEnhancedSigchild($expectException = true)
{
if (self::$sigchild) {
if (!$expectException) {
$this->markTestSkipped('PHP is compiled with --enable-sigchild.');
} elseif (self::$notEnhancedSigchild) {
$this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
if (method_exists($this, 'expectException')) {
$this->expectException('Symfony\Component\Process\Exception\RuntimeException');
$this->expectExceptionMessage('This PHP has been compiled with --enable-sigchild.');
} else {
$this->setExpectedException('Symfony\Component\Process\Exception\RuntimeException', 'This PHP has been compiled with --enable-sigchild.');
}
}
}
}

View File

@@ -11,9 +11,13 @@
namespace Symfony\Component\Process\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\ProcessUtils;
class ProcessUtilsTest extends \PHPUnit_Framework_TestCase
/**
* @group legacy
*/
class ProcessUtilsTest extends TestCase
{
/**
* @dataProvider dataArguments
@@ -25,7 +29,7 @@ class ProcessUtilsTest extends \PHPUnit_Framework_TestCase
public function dataArguments()
{
if ('\\' === DIRECTORY_SEPARATOR) {
if ('\\' === \DIRECTORY_SEPARATOR) {
return array(
array('"\"php\" \"-v\""', '"php" "-v"'),
array('"foo bar"', 'foo bar'),
@@ -43,6 +47,7 @@ class ProcessUtilsTest extends \PHPUnit_Framework_TestCase
array("'<|>\" \"'\\''f'", '<|>" "\'f'),
array("''", ''),
array("'with\\trailingbs\\'", 'with\trailingbs\\'),
array("'withNonAsciiAccentLikeéÉèÈàÀöä'", 'withNonAsciiAccentLikeéÉèÈàÀöä'),
);
}
}

View File

@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
pcntl_signal(SIGUSR1, function () {echo 'SIGUSR1'; exit;});
pcntl_signal(SIGUSR1, function () { echo 'SIGUSR1'; exit; });
echo 'Caught ';

View File

@@ -16,7 +16,7 @@
}
],
"require": {
"php": ">=5.5.9"
"php": "^5.5.9|>=7.0.8"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Process\\": "" },
@@ -27,7 +27,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "3.0-dev"
"dev-master": "3.4-dev"
}
}
}

View File

@@ -5,6 +5,8 @@
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />