| 1 |
<?php |
| 2 |
/* |
| 3 |
* This file is part of the ManageWP Worker plugin. |
| 4 |
* |
| 5 |
* (c) ManageWP LLC <contact@managewp.com> |
| 6 |
* |
| 7 |
* For the full copyright and license information, please view the LICENSE |
| 8 |
* file that was distributed with this source code. |
| 9 |
*/ |
| 10 |
|
| 11 |
class MWP_Stream_ProcessOutput extends MWP_Stream_Callable |
| 12 |
{ |
| 13 |
|
| 14 |
/** |
| 15 |
* @var Symfony_Process_Process |
| 16 |
*/ |
| 17 |
private $process; |
| 18 |
|
| 19 |
/** |
| 20 |
* @var bool |
| 21 |
*/ |
| 22 |
private $ran = false; |
| 23 |
|
| 24 |
public function __construct(Symfony_Process_Process $process) |
| 25 |
{ |
| 26 |
parent::__construct(array($this, 'getIncrementalOutput')); |
| 27 |
$this->process = $process; |
| 28 |
} |
| 29 |
|
| 30 |
/** |
| 31 |
* Returns incremental process output (even if empty string) or false if the process has finished |
| 32 |
* successfully and all output was already returned. |
| 33 |
* |
| 34 |
* @throws Symfony_Process_Exception_ProcessFailedException If the process did not exit successfully. |
| 35 |
* |
| 36 |
* @internal |
| 37 |
* |
| 38 |
* @return string|false |
| 39 |
*/ |
| 40 |
public function getIncrementalOutput() |
| 41 |
{ |
| 42 |
if (!$this->ran) { |
| 43 |
$this->ran = true; |
| 44 |
try { |
| 45 |
$this->process->start(); |
| 46 |
} catch (Symfony_Process_Exception_ExceptionInterface $e) { |
| 47 |
throw new Symfony_Process_Exception_ProcessFailedException($this->process); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
if ($this->process->isRunning()) { |
| 52 |
$output = $this->process->getIncrementalOutput(); |
| 53 |
$this->process->clearOutput(); |
| 54 |
|
| 55 |
if (strlen($output) < Symfony_Process_Pipes_PipesInterface::CHUNK_SIZE) { |
| 56 |
// Don't hog the processor while waiting for incremental process output. |
| 57 |
usleep(100000); |
| 58 |
} |
| 59 |
|
| 60 |
// The stream will be read again because we're returning a string. |
| 61 |
return (string)$output; |
| 62 |
} else { |
| 63 |
if (!$this->process->isSuccessful()) { |
| 64 |
throw new Symfony_Process_Exception_ProcessFailedException($this->process); |
| 65 |
} |
| 66 |
|
| 67 |
$output = $this->process->getIncrementalOutput(); |
| 68 |
$this->process->clearOutput(); |
| 69 |
|
| 70 |
// The process has finished and is successful. This part will probably get run twice, |
| 71 |
// first time we'll return final output, second time we'll return 'false' and break the loop. |
| 72 |
return strlen($output) ? $output : false; |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
|