1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-06 13:16:39 +02:00

Replaced indention tabs with 4 spaces in ProcessHandler and its test.

This commit is contained in:
kolja
2016-01-15 20:39:29 +01:00
parent f13011e03e
commit fbe0bae8c9
2 changed files with 321 additions and 321 deletions

View File

@@ -26,197 +26,197 @@ use Monolog\Logger;
*/ */
class ProcessHandler extends AbstractProcessingHandler class ProcessHandler extends AbstractProcessingHandler
{ {
/** /**
* Holds the process to receive data on its STDIN. * Holds the process to receive data on its STDIN.
* *
* @var resource * @var resource
*/ */
private $process; private $process;
/** /**
* @var string * @var string
*/ */
private $command; private $command;
/** /**
* @var string * @var string
*/ */
private $cwd; private $cwd;
/** /**
* @var array * @var array
*/ */
private $pipes = []; private $pipes = [];
/** /**
* @var array * @var array
*/ */
const DESCRIPTOR_SPEC = [ const DESCRIPTOR_SPEC = [
0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from
1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to
2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors
]; ];
/** /**
* @param int $command Command for the process to start. Absolute paths are recommended, * @param int $command Command for the process to start. Absolute paths are recommended,
* especially if you do not use the $cwd parameter. * especially if you do not use the $cwd parameter.
* @param bool|int $level The minimum logging level at which this handler will be triggered. * @param bool|int $level The minimum logging level at which this handler will be triggered.
* @param bool|true $bubble Whether the messages that are handled can bubble up the stack or not. * @param bool|true $bubble Whether the messages that are handled can bubble up the stack or not.
* @param string|null $cwd "Current working directory" (CWD) for the process to be executed in. * @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*/ */
public function __construct($command, $level = Logger::DEBUG, $bubble = true, $cwd = null) public function __construct($command, $level = Logger::DEBUG, $bubble = true, $cwd = null)
{ {
$this->guardAgainstInvalidCommand($command); $this->guardAgainstInvalidCommand($command);
$this->guardAgainstInvalidCwd($cwd); $this->guardAgainstInvalidCwd($cwd);
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->command = $command; $this->command = $command;
$this->cwd = $cwd; $this->cwd = $cwd;
} }
/** /**
* @param string $command * @param string $command
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
* @return void * @return void
*/ */
private function guardAgainstInvalidCommand($command) private function guardAgainstInvalidCommand($command)
{ {
if (empty($command) || is_string($command) === false) { if (empty($command) || is_string($command) === false) {
throw new \InvalidArgumentException('The command argument must be a non-empty string.'); throw new \InvalidArgumentException('The command argument must be a non-empty string.');
} }
} }
/** /**
* @param string $cwd * @param string $cwd
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
* @return void * @return void
*/ */
private function guardAgainstInvalidCwd($cwd) private function guardAgainstInvalidCwd($cwd)
{ {
if ($cwd !== null && (empty($cwd) || is_string($cwd) === false)) { if ($cwd !== null && (empty($cwd) || is_string($cwd) === false)) {
throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string, if any.'); throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string, if any.');
} }
} }
/** /**
* Writes the record down to the log of the implementing handler * Writes the record down to the log of the implementing handler
* *
* @param array $record * @param array $record
* @throws \UnexpectedValueException * @throws \UnexpectedValueException
* @return void * @return void
*/ */
protected function write(array $record) protected function write(array $record)
{ {
$this->ensureProcessIsStarted(); $this->ensureProcessIsStarted();
$this->writeProcessInput($record['formatted']); $this->writeProcessInput($record['formatted']);
$errors = $this->readProcessErrors(); $errors = $this->readProcessErrors();
if (empty($errors) === false) { if (empty($errors) === false) {
throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors)); throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors));
} }
} }
/** /**
* Makes sure that the process is actually started, and if not, starts it, * Makes sure that the process is actually started, and if not, starts it,
* assigns the stream pipes, and handles startup errors, if any. * assigns the stream pipes, and handles startup errors, if any.
* *
* @return void * @return void
*/ */
private function ensureProcessIsStarted() private function ensureProcessIsStarted()
{ {
if (is_resource($this->process) === false) { if (is_resource($this->process) === false) {
$this->startProcess(); $this->startProcess();
$this->handleStartupErrors(); $this->handleStartupErrors();
} }
} }
/** /**
* Starts the actual process and sets all streams to non-blocking. * Starts the actual process and sets all streams to non-blocking.
* *
* @return void * @return void
*/ */
private function startProcess() private function startProcess()
{ {
$this->process = proc_open($this->command, self::DESCRIPTOR_SPEC, $this->pipes, $this->cwd); $this->process = proc_open($this->command, self::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
foreach ($this->pipes as $pipe) { foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, false); stream_set_blocking($pipe, false);
} }
} }
/** /**
* Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any. * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
* *
* @throws \UnexpectedValueException * @throws \UnexpectedValueException
* @return void * @return void
*/ */
private function handleStartupErrors() private function handleStartupErrors()
{ {
$selected = $this->selectErrorStream(); $selected = $this->selectErrorStream();
if (false === $selected) { if (false === $selected) {
throw new \UnexpectedValueException('Something went wrong while selecting a stream.'); throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
} }
$errors = $this->readProcessErrors(); $errors = $this->readProcessErrors();
if (is_resource($this->process) === false || empty($errors) === false) { if (is_resource($this->process) === false || empty($errors) === false) {
throw new \UnexpectedValueException( throw new \UnexpectedValueException(
sprintf('The process "%s" could not be opened: ' . $errors, $this->command) sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
); );
} }
} }
/** /**
* Selects the STDERR stream. * Selects the STDERR stream.
* *
* @return int|bool * @return int|bool
*/ */
protected function selectErrorStream() protected function selectErrorStream()
{ {
$empty = []; $empty = [];
$errorPipes = [$this->pipes[2]]; $errorPipes = [$this->pipes[2]];
return stream_select($errorPipes, $empty, $empty, 1); return stream_select($errorPipes, $empty, $empty, 1);
} }
/** /**
* Reads the errors of the process, if there are any. * Reads the errors of the process, if there are any.
* *
* @codeCoverageIgnore * @codeCoverageIgnore
* @return string Empty string if there are no errors. * @return string Empty string if there are no errors.
*/ */
protected function readProcessErrors() protected function readProcessErrors()
{ {
return stream_get_contents($this->pipes[2]); return stream_get_contents($this->pipes[2]);
} }
/** /**
* Writes to the input stream of the opened process. * Writes to the input stream of the opened process.
* *
* @codeCoverageIgnore * @codeCoverageIgnore
* @param $string * @param $string
* @return void * @return void
*/ */
protected function writeProcessInput($string) protected function writeProcessInput($string)
{ {
fwrite($this->pipes[0], (string)$string); fwrite($this->pipes[0], (string)$string);
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function close() public function close()
{ {
if (is_resource($this->process)) { if (is_resource($this->process)) {
foreach ($this->pipes as $pipe) { foreach ($this->pipes as $pipe) {
fclose($pipe); fclose($pipe);
} }
proc_close($this->process); proc_close($this->process);
} }
$this->process = null; $this->process = null;
} }
} }

View File

@@ -16,180 +16,180 @@ use Monolog\Logger;
class ProcessHandlerTest extends TestCase class ProcessHandlerTest extends TestCase
{ {
/** /**
* Dummy command to be used by tests that should not fail due to the command. * Dummy command to be used by tests that should not fail due to the command.
* *
* @var string * @var string
*/ */
const DUMMY_COMMAND = 'echo'; const DUMMY_COMMAND = 'echo';
/** /**
* @covers Monolog\Handler\ProcessHandler::__construct * @covers Monolog\Handler\ProcessHandler::__construct
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
* @covers Monolog\Handler\ProcessHandler::write * @covers Monolog\Handler\ProcessHandler::write
* @covers Monolog\Handler\ProcessHandler::ensureProcessIsStarted * @covers Monolog\Handler\ProcessHandler::ensureProcessIsStarted
* @covers Monolog\Handler\ProcessHandler::startProcess * @covers Monolog\Handler\ProcessHandler::startProcess
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
*/ */
public function testWriteOpensProcessAndWritesToStdInOfProcess() public function testWriteOpensProcessAndWritesToStdInOfProcess()
{ {
$fixtures = array( $fixtures = array(
'chuck norris', 'chuck norris',
'foobar1337' 'foobar1337'
); );
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('writeProcessInput')); $mockBuilder->setMethods(array('writeProcessInput'));
// using echo as command, as it is most probably available // using echo as command, as it is most probably available
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND));
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();
$handler->expects($this->exactly(2)) $handler->expects($this->exactly(2))
->method('writeProcessInput') ->method('writeProcessInput')
->withConsecutive($this->stringContains($fixtures[0]), $this->stringContains($fixtures[1])); ->withConsecutive($this->stringContains($fixtures[0]), $this->stringContains($fixtures[1]));
/** @var ProcessHandler $handler */ /** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Logger::WARNING, $fixtures[0])); $handler->handle($this->getRecord(Logger::WARNING, $fixtures[0]));
$handler->handle($this->getRecord(Logger::ERROR, $fixtures[1])); $handler->handle($this->getRecord(Logger::ERROR, $fixtures[1]));
} }
/** /**
* Data provider for invalid commands. * Data provider for invalid commands.
* *
* @return array * @return array
*/ */
public function invalidCommandProvider() public function invalidCommandProvider()
{ {
return [ return [
[1337], [1337],
[''], [''],
[null], [null],
[fopen('php://input', 'r')], [fopen('php://input', 'r')],
]; ];
} }
/** /**
* @dataProvider invalidCommandProvider * @dataProvider invalidCommandProvider
* @param mixed $invalidCommand * @param mixed $invalidCommand
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
*/ */
public function testConstructWithInvalidCommandThrowsInvalidArgumentException($invalidCommand) public function testConstructWithInvalidCommandThrowsInvalidArgumentException($invalidCommand)
{ {
$this->setExpectedException('\InvalidArgumentException'); $this->setExpectedException('\InvalidArgumentException');
new ProcessHandler($invalidCommand, Logger::DEBUG); new ProcessHandler($invalidCommand, Logger::DEBUG);
} }
/** /**
* Data provider for invalid CWDs. * Data provider for invalid CWDs.
* *
* @return array * @return array
*/ */
public function invalidCwdProvider() public function invalidCwdProvider()
{ {
return [ return [
[1337], [1337],
[''], [''],
[fopen('php://input', 'r')], [fopen('php://input', 'r')],
]; ];
} }
/** /**
* @dataProvider invalidCwdProvider * @dataProvider invalidCwdProvider
* @param mixed $invalidCwd * @param mixed $invalidCwd
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
*/ */
public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd) public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd)
{ {
$this->setExpectedException('\InvalidArgumentException'); $this->setExpectedException('\InvalidArgumentException');
new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, $invalidCwd); new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, $invalidCwd);
} }
/** /**
* @covers Monolog\Handler\ProcessHandler::__construct * @covers Monolog\Handler\ProcessHandler::__construct
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
*/ */
public function testConstructWithValidCwdWorks() public function testConstructWithValidCwdWorks()
{ {
$handler = new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, sys_get_temp_dir()); $handler = new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, sys_get_temp_dir());
$this->assertInstanceOf( $this->assertInstanceOf(
'Monolog\Handler\ProcessHandler', 'Monolog\Handler\ProcessHandler',
$handler, $handler,
'Constructed handler is not a ProcessHandler.' 'Constructed handler is not a ProcessHandler.'
); );
} }
/** /**
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
*/ */
public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException() public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException()
{ {
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('selectErrorStream')); $mockBuilder->setMethods(array('selectErrorStream'));
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND));
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();
$handler->expects($this->once()) $handler->expects($this->once())
->method('selectErrorStream') ->method('selectErrorStream')
->will($this->returnValue(false)); ->will($this->returnValue(false));
$this->setExpectedException('\UnexpectedValueException'); $this->setExpectedException('\UnexpectedValueException');
/** @var ProcessHandler $handler */ /** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Logger::WARNING, 'stream failing, whoops')); $handler->handle($this->getRecord(Logger::WARNING, 'stream failing, whoops'));
} }
/** /**
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
* @covers Monolog\Handler\ProcessHandler::selectErrorStream * @covers Monolog\Handler\ProcessHandler::selectErrorStream
*/ */
public function testStartupWithErrorsThrowsUnexpectedValueException() public function testStartupWithErrorsThrowsUnexpectedValueException()
{ {
$handler = new ProcessHandler('>&2 echo "some fake error message"'); $handler = new ProcessHandler('>&2 echo "some fake error message"');
$this->setExpectedException('\UnexpectedValueException'); $this->setExpectedException('\UnexpectedValueException');
$handler->handle($this->getRecord(Logger::WARNING, 'some warning in the house')); $handler->handle($this->getRecord(Logger::WARNING, 'some warning in the house'));
} }
/** /**
* @covers Monolog\Handler\ProcessHandler::write * @covers Monolog\Handler\ProcessHandler::write
*/ */
public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException() public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException()
{ {
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->setMethods(array('readProcessErrors')); $mockBuilder->setMethods(array('readProcessErrors'));
// using echo as command, as it is most probably available // using echo as command, as it is most probably available
$mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND)); $mockBuilder->setConstructorArgs(array(self::DUMMY_COMMAND));
$handler = $mockBuilder->getMock(); $handler = $mockBuilder->getMock();
$handler->expects($this->exactly(2)) $handler->expects($this->exactly(2))
->method('readProcessErrors') ->method('readProcessErrors')
->willReturnOnConsecutiveCalls('', $this->returnValue('some fake error message here')); ->willReturnOnConsecutiveCalls('', $this->returnValue('some fake error message here'));
$this->setExpectedException('\UnexpectedValueException'); $this->setExpectedException('\UnexpectedValueException');
/** @var ProcessHandler $handler */ /** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Logger::WARNING, 'some test stuff')); $handler->handle($this->getRecord(Logger::WARNING, 'some test stuff'));
} }
/** /**
* @covers Monolog\Handler\ProcessHandler::close * @covers Monolog\Handler\ProcessHandler::close
*/ */
public function testCloseClosesProcess() public function testCloseClosesProcess()
{ {
$class = new \ReflectionClass('Monolog\Handler\ProcessHandler'); $class = new \ReflectionClass('Monolog\Handler\ProcessHandler');
$property = $class->getProperty('process'); $property = $class->getProperty('process');
$property->setAccessible(true); $property->setAccessible(true);
$handler = new ProcessHandler(self::DUMMY_COMMAND); $handler = new ProcessHandler(self::DUMMY_COMMAND);
$handler->handle($this->getRecord(Logger::WARNING, '21 is only the half truth')); $handler->handle($this->getRecord(Logger::WARNING, '21 is only the half truth'));
$process = $property->getValue($handler); $process = $property->getValue($handler);
$this->assertTrue(is_resource($process), 'Process is not running although it should.'); $this->assertTrue(is_resource($process), 'Process is not running although it should.');
$handler->close(); $handler->close();
$process = $property->getValue($handler); $process = $property->getValue($handler);
$this->assertFalse(is_resource($process), 'Process is still running although it should not.'); $this->assertFalse(is_resource($process), 'Process is still running although it should not.');
} }
} }