From af7c0a7bda396ed83dcfcf28cda8133d687a7b9c Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Thu, 26 May 2016 21:13:52 +0100 Subject: [PATCH] Make handlers more serializable by default by having them close() before sleeping, fixes #365 --- src/Monolog/Handler/Handler.php | 7 +++++ tests/Monolog/Handler/StreamHandlerTest.php | 35 ++++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/Monolog/Handler/Handler.php b/src/Monolog/Handler/Handler.php index 27e48abd..6d1e7bfc 100644 --- a/src/Monolog/Handler/Handler.php +++ b/src/Monolog/Handler/Handler.php @@ -43,4 +43,11 @@ abstract class Handler implements HandlerInterface // do nothing } } + + public function __sleep() + { + $this->close(); + + return array_keys(get_object_vars($this)); + } } diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php index d5234eef..b0d7d7fa 100644 --- a/tests/Monolog/Handler/StreamHandlerTest.php +++ b/tests/Monolog/Handler/StreamHandlerTest.php @@ -51,13 +51,38 @@ class StreamHandlerTest extends TestCase { $handler = new StreamHandler('php://memory'); $handler->handle($this->getRecord(Logger::WARNING, 'test')); - $streamProp = new \ReflectionProperty('Monolog\Handler\StreamHandler', 'stream'); - $streamProp->setAccessible(true); - $handle = $streamProp->getValue($handler); + $stream = $handler->getStream(); - $this->assertTrue(is_resource($handle)); + $this->assertTrue(is_resource($stream)); $handler->close(); - $this->assertFalse(is_resource($handle)); + $this->assertFalse(is_resource($stream)); + } + + /** + * @covers Monolog\Handler\StreamHandler::close + * @covers Monolog\Handler\Handler::__sleep + */ + public function testSerialization() + { + $handler = new StreamHandler('php://memory'); + $handler->handle($this->getRecord(Logger::WARNING, 'testfoo')); + $stream = $handler->getStream(); + + $this->assertTrue(is_resource($stream)); + fseek($stream, 0); + $this->assertContains('testfoo', stream_get_contents($stream)); + $serialized = serialize($handler); + $this->assertFalse(is_resource($stream)); + + $handler = unserialize($serialized); + $handler->handle($this->getRecord(Logger::WARNING, 'testbar')); + $stream = $handler->getStream(); + + $this->assertTrue(is_resource($stream)); + fseek($stream, 0); + $contents = stream_get_contents($stream); + $this->assertNotContains('testfoo', $contents); + $this->assertContains('testbar', $contents); } /**