From 9815726270d4f8435dae7e3b2ce19e732f50a4d0 Mon Sep 17 00:00:00 2001 From: Walter Tamboer Date: Wed, 1 Aug 2012 23:03:45 +0200 Subject: [PATCH 01/32] Added a ChromePhp logger. --- src/Formatter/ChromePhp.php | 51 ++++++++++ src/Writer/ChromePhp.php | 105 ++++++++++++++++++++ src/Writer/ChromePhp/ChromePhpBridge.php | 71 +++++++++++++ src/Writer/ChromePhp/ChromePhpInterface.php | 54 ++++++++++ 4 files changed, 281 insertions(+) create mode 100644 src/Formatter/ChromePhp.php create mode 100644 src/Writer/ChromePhp.php create mode 100644 src/Writer/ChromePhp/ChromePhpBridge.php create mode 100644 src/Writer/ChromePhp/ChromePhpInterface.php diff --git a/src/Formatter/ChromePhp.php b/src/Formatter/ChromePhp.php new file mode 100644 index 00000000..158f5b09 --- /dev/null +++ b/src/Formatter/ChromePhp.php @@ -0,0 +1,51 @@ +chromephp = $instance === null ? $this->getChromePhp() : $instance; + $this->formatter = new ChromePhpFormatter(); + } + + /** + * Write a message to the log. + * + * @param array $event event data + * @return void + */ + protected function doWrite(array $event) + { + $line = $this->formatter->format($event); + + switch ($event['priority']) { + case Logger::EMERG: + case Logger::ALERT: + case Logger::CRIT: + case Logger::ERR: + $this->chromephp->error($line); + break; + case Logger::WARN: + $this->chromephp->warn($line); + break; + case Logger::NOTICE: + case Logger::INFO: + $this->chromephp->info($line); + break; + case Logger::DEBUG: + $this->chromephp->trace($line); + break; + default: + $this->chromephp->log($line); + break; + } + } + + /** + * Gets the ChromePhpInterface instance that is used for logging. + * + * @return ChromePhpInterface + */ + public function getChromePhp() + { + // Remember: class names in strings are absolute; thus the class_exists + // here references the canonical name for the ChromePhp class + if (!$this->chromephp instanceof ChromePhpInterface + && class_exists('ChromePhp') + ) { + $this->setChromePhp(new ChromePhpBridge()); + } + return $this->chromephp; + } + + /** + * Sets the ChromePhpInterface instance that is used for logging. + * + * @param ChromePhpInterface $instance The instance to set. + * @return ChromePhp + */ + public function setChromePhp(ChromePhpInterface $instance) + { + $this->chromephp = $instance; + return $this; + } +} diff --git a/src/Writer/ChromePhp/ChromePhpBridge.php b/src/Writer/ChromePhp/ChromePhpBridge.php new file mode 100644 index 00000000..d6a97655 --- /dev/null +++ b/src/Writer/ChromePhp/ChromePhpBridge.php @@ -0,0 +1,71 @@ + Date: Thu, 2 Aug 2012 18:42:00 +0200 Subject: [PATCH 02/32] Added tests for ChromePhp --- test/Filter/MockTest.php | 33 --- test/Filter/PriorityTest.php | 49 ---- test/Filter/RegexTest.php | 37 --- test/Filter/SuppressFilterTest.php | 57 ---- test/Filter/ValidatorTest.php | 45 --- test/Formatter/ErrorHandlerTest.php | 53 ---- test/Formatter/ExceptionHandlerTest.php | 120 -------- test/Formatter/FirePhpTest.php | 54 ---- test/Formatter/SimpleTest.php | 144 ---------- test/Formatter/XmlTest.php | 200 ------------- test/LoggerTest.php | 262 ------------------ test/TestAsset/ConcreteWriter.php | 20 -- test/TestAsset/CustomSyslogWriter.php | 21 -- .../{MockFirePhp.php => MockChromePhp.php} | 0 test/TestAsset/MockDbAdapter.php | 38 --- test/TestAsset/MockDbDriver.php | 21 -- test/TestAsset/MockDbPlatform.php | 21 -- test/TestAsset/SerializableObject.php | 19 -- test/TestAsset/StringObject.php | 19 -- test/Writer/AbstractTest.php | 72 ----- .../{FirePhpTest.php => ChromePhpTest.php} | 0 test/Writer/DbTest.php | 215 -------------- test/Writer/MailTest.php | 87 ------ test/Writer/MockTest.php | 33 --- test/Writer/MongoDBTest.php | 102 ------- test/Writer/NullTest.php | 29 -- test/Writer/StreamTest.php | 150 ---------- test/Writer/SyslogTest.php | 96 ------- test/Writer/ZendMonitorTest.php | 40 --- test/WriterPluginManagerTest.php | 44 --- test/_files/layout.phtml | 1 - 31 files changed, 2082 deletions(-) delete mode 100644 test/Filter/MockTest.php delete mode 100644 test/Filter/PriorityTest.php delete mode 100644 test/Filter/RegexTest.php delete mode 100644 test/Filter/SuppressFilterTest.php delete mode 100644 test/Filter/ValidatorTest.php delete mode 100644 test/Formatter/ErrorHandlerTest.php delete mode 100644 test/Formatter/ExceptionHandlerTest.php delete mode 100644 test/Formatter/FirePhpTest.php delete mode 100644 test/Formatter/SimpleTest.php delete mode 100644 test/Formatter/XmlTest.php delete mode 100644 test/LoggerTest.php delete mode 100644 test/TestAsset/ConcreteWriter.php delete mode 100644 test/TestAsset/CustomSyslogWriter.php rename test/TestAsset/{MockFirePhp.php => MockChromePhp.php} (100%) delete mode 100644 test/TestAsset/MockDbAdapter.php delete mode 100644 test/TestAsset/MockDbDriver.php delete mode 100644 test/TestAsset/MockDbPlatform.php delete mode 100644 test/TestAsset/SerializableObject.php delete mode 100644 test/TestAsset/StringObject.php delete mode 100644 test/Writer/AbstractTest.php rename test/Writer/{FirePhpTest.php => ChromePhpTest.php} (100%) delete mode 100644 test/Writer/DbTest.php delete mode 100644 test/Writer/MailTest.php delete mode 100644 test/Writer/MockTest.php delete mode 100644 test/Writer/MongoDBTest.php delete mode 100644 test/Writer/NullTest.php delete mode 100644 test/Writer/StreamTest.php delete mode 100644 test/Writer/SyslogTest.php delete mode 100644 test/Writer/ZendMonitorTest.php delete mode 100644 test/WriterPluginManagerTest.php delete mode 100644 test/_files/layout.phtml diff --git a/test/Filter/MockTest.php b/test/Filter/MockTest.php deleted file mode 100644 index d198332b..00000000 --- a/test/Filter/MockTest.php +++ /dev/null @@ -1,33 +0,0 @@ -assertSame(array(), $filter->events); - - $fields = array('foo' => 'bar'); - $this->assertTrue($filter->filter($fields)); - $this->assertSame(array($fields), $filter->events); - } -} diff --git a/test/Filter/PriorityTest.php b/test/Filter/PriorityTest.php deleted file mode 100644 index 905eb146..00000000 --- a/test/Filter/PriorityTest.php +++ /dev/null @@ -1,49 +0,0 @@ -assertTrue($filter->filter(array('priority' => 2))); - $this->assertTrue($filter->filter(array('priority' => 1))); - $this->assertFalse($filter->filter(array('priority' => 3))); - } - - public function testComparisonOperatorCanBeChanged() - { - // accept above priority 2 - $filter = new Priority(2, '>'); - - $this->assertTrue($filter->filter(array('priority' => 3))); - $this->assertFalse($filter->filter(array('priority' => 2))); - $this->assertFalse($filter->filter(array('priority' => 1))); - } - - public function testConstructorThrowsOnInvalidPriority() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be an integer'); - new Priority('foo'); - } -} diff --git a/test/Filter/RegexTest.php b/test/Filter/RegexTest.php deleted file mode 100644 index b757c761..00000000 --- a/test/Filter/RegexTest.php +++ /dev/null @@ -1,37 +0,0 @@ -setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'invalid reg'); - new Regex('invalid regexp'); - } - - public function testMessageFilter() - { - $filter = new Regex('/accept/'); - $this->assertTrue($filter->filter(array('message' => 'foo accept bar'))); - $this->assertFalse($filter->filter(array('message' => 'foo reject bar'))); - } -} diff --git a/test/Filter/SuppressFilterTest.php b/test/Filter/SuppressFilterTest.php deleted file mode 100644 index c16062f0..00000000 --- a/test/Filter/SuppressFilterTest.php +++ /dev/null @@ -1,57 +0,0 @@ -filter = new SuppressFilter(); - } - - public function testSuppressIsInitiallyOff() - { - $this->assertTrue($this->filter->filter(array())); - } - - public function testSuppressOn() - { - $this->filter->suppress(true); - $this->assertFalse($this->filter->filter(array())); - $this->assertFalse($this->filter->filter(array())); - } - - public function testSuppressOff() - { - $this->filter->suppress(false); - $this->assertTrue($this->filter->filter(array())); - $this->assertTrue($this->filter->filter(array())); - } - - public function testSuppressCanBeReset() - { - $this->filter->suppress(true); - $this->assertFalse($this->filter->filter(array())); - $this->filter->suppress(false); - $this->assertTrue($this->filter->filter(array())); - $this->filter->suppress(true); - $this->assertFalse($this->filter->filter(array())); - } -} diff --git a/test/Filter/ValidatorTest.php b/test/Filter/ValidatorTest.php deleted file mode 100644 index 3e7a1181..00000000 --- a/test/Filter/ValidatorTest.php +++ /dev/null @@ -1,45 +0,0 @@ -assertTrue($filter->filter(array('message' => '123'))); - $this->assertFalse($filter->filter(array('message' => 'test'))); - $this->assertFalse($filter->filter(array('message' => 'test123'))); - $this->assertFalse($filter->filter(array('message' => '(%$'))); - } - - public function testValidatorChain() - { - $validatorChain = new ValidatorChain(); - $validatorChain->addValidator(new DigitsFilter()); - $validatorChain->addValidator(new Int()); - $filter = new Validator($validatorChain); - $this->assertTrue($filter->filter(array('message' => '123'))); - $this->assertFalse($filter->filter(array('message' => 'test'))); - } -} diff --git a/test/Formatter/ErrorHandlerTest.php b/test/Formatter/ErrorHandlerTest.php deleted file mode 100644 index 829b91ac..00000000 --- a/test/Formatter/ErrorHandlerTest.php +++ /dev/null @@ -1,53 +0,0 @@ - $date, - 'message' => 'test', - 'priority' => 1, - 'priorityName' => 'CRIT', - 'extra' => array ( - 'errno' => 1, - 'file' => 'test.php', - 'line' => 1 - ) - ); - $formatter = new ErrorHandler(); - $output = $formatter->format($event); - - $this->assertEquals($date->format('c') . ' CRIT (1) test (errno 1) in test.php on line 1', $output); - } - - public function testSetDateTimeFormat() - { - $formatter = new ErrorHandler(); - - $this->assertEquals('c', $formatter->getDateTimeFormat()); - $this->assertSame($formatter, $formatter->setDateTimeFormat('r')); - $this->assertEquals('r', $formatter->getDateTimeFormat()); - } -} diff --git a/test/Formatter/ExceptionHandlerTest.php b/test/Formatter/ExceptionHandlerTest.php deleted file mode 100644 index 20cae5bc..00000000 --- a/test/Formatter/ExceptionHandlerTest.php +++ /dev/null @@ -1,120 +0,0 @@ - $date, - 'message' => 'test', - 'priority' => 1, - 'priorityName' => 'CRIT', - 'extra' => array( - 'file' => 'test.php', - 'line' => 1, - 'trace' => array( - array( - 'file' => 'test.php', - 'line' => 1, - 'function' => 'test', - 'class' => 'Test', - 'type' => '::', - 'args' => array(1) - ), - array( - 'file' => 'test.php', - 'line' => 2, - 'function' => 'test', - 'class' => 'Test', - 'type' => '::', - 'args' => array(1) - ) - ) - ) - ); - - // The formatter ends with unix style line endings so make sure we expect that - // output as well: - $expected = $date->format('c') . " CRIT (1) test in test.php on line 1\n"; - $expected .= "[Trace]\n"; - $expected .= "File : test.php\n"; - $expected .= "Line : 1\n"; - $expected .= "Func : test\n"; - $expected .= "Class : Test\n"; - $expected .= "Type : static\n"; - $expected .= "Args : Array\n"; - $expected .= "(\n"; - $expected .= " [0] => 1\n"; - $expected .= ")\n\n"; - $expected .= "File : test.php\n"; - $expected .= "Line : 2\n"; - $expected .= "Func : test\n"; - $expected .= "Class : Test\n"; - $expected .= "Type : static\n"; - $expected .= "Args : Array\n"; - $expected .= "(\n"; - $expected .= " [0] => 1\n"; - $expected .= ")\n\n"; - - $formatter = new ExceptionHandler(); - $output = $formatter->format($event); - - $this->assertEquals($expected, $output); - } - - /** - * @dataProvider provideDateTimeFormats - */ - public function testSetDateTimeFormat($dateTimeFormat) - { - $date = new DateTime(); - - $event = array( - 'timestamp' => $date, - 'message' => 'test', - 'priority' => 1, - 'priorityName' => 'CRIT', - 'extra' => array( - 'file' => 'test.php', - 'line' => 1, - ), - ); - - $expected = $date->format($dateTimeFormat) . ' CRIT (1) test in test.php on line 1'; - - $formatter = new ExceptionHandler(); - - $this->assertSame($formatter, $formatter->setDateTimeFormat($dateTimeFormat)); - $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); - $this->assertEquals($expected, $formatter->format($event)); - } - - public function provideDateTimeFormats() - { - return array( - array('r'), - array('U'), - ); - } -} diff --git a/test/Formatter/FirePhpTest.php b/test/Formatter/FirePhpTest.php deleted file mode 100644 index 9fef4bf5..00000000 --- a/test/Formatter/FirePhpTest.php +++ /dev/null @@ -1,54 +0,0 @@ - 'foo' ); - - $f = new FirePhp(); - $line = $f->format($fields); - - $this->assertContains($fields['message'], $line); - } - - public function testSetDateTimeFormatDoesNothing() - { - $formatter = new FirePhp(); - - $this->assertEquals('', $formatter->getDateTimeFormat()); - $this->assertSame($formatter, $formatter->setDateTimeFormat('r')); - $this->assertEquals('', $formatter->getDateTimeFormat()); - } -} diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php deleted file mode 100644 index 8db4f10a..00000000 --- a/test/Formatter/SimpleTest.php +++ /dev/null @@ -1,144 +0,0 @@ -setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be a string'); - new Simple(1); - } - - public function testDefaultFormat() - { - $date = new DateTime(); - $fields = array('timestamp' => $date, - 'message' => 'foo', - 'priority' => 42, - 'priorityName' => 'bar'); - - $f = new Simple(); - $line = $f->format($fields); - - $this->assertContains($date->format('c'), $line, 'Default date format is ISO 8601'); - $this->assertContains($fields['message'], $line); - $this->assertContains($fields['priorityName'], $line); - $this->assertContains((string)$fields['priority'], $line); - } - - public function testComplexValues() - { - $fields = array('timestamp' => new DateTime(), - 'priority' => 42, - 'priorityName' => 'bar'); - - $f = new Simple(); - - $fields['message'] = 'Foo'; - $line = $f->format($fields); - $this->assertContains($fields['message'], $line); - - $fields['message'] = 10; - $line = $f->format($fields); - $this->assertContains((string)$fields['message'], $line); - - $fields['message'] = 10.5; - $line = $f->format($fields); - $this->assertContains((string)$fields['message'], $line); - - $fields['message'] = true; - $line = $f->format($fields); - $this->assertContains('1', $line); - - $fields['message'] = fopen('php://stdout', 'w'); - $line = $f->format($fields); - $this->assertContains('Resource id ', $line); - fclose($fields['message']); - - $fields['message'] = range(1,10); - $line = $f->format($fields); - $this->assertContains('array', $line); - - $fields['message'] = new StringObject(); - $line = $f->format($fields); - $this->assertContains($fields['message']->__toString(), $line); - - $fields['message'] = new \stdClass(); - $line = $f->format($fields); - $this->assertContains('object', $line); - } - - /** - * @dataProvider provideDateTimeFormats - */ - public function testCustomDateTimeFormat($dateTimeFormat) - { - $date = new DateTime(); - $event = array('timestamp' => $date); - $formatter = new Simple('%timestamp%', $dateTimeFormat); - - $this->assertEquals($date->format($dateTimeFormat), $formatter->format($event)); - } - - /** - * @dataProvider provideDateTimeFormats - */ - public function testSetDateTimeFormat($dateTimeFormat) - { - $date = new DateTime(); - $event = array('timestamp' => $date); - $formatter = new Simple('%timestamp%'); - - $this->assertSame($formatter, $formatter->setDateTimeFormat($dateTimeFormat)); - $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); - $this->assertEquals($date->format($dateTimeFormat), $formatter->format($event)); - } - - public function provideDateTimeFormats() - { - return array( - array('r'), - array('U'), - ); - } - - /** - * @group ZF-10427 - */ - public function testDefaultFormatShouldDisplayExtraInformations() - { - $message = 'custom message'; - $exception = new \RuntimeException($message); - $event = array( - 'timestamp' => new DateTime(), - 'message' => 'Application error', - 'priority' => 2, - 'priorityName' => 'CRIT', - 'info' => $exception, - ); - - $formatter = new Simple(); - $output = $formatter->format($event); - - $this->assertContains($message, $output); - } -} diff --git a/test/Formatter/XmlTest.php b/test/Formatter/XmlTest.php deleted file mode 100644 index 660aeaee..00000000 --- a/test/Formatter/XmlTest.php +++ /dev/null @@ -1,200 +0,0 @@ -format(array('timestamp' => $date, 'message' => 'foo', 'priority' => 42)); - - $this->assertContains($date->format('c'), $line); - $this->assertContains('foo', $line); - $this->assertContains((string)42, $line); - } - - public function testConfiguringElementMapping() - { - $f = new XmlFormatter('log', array('foo' => 'bar')); - $line = $f->format(array('bar' => 'baz')); - $this->assertContains('baz', $line); - } - - /** - * @dataProvider provideDateTimeFormats - */ - public function testConfiguringDateTimeFormat($dateTimeFormat) - { - $date = new DateTime(); - $f = new XmlFormatter('log', null, 'UTF-8', $dateTimeFormat); - $this->assertContains($date->format($dateTimeFormat), $f->format(array('timestamp' => $date))); - } - - /** - * @dataProvider provideDateTimeFormats - */ - public function testSetDateTimeFormat($dateTimeFormat) - { - $date = new DateTime(); - $f = new XmlFormatter(); - $this->assertSame($f, $f->setDateTimeFormat($dateTimeFormat)); - $this->assertContains($dateTimeFormat, $f->getDateTimeFormat()); - $this->assertContains($date->format($dateTimeFormat), $f->format(array('timestamp' => $date))); - } - - public function provideDateTimeFormats() - { - return array( - array('r'), - array('U'), - ); - } - - public function testXmlDeclarationIsStripped() - { - $f = new XmlFormatter(); - $line = $f->format(array('message' => 'foo', 'priority' => 42)); - - $this->assertNotContains('<\?xml version=', $line); - } - - public function testXmlValidates() - { - $f = new XmlFormatter(); - $line = $f->format(array('message' => 'foo', 'priority' => 42)); - - $sxml = @simplexml_load_string($line); - $this->assertInstanceOf('SimpleXMLElement', $sxml, 'Formatted XML is invalid'); - } - - /** - * @group ZF-2062 - * @group ZF-4190 - */ - public function testHtmlSpecialCharsInMessageGetEscapedForValidXml() - { - $f = new XmlFormatter(); - $line = $f->format(array('message' => '&key1=value1&key2=value2', 'priority' => 42)); - - $this->assertContains("&", $line); - $this->assertTrue(substr_count($line, "&") == 2); - } - - /** - * @group ZF-2062 - * @group ZF-4190 - */ - public function testFixingBrokenCharsSoXmlIsValid() - { - $f = new XmlFormatter(); - $line = $f->format(array('message' => '&', 'priority' => 42)); - - $this->assertContains('&amp', $line); - } - - public function testConstructorWithArray() - { - $date = new DateTime(); - $options = array( - 'rootElement' => 'log', - 'elementMap' => array( - 'date' => 'timestamp', - 'word' => 'message', - 'priority' => 'priority' - ), - 'dateTimeFormat' => 'r', - ); - $event = array( - 'timestamp' => $date, - 'message' => 'tottakai', - 'priority' => 4 - ); - $expected = sprintf('%stottakai4', $date->format('r')); - - $formatter = new XmlFormatter($options); - $output = $formatter->format($event); - $this->assertContains($expected, $output); - $this->assertEquals('UTF-8', $formatter->getEncoding()); - } - - /** - * @group ZF-11161 - */ - public function testNonScalarValuesAreExcludedFromFormattedString() - { - $options = array( - 'rootElement' => 'log' - ); - $event = array( - 'message' => 'tottakai', - 'priority' => 4, - 'context' => array('test'=>'one'), - 'reference' => new XmlFormatter() - ); - $expected = 'tottakai4'; - - $formatter = new XmlFormatter($options); - $output = $formatter->format($event); - $this->assertContains($expected, $output); - } - - /** - * @group ZF-11161 - */ - public function testObjectsWithStringSerializationAreIncludedInFormattedString() - { - $options = array( - 'rootElement' => 'log' - ); - $event = array( - 'message' => 'tottakai', - 'priority' => 4, - 'context' => array('test'=>'one'), - 'reference' => new SerializableObject() - ); - $expected = 'tottakai4ZendTest\Log\TestAsset\SerializableObject'; - - $formatter = new XmlFormatter($options); - $output = $formatter->format($event); - $this->assertContains($expected, $output); - } - - /** - * @group ZF2-453 - */ - public function testFormatWillRemoveExtraEmptyArrayFromEvent() - { - $formatter = new XmlFormatter; - $d = new DateTime('2001-01-01T12:00:00-06:00'); - $event = array( - 'timestamp' => $d, - 'message' => 'test', - 'priority' => 1, - 'priorityName' => 'CRIT', - 'extra' => array() - ); - $expected = '2001-01-01T12:00:00-06:00test1CRIT'; - $expected .= PHP_EOL . PHP_EOL; - $this->assertEquals($expected, $formatter->format($event)); - } -} diff --git a/test/LoggerTest.php b/test/LoggerTest.php deleted file mode 100644 index 9343c885..00000000 --- a/test/LoggerTest.php +++ /dev/null @@ -1,262 +0,0 @@ -logger = new Logger; - } - - public function testUsesWriterPluginManagerByDefault() - { - $this->assertInstanceOf('Zend\Log\WriterPluginManager', $this->logger->getWriterPluginManager()); - } - - public function testPassingValidStringClassToSetPluginManager() - { - $this->logger->setWriterPluginManager('Zend\Log\WriterPluginManager'); - $this->assertInstanceOf('Zend\Log\WriterPluginManager', $this->logger->getWriterPluginManager()); - } - - public static function provideInvalidClasses() - { - return array( - array('stdClass'), - array(new \stdClass()), - ); - } - - /** - * @dataProvider provideInvalidClasses - */ - public function testPassingInvalidArgumentToSetPluginManagerRaisesException($plugins) - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); - $this->logger->setWriterPluginManager($plugins); - } - - public function testPassingShortNameToPluginReturnsWriterByThatName() - { - $writer = $this->logger->writerPlugin('mock'); - $this->assertInstanceOf('Zend\Log\Writer\Mock', $writer); - } - - public function testPassWriterAsString() - { - $this->logger->addWriter('mock'); - $writers = $this->logger->getWriters(); - $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); - } - - /** - * @dataProvider provideInvalidClasses - */ - public function testPassingInvalidArgumentToAddWriterRaisesException($writer) - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must implement'); - $this->logger->addWriter($writer); - } - - public function testEmptyWriter() - { - $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'No log writer specified'); - $this->logger->log(Logger::INFO, 'test'); - } - - public function testSetWriters() - { - $writer1 = $this->logger->writerPlugin('mock'); - $writer2 = $this->logger->writerPlugin('null'); - $writers = new SplPriorityQueue(); - $writers->insert($writer1, 1); - $writers->insert($writer2, 2); - $this->logger->setWriters($writers); - - $writers = $this->logger->getWriters(); - $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); - } - - public function testAddWriterWithPriority() - { - $writer1 = $this->logger->writerPlugin('mock'); - $this->logger->addWriter($writer1,1); - $writer2 = $this->logger->writerPlugin('null'); - $this->logger->addWriter($writer2,2); - $writers = $this->logger->getWriters(); - - $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); - - } - - public function testAddWithSamePriority() - { - $writer1 = $this->logger->writerPlugin('mock'); - $this->logger->addWriter($writer1,1); - $writer2 = $this->logger->writerPlugin('null'); - $this->logger->addWriter($writer2,1); - $writers = $this->logger->getWriters(); - - $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); - $writer = $writers->extract(); - $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); - } - - public function testLogging() - { - $writer = new MockWriter; - $this->logger->addWriter($writer); - $this->logger->log(Logger::INFO, 'tottakai'); - - $this->assertEquals(count($writer->events), 1); - $this->assertContains('tottakai', $writer->events[0]['message']); - } - - public function testLoggingArray() - { - $writer = new MockWriter; - $this->logger->addWriter($writer); - $this->logger->log(Logger::INFO, array('test')); - - $this->assertEquals(count($writer->events), 1); - $this->assertContains('test', $writer->events[0]['message']); - } - - public function testAddFilter() - { - $writer = new MockWriter; - $filter = new MockFilter; - $writer->addFilter($filter); - $this->logger->addWriter($writer); - $this->logger->log(Logger::INFO, array('test')); - - $this->assertEquals(count($filter->events), 1); - $this->assertContains('test', $filter->events[0]['message']); - } - - public function testAddFilterByName() - { - $writer = new MockWriter; - $writer->addFilter('mock'); - $this->logger->addWriter($writer); - $this->logger->log(Logger::INFO, array('test')); - - $this->assertEquals(count($writer->events), 1); - $this->assertContains('test', $writer->events[0]['message']); - } - - /** - * provideTestFilters - */ - public function provideTestFilters() - { - return array( - array('priority', array('priority' => Logger::INFO)), - array('regex', array( 'regex' => '/[0-9]+/' )), - array('validator', array('validator' => new DigitsFilter)), - ); - } - - /** - * @dataProvider provideTestFilters - */ - public function testAddFilterByNameWithParams($filter, $options) - { - $writer = new MockWriter; - $writer->addFilter($filter, $options); - $this->logger->addWriter($writer); - - $this->logger->log(Logger::INFO, '123'); - $this->assertEquals(count($writer->events), 1); - $this->assertContains('123', $writer->events[0]['message']); - } - - public static function provideAttributes() - { - return array( - array(array()), - array(array('user' => 'foo', 'ip' => '127.0.0.1')), - array(new \ArrayObject(array('id' => 42))), - ); - } - - /** - * @dataProvider provideAttributes - */ - public function testLoggingCustomAttributesForUserContext($extra) - { - $writer = new MockWriter; - $this->logger->addWriter($writer); - $this->logger->log(Logger::ERR, 'tottakai', $extra); - - $this->assertEquals(count($writer->events), 1); - $this->assertInternalType('array', $writer->events[0]['extra']); - $this->assertEquals(count($writer->events[0]['extra']), count($extra)); - } - - public static function provideInvalidArguments() - { - return array( - array(new \stdClass(), array('valid')), - array('valid', null), - array('valid', true), - array('valid', 10), - array('valid', 'invalid'), - array('valid', new \stdClass()), - ); - } - - /** - * @dataProvider provideInvalidArguments - */ - public function testPassingInvalidArgumentToLogRaisesException($message, $extra) - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); - $this->logger->log(Logger::ERR, $message, $extra); - } - - public function testRegisterErrorHandler() - { - $writer = new MockWriter; - $this->logger->addWriter($writer); - - $this->assertTrue(Logger::registerErrorHandler($this->logger)); - // check for single error handler instance - $this->assertFalse(Logger::registerErrorHandler($this->logger)); - // generate a warning - echo $test; - Logger::unregisterErrorHandler(); - $this->assertEquals($writer->events[0]['message'], 'Undefined variable: test'); - } -} diff --git a/test/TestAsset/ConcreteWriter.php b/test/TestAsset/ConcreteWriter.php deleted file mode 100644 index bb4644da..00000000 --- a/test/TestAsset/ConcreteWriter.php +++ /dev/null @@ -1,20 +0,0 @@ -facility; - } -} diff --git a/test/TestAsset/MockFirePhp.php b/test/TestAsset/MockChromePhp.php similarity index 100% rename from test/TestAsset/MockFirePhp.php rename to test/TestAsset/MockChromePhp.php diff --git a/test/TestAsset/MockDbAdapter.php b/test/TestAsset/MockDbAdapter.php deleted file mode 100644 index 6f8eec29..00000000 --- a/test/TestAsset/MockDbAdapter.php +++ /dev/null @@ -1,38 +0,0 @@ -calls[$method][] = $params; - } - - public function __construct() - { - $this->platform = new MockDbPlatform; - $this->driver = new MockDbDriver; - - } - public function query($sql, $parametersOrQueryMode = DbAdapter::QUERY_MODE_PREPARE) - { - $this->calls[__FUNCTION__][] = $sql; - return $this; - } -} diff --git a/test/TestAsset/MockDbDriver.php b/test/TestAsset/MockDbDriver.php deleted file mode 100644 index 56c667f7..00000000 --- a/test/TestAsset/MockDbDriver.php +++ /dev/null @@ -1,21 +0,0 @@ -calls[$method][] = $params; - } - -} diff --git a/test/TestAsset/MockDbPlatform.php b/test/TestAsset/MockDbPlatform.php deleted file mode 100644 index a0d9415c..00000000 --- a/test/TestAsset/MockDbPlatform.php +++ /dev/null @@ -1,21 +0,0 @@ -calls[$method][] = $params; - } - -} diff --git a/test/TestAsset/SerializableObject.php b/test/TestAsset/SerializableObject.php deleted file mode 100644 index da5e2b9a..00000000 --- a/test/TestAsset/SerializableObject.php +++ /dev/null @@ -1,19 +0,0 @@ -_writer = new ConcreteWriter(); - } - - /** - * @group ZF-6085 - */ - public function testSetFormatter() - { - $this->_writer->setFormatter(new SimpleFormatter()); - $this->setExpectedException('PHPUnit_Framework_Error'); - $this->_writer->setFormatter(new \StdClass()); - } - - public function testAddFilter() - { - $this->_writer->addFilter(1); - $this->_writer->addFilter(new RegexFilter('/mess/')); - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); - $this->_writer->addFilter(new \StdClass()); - } - - public function testAddMockFilterByName() - { - $instance = $this->_writer->addFilter('mock'); - $this->assertTrue($instance instanceof ConcreteWriter); - } - - public function testAddRegexFilterWithParamsByName() - { - $instance = $this->_writer->addFilter('regex', array( 'regex' => '/mess/' )); - $this->assertTrue($instance instanceof ConcreteWriter); - } - - /** - * @group ZF-8953 - */ - public function testFluentInterface() - { - $instance = $this->_writer->addFilter(1) - ->setFormatter(new SimpleFormatter()); - - $this->assertTrue($instance instanceof ConcreteWriter); - } -} diff --git a/test/Writer/FirePhpTest.php b/test/Writer/ChromePhpTest.php similarity index 100% rename from test/Writer/FirePhpTest.php rename to test/Writer/ChromePhpTest.php diff --git a/test/Writer/DbTest.php b/test/Writer/DbTest.php deleted file mode 100644 index f20717ce..00000000 --- a/test/Writer/DbTest.php +++ /dev/null @@ -1,215 +0,0 @@ -tableName = 'db-table-name'; - - $this->db = new MockDbAdapter(); - $this->writer = new DbWriter($this->db, $this->tableName); - } - - public function testFormattingIsNotSupported() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'does not support formatting'); - $this->writer->setFormatter(new SimpleFormatter); - } - - public function testNotPassingTableNameToConstructorThrowsException() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'table name'); - $writer = new DbWriter($this->db); - } - - public function testNotPassingDbToConstructorThrowsException() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Adapter'); - $writer = new DbWriter(array()); - } - - public function testPassingTableNameAsArgIsOK() - { - $options = array( - 'db' => $this->db, - 'table' => $this->tableName, - ); - $writer = new DbWriter($options); - $this->assertInstanceOf('Zend\Log\Writer\Db', $writer); - $this->assertAttributeEquals($this->tableName, 'tableName', $writer); - } - - public function testWriteWithDefaults() - { - // log to the mock db adapter - $fields = array( - 'message' => 'foo', - 'priority' => 42 - ); - - $this->writer->write($fields); - - // insert should be called once... - $this->assertContains('query', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['query'])); - $this->assertContains('execute', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['execute'])); - $this->assertEquals(array($fields), $this->db->calls['execute'][0]); - } - - public function testWriteWithDefaultsUsingArray() - { - // log to the mock db adapter - $message = 'message-to-log'; - $priority = 2; - $events = array( - 'file' => 'test', - 'line' => 1 - ); - $this->writer->write(array( - 'message' => $message, - 'priority' => $priority, - 'events' => $events - )); - $this->assertContains('query', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['query'])); - - $binds = array( - 'message' => $message, - 'priority' => $priority, - 'events_line' => $events['line'], - 'events_file' => $events['file'] - ); - $this->assertEquals(array($binds), $this->db->calls['execute'][0]); - } - - public function testWriteWithDefaultsUsingArrayAndSeparator() - { - $this->writer = new DbWriter($this->db, $this->tableName, null, '-'); - - // log to the mock db adapter - $message = 'message-to-log'; - $priority = 2; - $events = array( - 'file' => 'test', - 'line' => 1 - ); - $this->writer->write(array( - 'message' => $message, - 'priority' => $priority, - 'events' => $events - )); - $this->assertContains('query', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['query'])); - - $binds = array( - 'message' => $message, - 'priority' => $priority, - 'events-line' => $events['line'], - 'events-file' => $events['file'] - ); - $this->assertEquals(array($binds), $this->db->calls['execute'][0]); - } - - public function testWriteUsesOptionalCustomColumnNames() - { - $this->writer = new DbWriter($this->db, $this->tableName, array( - 'message' => 'new-message-field' , - 'priority' => 'new-priority-field' - )); - - // log to the mock db adapter - $message = 'message-to-log'; - $priority = 2; - $this->writer->write(array( - 'message' => $message, - 'priority' => $priority - )); - - // insert should be called once... - $this->assertContains('query', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['query'])); - - // ...with the correct table and binds for the database - $binds = array( - 'new-message-field' => $message, - 'new-priority-field' => $priority - ); - $this->assertEquals(array($binds), $this->db->calls['execute'][0]); - } - - public function testWriteUsesParamsWithArray() - { - $this->writer = new DbWriter($this->db, $this->tableName, array( - 'message' => 'new-message-field' , - 'priority' => 'new-priority-field', - 'events' => array( - 'line' => 'new-line', - 'file' => 'new-file' - ) - )); - - // log to the mock db adapter - $message = 'message-to-log'; - $priority = 2; - $events = array( - 'file' => 'test', - 'line' => 1 - ); - $this->writer->write(array( - 'message' => $message, - 'priority' => $priority, - 'events' => $events - )); - $this->assertContains('query', array_keys($this->db->calls)); - $this->assertEquals(1, count($this->db->calls['query'])); - // ...with the correct table and binds for the database - $binds = array( - 'new-message-field' => $message, - 'new-priority-field' => $priority, - 'new-line' => $events['line'], - 'new-file' => $events['file'] - ); - $this->assertEquals(array($binds), $this->db->calls['execute'][0]); - } - - public function testShutdownRemovesReferenceToDatabaseInstance() - { - $this->writer->write(array('message' => 'this should not fail')); - $this->writer->shutdown(); - - $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Database adapter is null'); - $this->writer->write(array('message' => 'this should fail')); - } - - /** - * @group ZF-10089 - */ - public function testThrowStrictSetFormatter() - { - $this->setExpectedException('PHPUnit_Framework_Error'); - $this->writer->setFormatter(new \StdClass()); - } -} diff --git a/test/Writer/MailTest.php b/test/Writer/MailTest.php deleted file mode 100644 index cc01fcb6..00000000 --- a/test/Writer/MailTest.php +++ /dev/null @@ -1,87 +0,0 @@ - __DIR__, - 'callback' => function (Transport\File $transport) { - return MailTest::FILENAME; - }, - )); - $transport->setOptions($options); - - $this->writer = new MailWriter($message, $transport); - $this->log = new Logger(); - $this->log->addWriter($this->writer); - } - - protected function tearDown() - { - @unlink(__DIR__. '/' . self::FILENAME); - } - - /** - * Tests normal logging, but with multiple messages for a level. - * - * @return void - */ - public function testNormalLoggingMultiplePerLevel() - { - $this->log->info('an info message'); - $this->log->info('a second info message'); - unset($this->log); - - $contents = file_get_contents(__DIR__ . '/' . self::FILENAME); - $this->assertContains('an info message', $contents); - $this->assertContains('a second info message', $contents); - } - - public function testSetSubjectPrependText() - { - $this->writer->setSubjectPrependText('test'); - - $this->log->info('an info message'); - $this->log->info('a second info message'); - unset($this->log); - - $contents = file_get_contents(__DIR__ . '/' . self::FILENAME); - $this->assertContains('an info message', $contents); - $this->assertContains('Subject: test', $contents); - } -} diff --git a/test/Writer/MockTest.php b/test/Writer/MockTest.php deleted file mode 100644 index f8a0f778..00000000 --- a/test/Writer/MockTest.php +++ /dev/null @@ -1,33 +0,0 @@ -assertSame(array(), $writer->events); - - $fields = array('foo' => 'bar'); - $writer->write($fields); - $this->assertSame(array($fields), $writer->events); - } -} diff --git a/test/Writer/MongoDBTest.php b/test/Writer/MongoDBTest.php deleted file mode 100644 index 1d2e3416..00000000 --- a/test/Writer/MongoDBTest.php +++ /dev/null @@ -1,102 +0,0 @@ -markTestSkipped('The mongo PHP extension is not available'); - } - - $this->database = 'zf2_test'; - $this->collection = 'logs'; - - $this->mongo = $this->getMockBuilder('Mongo') - ->disableOriginalConstructor() - ->setMethods(array('selectCollection')) - ->getMock(); - - $this->mongoCollection = $this->getMockBuilder('MongoCollection') - ->disableOriginalConstructor() - ->setMethods(array('save')) - ->getMock(); - - $this->mongo->expects($this->any()) - ->method('selectCollection') - ->with($this->database, $this->collection) - ->will($this->returnValue($this->mongoCollection)); - } - - /** - * @expectedException Zend\Log\Exception\InvalidArgumentException - */ - public function testFormattingIsNotSupported() - { - $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); - - $writer->setFormatter($this->getMock('Zend\Log\Formatter\FormatterInterface')); - } - - public function testWriteWithDefaultSaveOptions() - { - $event = array('message'=> 'foo', 'priority' => 42); - - $this->mongoCollection->expects($this->once()) - ->method('save') - ->with($event, array()); - - $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); - - $writer->write($event); - } - - public function testWriteWithCustomSaveOptions() - { - $event = array('message' => 'foo', 'priority' => 42); - $saveOptions = array('safe' => false, 'fsync' => false, 'timeout' => 100); - - $this->mongoCollection->expects($this->once()) - ->method('save') - ->with($event, $saveOptions); - - $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection, $saveOptions); - - $writer->write($event); - } - - public function testWriteConvertsDateTimeToMongoDate() - { - $date = new DateTime(); - $event = array('timestamp'=> $date); - - $this->mongoCollection->expects($this->once()) - ->method('save') - ->with($this->contains(new MongoDate($date->getTimestamp()), false)); - - $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); - - $writer->write($event); - } -} diff --git a/test/Writer/NullTest.php b/test/Writer/NullTest.php deleted file mode 100644 index 07dfaebd..00000000 --- a/test/Writer/NullTest.php +++ /dev/null @@ -1,29 +0,0 @@ -write(array('message' => 'foo', 'priority' => 42)); - } -} diff --git a/test/Writer/StreamTest.php b/test/Writer/StreamTest.php deleted file mode 100644 index 098d5e28..00000000 --- a/test/Writer/StreamTest.php +++ /dev/null @@ -1,150 +0,0 @@ -fail(); - } catch (\Exception $e) { - $this->assertInstanceOf('Zend\Log\Exception\InvalidArgumentException', $e); - $this->assertRegExp('/not a stream/i', $e->getMessage()); - } - xml_parser_free($resource); - } - - public function testConstructorWithValidStream() - { - $stream = fopen('php://memory', 'w+'); - new StreamWriter($stream); - } - - public function testConstructorWithValidUrl() - { - new StreamWriter('php://memory'); - } - - public function testConstructorThrowsWhenModeSpecifiedForExistingStream() - { - $stream = fopen('php://memory', 'w+'); - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'existing stream'); - new StreamWriter($stream, 'w+'); - } - - public function testConstructorThrowsWhenStreamCannotBeOpened() - { - $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'cannot be opened'); - new StreamWriter(''); - } - - public function testWrite() - { - $stream = fopen('php://memory', 'w+'); - $fields = array('message' => 'message-to-log'); - - $writer = new StreamWriter($stream); - $writer->write($fields); - - rewind($stream); - $contents = stream_get_contents($stream); - fclose($stream); - - $this->assertContains($fields['message'], $contents); - } - - public function testWriteThrowsWhenStreamWriteFails() - { - $stream = fopen('php://memory', 'w+'); - $writer = new StreamWriter($stream); - fclose($stream); - - $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Unable to write'); - $writer->write(array('message' => 'foo')); - } - - public function testShutdownClosesStreamResource() - { - $writer = new StreamWriter('php://memory', 'w+'); - $writer->write(array('message' => 'this write should succeed')); - - $writer->shutdown(); - - $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Unable to write'); - $writer->write(array('message' => 'this write should fail')); - } - - public function testSettingNewFormatter() - { - $stream = fopen('php://memory', 'w+'); - $writer = new StreamWriter($stream); - $expected = 'foo'; - - $formatter = new SimpleFormatter($expected); - $writer->setFormatter($formatter); - - $writer->write(array('bar'=>'baz')); - rewind($stream); - $contents = stream_get_contents($stream); - fclose($stream); - - $this->assertContains($expected, $contents); - } - - public function testAllowSpecifyingLogSeparator() - { - $stream = fopen('php://memory', 'w+'); - $writer = new StreamWriter($stream); - $writer->setLogSeparator('::'); - - $fields = array('message' => 'message1'); - $writer->write($fields); - $fields['message'] = 'message2'; - $writer->write($fields); - - rewind($stream); - $contents = stream_get_contents($stream); - fclose($stream); - - $this->assertRegexp('/message1.*?::.*?message2/', $contents); - $this->assertNotContains(PHP_EOL, $contents); - } - - public function testAllowsSpecifyingLogSeparatorAsConstructorArgument() - { - $writer = new StreamWriter('php://memory', 'w+', '::'); - $this->assertEquals('::', $writer->getLogSeparator()); - } - - public function testAllowsSpecifyingLogSeparatorWithinArrayPassedToConstructor() - { - $options = array( - 'stream' => 'php://memory', - 'mode' => 'w+', - 'log_separator' => '::', - ); - $writer = new StreamWriter($options); - $this->assertEquals('::', $writer->getLogSeparator()); - } -} diff --git a/test/Writer/SyslogTest.php b/test/Writer/SyslogTest.php deleted file mode 100644 index a57a0afe..00000000 --- a/test/Writer/SyslogTest.php +++ /dev/null @@ -1,96 +0,0 @@ - 'foo', - 'priority' => LOG_NOTICE - ); - $writer = new SyslogWriter(); - $writer->write($fields); - } - - /** - * @group ZF-7603 - */ - public function testThrowExceptionValueNotPresentInFacilities() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Invalid log facility provided'); - $writer = new SyslogWriter(); - $writer->setFacility(LOG_USER * 1000); - } - - /** - * @group ZF-7603 - */ - public function testThrowExceptionIfFacilityInvalidInWindows() - { - if ('WIN' != strtoupper(substr(PHP_OS, 0, 3))) { - $this->markTestSkipped('Run only in windows'); - } - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Only LOG_USER is a valid'); - $writer = new SyslogWriter(); - $writer->setFacility(LOG_AUTH); - } - - /** - * @group ZF-8953 - */ - public function testFluentInterface() - { - $writer = new SyslogWriter(); - $instance = $writer->setFacility(LOG_USER) - ->setApplicationName('my_app'); - - $this->assertTrue($instance instanceof SyslogWriter); - } - - /** - * @group ZF-10769 - */ - public function testPastFacilityViaConstructor() - { - $writer = new CustomSyslogWriter(array('facility' => LOG_USER)); - $this->assertEquals(LOG_USER, $writer->getFacility()); - } - - /** - * @group ZF-8382 - */ - public function testWriteWithFormatter() - { - $event = array( - 'message' => 'tottakai', - 'priority' => Logger::ERR - ); - - $writer = new SyslogWriter(); - $formatter = new SimpleFormatter('%message% (this is a test)'); - $writer->setFormatter($formatter); - - $writer->write($event); - } -} diff --git a/test/Writer/ZendMonitorTest.php b/test/Writer/ZendMonitorTest.php deleted file mode 100644 index a1ce8616..00000000 --- a/test/Writer/ZendMonitorTest.php +++ /dev/null @@ -1,40 +0,0 @@ -write(array( - 'message' => 'my mess', - 'priority' => 1 - )); - } - - public function testIsEnabled() - { - $writer = new ZendMonitor(); - $this->assertInternalType('boolean', $writer->isEnabled()); - } -} diff --git a/test/WriterPluginManagerTest.php b/test/WriterPluginManagerTest.php deleted file mode 100644 index 6ad21b06..00000000 --- a/test/WriterPluginManagerTest.php +++ /dev/null @@ -1,44 +0,0 @@ -plugins = new WriterPluginManager(); - } - - public function testRegisteringInvalidWriterRaisesException() - { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must implement'); - $this->plugins->setService('test', $this); - } - - public function testInvokableClassFirephp() - { - $firephp = $this->plugins->get('firephp'); - $this->assertInstanceOf('Zend\Log\Writer\Firephp', $firephp); - } -} diff --git a/test/_files/layout.phtml b/test/_files/layout.phtml deleted file mode 100644 index b1ebac07..00000000 --- a/test/_files/layout.phtml +++ /dev/null @@ -1 +0,0 @@ -layout()->events; \ No newline at end of file From 6ebda1b3d0036f0eeb10f971d8c7f67ed29c1c9d Mon Sep 17 00:00:00 2001 From: Walter Tamboer Date: Thu, 2 Aug 2012 18:42:30 +0200 Subject: [PATCH 03/32] Added tests for ChromePhp --- test/TestAsset/MockChromePhp.php | 4 +-- test/Writer/ChromePhpTest.php | 56 ++++++++++++++------------------ 2 files changed, 26 insertions(+), 34 deletions(-) diff --git a/test/TestAsset/MockChromePhp.php b/test/TestAsset/MockChromePhp.php index 41b4933f..814bedfe 100644 --- a/test/TestAsset/MockChromePhp.php +++ b/test/TestAsset/MockChromePhp.php @@ -1,9 +1,9 @@ firephp = new MockFirePhp(); + $this->chromephp = new MockChromePhp(); } - /** - * Test get FirePhp - */ - public function testGetFirePhp() + + public function testGetChromePhp() { - $writer = new FirePhp($this->firephp); - $this->assertTrue($writer->getFirePhp() instanceof FirePhpInterface); + $writer = new ChromePhp($this->chromephp); + $this->assertTrue($writer->getChromePhp() instanceof ChromePhpInterface); } - /** - * Test set firephp - */ - public function testSetFirePhp() + + public function testSetChromePhp() { - $writer = new FirePhp($this->firephp); - $firephp2 = new MockFirePhp(); + $writer = new ChromePhp($this->chromephp); + $chromephp2 = new MockChromePhp(); - $writer->setFirePhp($firephp2); - $this->assertTrue($writer->getFirePhp() instanceof FirePhpInterface); - $this->assertEquals($firephp2, $writer->getFirePhp()); + $writer->setChromePhp($chromephp2); + $this->assertTrue($writer->getChromePhp() instanceof ChromePhpInterface); + $this->assertEquals($chromephp2, $writer->getChromePhp()); } - /** - * Test write - */ + public function testWrite() { - $writer = new FirePhp($this->firephp); + $writer = new ChromePhp($this->chromephp); $writer->write(array( 'message' => 'my msg', 'priority' => Logger::DEBUG )); - $this->assertEquals('my msg', $this->firephp->calls['trace'][0]); + $this->assertEquals('my msg', $this->chromephp->calls['trace'][0]); } - /** - * Test write with FirePhp disabled - */ + public function testWriteDisabled() { - $firephp = new MockFirePhp(false); - $writer = new FirePhp($firephp); + $chromephp = new MockChromePhp(false); + $writer = new ChromePhp($chromephp); $writer->write(array( 'message' => 'my msg', 'priority' => Logger::DEBUG )); - $this->assertTrue(empty($this->firephp->calls)); + $this->assertTrue(empty($this->chromephp->calls)); } } From 966506e419c475bc3b970a1640732a39762bfcdb Mon Sep 17 00:00:00 2001 From: Walter Tamboer Date: Tue, 21 Aug 2012 21:32:22 +0200 Subject: [PATCH 04/32] Moved the chrome tests from Zend to ZendTest --- test/Filter/MockTest.php | 33 +++ test/Filter/PriorityTest.php | 49 +++++ test/Filter/RegexTest.php | 37 ++++ test/Filter/SuppressFilterTest.php | 57 ++++++ test/Filter/ValidatorTest.php | 45 ++++ test/Formatter/ErrorHandlerTest.php | 53 +++++ test/Formatter/ExceptionHandlerTest.php | 120 +++++++++++ test/Formatter/FirePhpTest.php | 54 +++++ test/Formatter/SimpleTest.php | 144 +++++++++++++ test/Formatter/XmlTest.php | 200 ++++++++++++++++++ test/LoggerTest.php | 262 ++++++++++++++++++++++++ test/TestAsset/ConcreteWriter.php | 20 ++ test/TestAsset/CustomSyslogWriter.php | 21 ++ test/TestAsset/MockDbAdapter.php | 38 ++++ test/TestAsset/MockDbDriver.php | 21 ++ test/TestAsset/MockDbPlatform.php | 21 ++ test/TestAsset/MockFirePhp.php | 46 +++++ test/TestAsset/SerializableObject.php | 19 ++ test/TestAsset/StringObject.php | 19 ++ test/Writer/AbstractTest.php | 72 +++++++ test/Writer/DbTest.php | 215 +++++++++++++++++++ test/Writer/FirePhpTest.php | 91 ++++++++ test/Writer/MailTest.php | 87 ++++++++ test/Writer/MockTest.php | 33 +++ test/Writer/MongoDBTest.php | 102 +++++++++ test/Writer/NullTest.php | 29 +++ test/Writer/StreamTest.php | 150 ++++++++++++++ test/Writer/SyslogTest.php | 96 +++++++++ test/Writer/ZendMonitorTest.php | 40 ++++ test/WriterPluginManagerTest.php | 44 ++++ test/_files/layout.phtml | 1 + 31 files changed, 2219 insertions(+) create mode 100644 test/Filter/MockTest.php create mode 100644 test/Filter/PriorityTest.php create mode 100644 test/Filter/RegexTest.php create mode 100644 test/Filter/SuppressFilterTest.php create mode 100644 test/Filter/ValidatorTest.php create mode 100644 test/Formatter/ErrorHandlerTest.php create mode 100644 test/Formatter/ExceptionHandlerTest.php create mode 100644 test/Formatter/FirePhpTest.php create mode 100644 test/Formatter/SimpleTest.php create mode 100644 test/Formatter/XmlTest.php create mode 100644 test/LoggerTest.php create mode 100644 test/TestAsset/ConcreteWriter.php create mode 100644 test/TestAsset/CustomSyslogWriter.php create mode 100644 test/TestAsset/MockDbAdapter.php create mode 100644 test/TestAsset/MockDbDriver.php create mode 100644 test/TestAsset/MockDbPlatform.php create mode 100644 test/TestAsset/MockFirePhp.php create mode 100644 test/TestAsset/SerializableObject.php create mode 100644 test/TestAsset/StringObject.php create mode 100644 test/Writer/AbstractTest.php create mode 100644 test/Writer/DbTest.php create mode 100644 test/Writer/FirePhpTest.php create mode 100644 test/Writer/MailTest.php create mode 100644 test/Writer/MockTest.php create mode 100644 test/Writer/MongoDBTest.php create mode 100644 test/Writer/NullTest.php create mode 100644 test/Writer/StreamTest.php create mode 100644 test/Writer/SyslogTest.php create mode 100644 test/Writer/ZendMonitorTest.php create mode 100644 test/WriterPluginManagerTest.php create mode 100644 test/_files/layout.phtml diff --git a/test/Filter/MockTest.php b/test/Filter/MockTest.php new file mode 100644 index 00000000..d198332b --- /dev/null +++ b/test/Filter/MockTest.php @@ -0,0 +1,33 @@ +assertSame(array(), $filter->events); + + $fields = array('foo' => 'bar'); + $this->assertTrue($filter->filter($fields)); + $this->assertSame(array($fields), $filter->events); + } +} diff --git a/test/Filter/PriorityTest.php b/test/Filter/PriorityTest.php new file mode 100644 index 00000000..905eb146 --- /dev/null +++ b/test/Filter/PriorityTest.php @@ -0,0 +1,49 @@ +assertTrue($filter->filter(array('priority' => 2))); + $this->assertTrue($filter->filter(array('priority' => 1))); + $this->assertFalse($filter->filter(array('priority' => 3))); + } + + public function testComparisonOperatorCanBeChanged() + { + // accept above priority 2 + $filter = new Priority(2, '>'); + + $this->assertTrue($filter->filter(array('priority' => 3))); + $this->assertFalse($filter->filter(array('priority' => 2))); + $this->assertFalse($filter->filter(array('priority' => 1))); + } + + public function testConstructorThrowsOnInvalidPriority() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be an integer'); + new Priority('foo'); + } +} diff --git a/test/Filter/RegexTest.php b/test/Filter/RegexTest.php new file mode 100644 index 00000000..b757c761 --- /dev/null +++ b/test/Filter/RegexTest.php @@ -0,0 +1,37 @@ +setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'invalid reg'); + new Regex('invalid regexp'); + } + + public function testMessageFilter() + { + $filter = new Regex('/accept/'); + $this->assertTrue($filter->filter(array('message' => 'foo accept bar'))); + $this->assertFalse($filter->filter(array('message' => 'foo reject bar'))); + } +} diff --git a/test/Filter/SuppressFilterTest.php b/test/Filter/SuppressFilterTest.php new file mode 100644 index 00000000..c16062f0 --- /dev/null +++ b/test/Filter/SuppressFilterTest.php @@ -0,0 +1,57 @@ +filter = new SuppressFilter(); + } + + public function testSuppressIsInitiallyOff() + { + $this->assertTrue($this->filter->filter(array())); + } + + public function testSuppressOn() + { + $this->filter->suppress(true); + $this->assertFalse($this->filter->filter(array())); + $this->assertFalse($this->filter->filter(array())); + } + + public function testSuppressOff() + { + $this->filter->suppress(false); + $this->assertTrue($this->filter->filter(array())); + $this->assertTrue($this->filter->filter(array())); + } + + public function testSuppressCanBeReset() + { + $this->filter->suppress(true); + $this->assertFalse($this->filter->filter(array())); + $this->filter->suppress(false); + $this->assertTrue($this->filter->filter(array())); + $this->filter->suppress(true); + $this->assertFalse($this->filter->filter(array())); + } +} diff --git a/test/Filter/ValidatorTest.php b/test/Filter/ValidatorTest.php new file mode 100644 index 00000000..3e7a1181 --- /dev/null +++ b/test/Filter/ValidatorTest.php @@ -0,0 +1,45 @@ +assertTrue($filter->filter(array('message' => '123'))); + $this->assertFalse($filter->filter(array('message' => 'test'))); + $this->assertFalse($filter->filter(array('message' => 'test123'))); + $this->assertFalse($filter->filter(array('message' => '(%$'))); + } + + public function testValidatorChain() + { + $validatorChain = new ValidatorChain(); + $validatorChain->addValidator(new DigitsFilter()); + $validatorChain->addValidator(new Int()); + $filter = new Validator($validatorChain); + $this->assertTrue($filter->filter(array('message' => '123'))); + $this->assertFalse($filter->filter(array('message' => 'test'))); + } +} diff --git a/test/Formatter/ErrorHandlerTest.php b/test/Formatter/ErrorHandlerTest.php new file mode 100644 index 00000000..829b91ac --- /dev/null +++ b/test/Formatter/ErrorHandlerTest.php @@ -0,0 +1,53 @@ + $date, + 'message' => 'test', + 'priority' => 1, + 'priorityName' => 'CRIT', + 'extra' => array ( + 'errno' => 1, + 'file' => 'test.php', + 'line' => 1 + ) + ); + $formatter = new ErrorHandler(); + $output = $formatter->format($event); + + $this->assertEquals($date->format('c') . ' CRIT (1) test (errno 1) in test.php on line 1', $output); + } + + public function testSetDateTimeFormat() + { + $formatter = new ErrorHandler(); + + $this->assertEquals('c', $formatter->getDateTimeFormat()); + $this->assertSame($formatter, $formatter->setDateTimeFormat('r')); + $this->assertEquals('r', $formatter->getDateTimeFormat()); + } +} diff --git a/test/Formatter/ExceptionHandlerTest.php b/test/Formatter/ExceptionHandlerTest.php new file mode 100644 index 00000000..20cae5bc --- /dev/null +++ b/test/Formatter/ExceptionHandlerTest.php @@ -0,0 +1,120 @@ + $date, + 'message' => 'test', + 'priority' => 1, + 'priorityName' => 'CRIT', + 'extra' => array( + 'file' => 'test.php', + 'line' => 1, + 'trace' => array( + array( + 'file' => 'test.php', + 'line' => 1, + 'function' => 'test', + 'class' => 'Test', + 'type' => '::', + 'args' => array(1) + ), + array( + 'file' => 'test.php', + 'line' => 2, + 'function' => 'test', + 'class' => 'Test', + 'type' => '::', + 'args' => array(1) + ) + ) + ) + ); + + // The formatter ends with unix style line endings so make sure we expect that + // output as well: + $expected = $date->format('c') . " CRIT (1) test in test.php on line 1\n"; + $expected .= "[Trace]\n"; + $expected .= "File : test.php\n"; + $expected .= "Line : 1\n"; + $expected .= "Func : test\n"; + $expected .= "Class : Test\n"; + $expected .= "Type : static\n"; + $expected .= "Args : Array\n"; + $expected .= "(\n"; + $expected .= " [0] => 1\n"; + $expected .= ")\n\n"; + $expected .= "File : test.php\n"; + $expected .= "Line : 2\n"; + $expected .= "Func : test\n"; + $expected .= "Class : Test\n"; + $expected .= "Type : static\n"; + $expected .= "Args : Array\n"; + $expected .= "(\n"; + $expected .= " [0] => 1\n"; + $expected .= ")\n\n"; + + $formatter = new ExceptionHandler(); + $output = $formatter->format($event); + + $this->assertEquals($expected, $output); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormat($dateTimeFormat) + { + $date = new DateTime(); + + $event = array( + 'timestamp' => $date, + 'message' => 'test', + 'priority' => 1, + 'priorityName' => 'CRIT', + 'extra' => array( + 'file' => 'test.php', + 'line' => 1, + ), + ); + + $expected = $date->format($dateTimeFormat) . ' CRIT (1) test in test.php on line 1'; + + $formatter = new ExceptionHandler(); + + $this->assertSame($formatter, $formatter->setDateTimeFormat($dateTimeFormat)); + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + $this->assertEquals($expected, $formatter->format($event)); + } + + public function provideDateTimeFormats() + { + return array( + array('r'), + array('U'), + ); + } +} diff --git a/test/Formatter/FirePhpTest.php b/test/Formatter/FirePhpTest.php new file mode 100644 index 00000000..9fef4bf5 --- /dev/null +++ b/test/Formatter/FirePhpTest.php @@ -0,0 +1,54 @@ + 'foo' ); + + $f = new FirePhp(); + $line = $f->format($fields); + + $this->assertContains($fields['message'], $line); + } + + public function testSetDateTimeFormatDoesNothing() + { + $formatter = new FirePhp(); + + $this->assertEquals('', $formatter->getDateTimeFormat()); + $this->assertSame($formatter, $formatter->setDateTimeFormat('r')); + $this->assertEquals('', $formatter->getDateTimeFormat()); + } +} diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php new file mode 100644 index 00000000..8db4f10a --- /dev/null +++ b/test/Formatter/SimpleTest.php @@ -0,0 +1,144 @@ +setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be a string'); + new Simple(1); + } + + public function testDefaultFormat() + { + $date = new DateTime(); + $fields = array('timestamp' => $date, + 'message' => 'foo', + 'priority' => 42, + 'priorityName' => 'bar'); + + $f = new Simple(); + $line = $f->format($fields); + + $this->assertContains($date->format('c'), $line, 'Default date format is ISO 8601'); + $this->assertContains($fields['message'], $line); + $this->assertContains($fields['priorityName'], $line); + $this->assertContains((string)$fields['priority'], $line); + } + + public function testComplexValues() + { + $fields = array('timestamp' => new DateTime(), + 'priority' => 42, + 'priorityName' => 'bar'); + + $f = new Simple(); + + $fields['message'] = 'Foo'; + $line = $f->format($fields); + $this->assertContains($fields['message'], $line); + + $fields['message'] = 10; + $line = $f->format($fields); + $this->assertContains((string)$fields['message'], $line); + + $fields['message'] = 10.5; + $line = $f->format($fields); + $this->assertContains((string)$fields['message'], $line); + + $fields['message'] = true; + $line = $f->format($fields); + $this->assertContains('1', $line); + + $fields['message'] = fopen('php://stdout', 'w'); + $line = $f->format($fields); + $this->assertContains('Resource id ', $line); + fclose($fields['message']); + + $fields['message'] = range(1,10); + $line = $f->format($fields); + $this->assertContains('array', $line); + + $fields['message'] = new StringObject(); + $line = $f->format($fields); + $this->assertContains($fields['message']->__toString(), $line); + + $fields['message'] = new \stdClass(); + $line = $f->format($fields); + $this->assertContains('object', $line); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testCustomDateTimeFormat($dateTimeFormat) + { + $date = new DateTime(); + $event = array('timestamp' => $date); + $formatter = new Simple('%timestamp%', $dateTimeFormat); + + $this->assertEquals($date->format($dateTimeFormat), $formatter->format($event)); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormat($dateTimeFormat) + { + $date = new DateTime(); + $event = array('timestamp' => $date); + $formatter = new Simple('%timestamp%'); + + $this->assertSame($formatter, $formatter->setDateTimeFormat($dateTimeFormat)); + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + $this->assertEquals($date->format($dateTimeFormat), $formatter->format($event)); + } + + public function provideDateTimeFormats() + { + return array( + array('r'), + array('U'), + ); + } + + /** + * @group ZF-10427 + */ + public function testDefaultFormatShouldDisplayExtraInformations() + { + $message = 'custom message'; + $exception = new \RuntimeException($message); + $event = array( + 'timestamp' => new DateTime(), + 'message' => 'Application error', + 'priority' => 2, + 'priorityName' => 'CRIT', + 'info' => $exception, + ); + + $formatter = new Simple(); + $output = $formatter->format($event); + + $this->assertContains($message, $output); + } +} diff --git a/test/Formatter/XmlTest.php b/test/Formatter/XmlTest.php new file mode 100644 index 00000000..660aeaee --- /dev/null +++ b/test/Formatter/XmlTest.php @@ -0,0 +1,200 @@ +format(array('timestamp' => $date, 'message' => 'foo', 'priority' => 42)); + + $this->assertContains($date->format('c'), $line); + $this->assertContains('foo', $line); + $this->assertContains((string)42, $line); + } + + public function testConfiguringElementMapping() + { + $f = new XmlFormatter('log', array('foo' => 'bar')); + $line = $f->format(array('bar' => 'baz')); + $this->assertContains('baz', $line); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testConfiguringDateTimeFormat($dateTimeFormat) + { + $date = new DateTime(); + $f = new XmlFormatter('log', null, 'UTF-8', $dateTimeFormat); + $this->assertContains($date->format($dateTimeFormat), $f->format(array('timestamp' => $date))); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormat($dateTimeFormat) + { + $date = new DateTime(); + $f = new XmlFormatter(); + $this->assertSame($f, $f->setDateTimeFormat($dateTimeFormat)); + $this->assertContains($dateTimeFormat, $f->getDateTimeFormat()); + $this->assertContains($date->format($dateTimeFormat), $f->format(array('timestamp' => $date))); + } + + public function provideDateTimeFormats() + { + return array( + array('r'), + array('U'), + ); + } + + public function testXmlDeclarationIsStripped() + { + $f = new XmlFormatter(); + $line = $f->format(array('message' => 'foo', 'priority' => 42)); + + $this->assertNotContains('<\?xml version=', $line); + } + + public function testXmlValidates() + { + $f = new XmlFormatter(); + $line = $f->format(array('message' => 'foo', 'priority' => 42)); + + $sxml = @simplexml_load_string($line); + $this->assertInstanceOf('SimpleXMLElement', $sxml, 'Formatted XML is invalid'); + } + + /** + * @group ZF-2062 + * @group ZF-4190 + */ + public function testHtmlSpecialCharsInMessageGetEscapedForValidXml() + { + $f = new XmlFormatter(); + $line = $f->format(array('message' => '&key1=value1&key2=value2', 'priority' => 42)); + + $this->assertContains("&", $line); + $this->assertTrue(substr_count($line, "&") == 2); + } + + /** + * @group ZF-2062 + * @group ZF-4190 + */ + public function testFixingBrokenCharsSoXmlIsValid() + { + $f = new XmlFormatter(); + $line = $f->format(array('message' => '&', 'priority' => 42)); + + $this->assertContains('&amp', $line); + } + + public function testConstructorWithArray() + { + $date = new DateTime(); + $options = array( + 'rootElement' => 'log', + 'elementMap' => array( + 'date' => 'timestamp', + 'word' => 'message', + 'priority' => 'priority' + ), + 'dateTimeFormat' => 'r', + ); + $event = array( + 'timestamp' => $date, + 'message' => 'tottakai', + 'priority' => 4 + ); + $expected = sprintf('%stottakai4', $date->format('r')); + + $formatter = new XmlFormatter($options); + $output = $formatter->format($event); + $this->assertContains($expected, $output); + $this->assertEquals('UTF-8', $formatter->getEncoding()); + } + + /** + * @group ZF-11161 + */ + public function testNonScalarValuesAreExcludedFromFormattedString() + { + $options = array( + 'rootElement' => 'log' + ); + $event = array( + 'message' => 'tottakai', + 'priority' => 4, + 'context' => array('test'=>'one'), + 'reference' => new XmlFormatter() + ); + $expected = 'tottakai4'; + + $formatter = new XmlFormatter($options); + $output = $formatter->format($event); + $this->assertContains($expected, $output); + } + + /** + * @group ZF-11161 + */ + public function testObjectsWithStringSerializationAreIncludedInFormattedString() + { + $options = array( + 'rootElement' => 'log' + ); + $event = array( + 'message' => 'tottakai', + 'priority' => 4, + 'context' => array('test'=>'one'), + 'reference' => new SerializableObject() + ); + $expected = 'tottakai4ZendTest\Log\TestAsset\SerializableObject'; + + $formatter = new XmlFormatter($options); + $output = $formatter->format($event); + $this->assertContains($expected, $output); + } + + /** + * @group ZF2-453 + */ + public function testFormatWillRemoveExtraEmptyArrayFromEvent() + { + $formatter = new XmlFormatter; + $d = new DateTime('2001-01-01T12:00:00-06:00'); + $event = array( + 'timestamp' => $d, + 'message' => 'test', + 'priority' => 1, + 'priorityName' => 'CRIT', + 'extra' => array() + ); + $expected = '2001-01-01T12:00:00-06:00test1CRIT'; + $expected .= PHP_EOL . PHP_EOL; + $this->assertEquals($expected, $formatter->format($event)); + } +} diff --git a/test/LoggerTest.php b/test/LoggerTest.php new file mode 100644 index 00000000..9343c885 --- /dev/null +++ b/test/LoggerTest.php @@ -0,0 +1,262 @@ +logger = new Logger; + } + + public function testUsesWriterPluginManagerByDefault() + { + $this->assertInstanceOf('Zend\Log\WriterPluginManager', $this->logger->getWriterPluginManager()); + } + + public function testPassingValidStringClassToSetPluginManager() + { + $this->logger->setWriterPluginManager('Zend\Log\WriterPluginManager'); + $this->assertInstanceOf('Zend\Log\WriterPluginManager', $this->logger->getWriterPluginManager()); + } + + public static function provideInvalidClasses() + { + return array( + array('stdClass'), + array(new \stdClass()), + ); + } + + /** + * @dataProvider provideInvalidClasses + */ + public function testPassingInvalidArgumentToSetPluginManagerRaisesException($plugins) + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); + $this->logger->setWriterPluginManager($plugins); + } + + public function testPassingShortNameToPluginReturnsWriterByThatName() + { + $writer = $this->logger->writerPlugin('mock'); + $this->assertInstanceOf('Zend\Log\Writer\Mock', $writer); + } + + public function testPassWriterAsString() + { + $this->logger->addWriter('mock'); + $writers = $this->logger->getWriters(); + $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); + } + + /** + * @dataProvider provideInvalidClasses + */ + public function testPassingInvalidArgumentToAddWriterRaisesException($writer) + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must implement'); + $this->logger->addWriter($writer); + } + + public function testEmptyWriter() + { + $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'No log writer specified'); + $this->logger->log(Logger::INFO, 'test'); + } + + public function testSetWriters() + { + $writer1 = $this->logger->writerPlugin('mock'); + $writer2 = $this->logger->writerPlugin('null'); + $writers = new SplPriorityQueue(); + $writers->insert($writer1, 1); + $writers->insert($writer2, 2); + $this->logger->setWriters($writers); + + $writers = $this->logger->getWriters(); + $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); + } + + public function testAddWriterWithPriority() + { + $writer1 = $this->logger->writerPlugin('mock'); + $this->logger->addWriter($writer1,1); + $writer2 = $this->logger->writerPlugin('null'); + $this->logger->addWriter($writer2,2); + $writers = $this->logger->getWriters(); + + $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); + + } + + public function testAddWithSamePriority() + { + $writer1 = $this->logger->writerPlugin('mock'); + $this->logger->addWriter($writer1,1); + $writer2 = $this->logger->writerPlugin('null'); + $this->logger->addWriter($writer2,1); + $writers = $this->logger->getWriters(); + + $this->assertInstanceOf('Zend\Stdlib\SplPriorityQueue', $writers); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Mock); + $writer = $writers->extract(); + $this->assertTrue($writer instanceof \Zend\Log\Writer\Null); + } + + public function testLogging() + { + $writer = new MockWriter; + $this->logger->addWriter($writer); + $this->logger->log(Logger::INFO, 'tottakai'); + + $this->assertEquals(count($writer->events), 1); + $this->assertContains('tottakai', $writer->events[0]['message']); + } + + public function testLoggingArray() + { + $writer = new MockWriter; + $this->logger->addWriter($writer); + $this->logger->log(Logger::INFO, array('test')); + + $this->assertEquals(count($writer->events), 1); + $this->assertContains('test', $writer->events[0]['message']); + } + + public function testAddFilter() + { + $writer = new MockWriter; + $filter = new MockFilter; + $writer->addFilter($filter); + $this->logger->addWriter($writer); + $this->logger->log(Logger::INFO, array('test')); + + $this->assertEquals(count($filter->events), 1); + $this->assertContains('test', $filter->events[0]['message']); + } + + public function testAddFilterByName() + { + $writer = new MockWriter; + $writer->addFilter('mock'); + $this->logger->addWriter($writer); + $this->logger->log(Logger::INFO, array('test')); + + $this->assertEquals(count($writer->events), 1); + $this->assertContains('test', $writer->events[0]['message']); + } + + /** + * provideTestFilters + */ + public function provideTestFilters() + { + return array( + array('priority', array('priority' => Logger::INFO)), + array('regex', array( 'regex' => '/[0-9]+/' )), + array('validator', array('validator' => new DigitsFilter)), + ); + } + + /** + * @dataProvider provideTestFilters + */ + public function testAddFilterByNameWithParams($filter, $options) + { + $writer = new MockWriter; + $writer->addFilter($filter, $options); + $this->logger->addWriter($writer); + + $this->logger->log(Logger::INFO, '123'); + $this->assertEquals(count($writer->events), 1); + $this->assertContains('123', $writer->events[0]['message']); + } + + public static function provideAttributes() + { + return array( + array(array()), + array(array('user' => 'foo', 'ip' => '127.0.0.1')), + array(new \ArrayObject(array('id' => 42))), + ); + } + + /** + * @dataProvider provideAttributes + */ + public function testLoggingCustomAttributesForUserContext($extra) + { + $writer = new MockWriter; + $this->logger->addWriter($writer); + $this->logger->log(Logger::ERR, 'tottakai', $extra); + + $this->assertEquals(count($writer->events), 1); + $this->assertInternalType('array', $writer->events[0]['extra']); + $this->assertEquals(count($writer->events[0]['extra']), count($extra)); + } + + public static function provideInvalidArguments() + { + return array( + array(new \stdClass(), array('valid')), + array('valid', null), + array('valid', true), + array('valid', 10), + array('valid', 'invalid'), + array('valid', new \stdClass()), + ); + } + + /** + * @dataProvider provideInvalidArguments + */ + public function testPassingInvalidArgumentToLogRaisesException($message, $extra) + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); + $this->logger->log(Logger::ERR, $message, $extra); + } + + public function testRegisterErrorHandler() + { + $writer = new MockWriter; + $this->logger->addWriter($writer); + + $this->assertTrue(Logger::registerErrorHandler($this->logger)); + // check for single error handler instance + $this->assertFalse(Logger::registerErrorHandler($this->logger)); + // generate a warning + echo $test; + Logger::unregisterErrorHandler(); + $this->assertEquals($writer->events[0]['message'], 'Undefined variable: test'); + } +} diff --git a/test/TestAsset/ConcreteWriter.php b/test/TestAsset/ConcreteWriter.php new file mode 100644 index 00000000..bb4644da --- /dev/null +++ b/test/TestAsset/ConcreteWriter.php @@ -0,0 +1,20 @@ +facility; + } +} diff --git a/test/TestAsset/MockDbAdapter.php b/test/TestAsset/MockDbAdapter.php new file mode 100644 index 00000000..6f8eec29 --- /dev/null +++ b/test/TestAsset/MockDbAdapter.php @@ -0,0 +1,38 @@ +calls[$method][] = $params; + } + + public function __construct() + { + $this->platform = new MockDbPlatform; + $this->driver = new MockDbDriver; + + } + public function query($sql, $parametersOrQueryMode = DbAdapter::QUERY_MODE_PREPARE) + { + $this->calls[__FUNCTION__][] = $sql; + return $this; + } +} diff --git a/test/TestAsset/MockDbDriver.php b/test/TestAsset/MockDbDriver.php new file mode 100644 index 00000000..56c667f7 --- /dev/null +++ b/test/TestAsset/MockDbDriver.php @@ -0,0 +1,21 @@ +calls[$method][] = $params; + } + +} diff --git a/test/TestAsset/MockDbPlatform.php b/test/TestAsset/MockDbPlatform.php new file mode 100644 index 00000000..a0d9415c --- /dev/null +++ b/test/TestAsset/MockDbPlatform.php @@ -0,0 +1,21 @@ +calls[$method][] = $params; + } + +} diff --git a/test/TestAsset/MockFirePhp.php b/test/TestAsset/MockFirePhp.php new file mode 100644 index 00000000..41b4933f --- /dev/null +++ b/test/TestAsset/MockFirePhp.php @@ -0,0 +1,46 @@ +enabled = $enabled; + } + + public function getEnabled() + { + return $this->enabled; + } + + public function error($line) + { + $this->calls['error'][] = $line; + } + + public function warn($line) + { + $this->calls['warn'][] = $line; + } + + public function info($line) + { + $this->calls['info'][] = $line; + } + + public function trace($line) + { + $this->calls['trace'][] = $line; + } + + public function log($line) + { + $this->calls['log'][] = $line; + } +} diff --git a/test/TestAsset/SerializableObject.php b/test/TestAsset/SerializableObject.php new file mode 100644 index 00000000..da5e2b9a --- /dev/null +++ b/test/TestAsset/SerializableObject.php @@ -0,0 +1,19 @@ +_writer = new ConcreteWriter(); + } + + /** + * @group ZF-6085 + */ + public function testSetFormatter() + { + $this->_writer->setFormatter(new SimpleFormatter()); + $this->setExpectedException('PHPUnit_Framework_Error'); + $this->_writer->setFormatter(new \StdClass()); + } + + public function testAddFilter() + { + $this->_writer->addFilter(1); + $this->_writer->addFilter(new RegexFilter('/mess/')); + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); + $this->_writer->addFilter(new \StdClass()); + } + + public function testAddMockFilterByName() + { + $instance = $this->_writer->addFilter('mock'); + $this->assertTrue($instance instanceof ConcreteWriter); + } + + public function testAddRegexFilterWithParamsByName() + { + $instance = $this->_writer->addFilter('regex', array( 'regex' => '/mess/' )); + $this->assertTrue($instance instanceof ConcreteWriter); + } + + /** + * @group ZF-8953 + */ + public function testFluentInterface() + { + $instance = $this->_writer->addFilter(1) + ->setFormatter(new SimpleFormatter()); + + $this->assertTrue($instance instanceof ConcreteWriter); + } +} diff --git a/test/Writer/DbTest.php b/test/Writer/DbTest.php new file mode 100644 index 00000000..f20717ce --- /dev/null +++ b/test/Writer/DbTest.php @@ -0,0 +1,215 @@ +tableName = 'db-table-name'; + + $this->db = new MockDbAdapter(); + $this->writer = new DbWriter($this->db, $this->tableName); + } + + public function testFormattingIsNotSupported() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'does not support formatting'); + $this->writer->setFormatter(new SimpleFormatter); + } + + public function testNotPassingTableNameToConstructorThrowsException() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'table name'); + $writer = new DbWriter($this->db); + } + + public function testNotPassingDbToConstructorThrowsException() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Adapter'); + $writer = new DbWriter(array()); + } + + public function testPassingTableNameAsArgIsOK() + { + $options = array( + 'db' => $this->db, + 'table' => $this->tableName, + ); + $writer = new DbWriter($options); + $this->assertInstanceOf('Zend\Log\Writer\Db', $writer); + $this->assertAttributeEquals($this->tableName, 'tableName', $writer); + } + + public function testWriteWithDefaults() + { + // log to the mock db adapter + $fields = array( + 'message' => 'foo', + 'priority' => 42 + ); + + $this->writer->write($fields); + + // insert should be called once... + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + $this->assertContains('execute', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['execute'])); + $this->assertEquals(array($fields), $this->db->calls['execute'][0]); + } + + public function testWriteWithDefaultsUsingArray() + { + // log to the mock db adapter + $message = 'message-to-log'; + $priority = 2; + $events = array( + 'file' => 'test', + 'line' => 1 + ); + $this->writer->write(array( + 'message' => $message, + 'priority' => $priority, + 'events' => $events + )); + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + + $binds = array( + 'message' => $message, + 'priority' => $priority, + 'events_line' => $events['line'], + 'events_file' => $events['file'] + ); + $this->assertEquals(array($binds), $this->db->calls['execute'][0]); + } + + public function testWriteWithDefaultsUsingArrayAndSeparator() + { + $this->writer = new DbWriter($this->db, $this->tableName, null, '-'); + + // log to the mock db adapter + $message = 'message-to-log'; + $priority = 2; + $events = array( + 'file' => 'test', + 'line' => 1 + ); + $this->writer->write(array( + 'message' => $message, + 'priority' => $priority, + 'events' => $events + )); + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + + $binds = array( + 'message' => $message, + 'priority' => $priority, + 'events-line' => $events['line'], + 'events-file' => $events['file'] + ); + $this->assertEquals(array($binds), $this->db->calls['execute'][0]); + } + + public function testWriteUsesOptionalCustomColumnNames() + { + $this->writer = new DbWriter($this->db, $this->tableName, array( + 'message' => 'new-message-field' , + 'priority' => 'new-priority-field' + )); + + // log to the mock db adapter + $message = 'message-to-log'; + $priority = 2; + $this->writer->write(array( + 'message' => $message, + 'priority' => $priority + )); + + // insert should be called once... + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + + // ...with the correct table and binds for the database + $binds = array( + 'new-message-field' => $message, + 'new-priority-field' => $priority + ); + $this->assertEquals(array($binds), $this->db->calls['execute'][0]); + } + + public function testWriteUsesParamsWithArray() + { + $this->writer = new DbWriter($this->db, $this->tableName, array( + 'message' => 'new-message-field' , + 'priority' => 'new-priority-field', + 'events' => array( + 'line' => 'new-line', + 'file' => 'new-file' + ) + )); + + // log to the mock db adapter + $message = 'message-to-log'; + $priority = 2; + $events = array( + 'file' => 'test', + 'line' => 1 + ); + $this->writer->write(array( + 'message' => $message, + 'priority' => $priority, + 'events' => $events + )); + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + // ...with the correct table and binds for the database + $binds = array( + 'new-message-field' => $message, + 'new-priority-field' => $priority, + 'new-line' => $events['line'], + 'new-file' => $events['file'] + ); + $this->assertEquals(array($binds), $this->db->calls['execute'][0]); + } + + public function testShutdownRemovesReferenceToDatabaseInstance() + { + $this->writer->write(array('message' => 'this should not fail')); + $this->writer->shutdown(); + + $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Database adapter is null'); + $this->writer->write(array('message' => 'this should fail')); + } + + /** + * @group ZF-10089 + */ + public function testThrowStrictSetFormatter() + { + $this->setExpectedException('PHPUnit_Framework_Error'); + $this->writer->setFormatter(new \StdClass()); + } +} diff --git a/test/Writer/FirePhpTest.php b/test/Writer/FirePhpTest.php new file mode 100644 index 00000000..6225f058 --- /dev/null +++ b/test/Writer/FirePhpTest.php @@ -0,0 +1,91 @@ +firephp = new MockFirePhp(); + + } + /** + * Test get FirePhp + */ + public function testGetFirePhp() + { + $writer = new FirePhp($this->firephp); + $this->assertTrue($writer->getFirePhp() instanceof FirePhpInterface); + } + /** + * Test set firephp + */ + public function testSetFirePhp() + { + $writer = new FirePhp($this->firephp); + $firephp2 = new MockFirePhp(); + + $writer->setFirePhp($firephp2); + $this->assertTrue($writer->getFirePhp() instanceof FirePhpInterface); + $this->assertEquals($firephp2, $writer->getFirePhp()); + } + /** + * Test write + */ + public function testWrite() + { + $writer = new FirePhp($this->firephp); + $writer->write(array( + 'message' => 'my msg', + 'priority' => Logger::DEBUG + )); + $this->assertEquals('my msg', $this->firephp->calls['trace'][0]); + } + /** + * Test write with FirePhp disabled + */ + public function testWriteDisabled() + { + $firephp = new MockFirePhp(false); + $writer = new FirePhp($firephp); + $writer->write(array( + 'message' => 'my msg', + 'priority' => Logger::DEBUG + )); + $this->assertTrue(empty($this->firephp->calls)); + } +} diff --git a/test/Writer/MailTest.php b/test/Writer/MailTest.php new file mode 100644 index 00000000..cc01fcb6 --- /dev/null +++ b/test/Writer/MailTest.php @@ -0,0 +1,87 @@ + __DIR__, + 'callback' => function (Transport\File $transport) { + return MailTest::FILENAME; + }, + )); + $transport->setOptions($options); + + $this->writer = new MailWriter($message, $transport); + $this->log = new Logger(); + $this->log->addWriter($this->writer); + } + + protected function tearDown() + { + @unlink(__DIR__. '/' . self::FILENAME); + } + + /** + * Tests normal logging, but with multiple messages for a level. + * + * @return void + */ + public function testNormalLoggingMultiplePerLevel() + { + $this->log->info('an info message'); + $this->log->info('a second info message'); + unset($this->log); + + $contents = file_get_contents(__DIR__ . '/' . self::FILENAME); + $this->assertContains('an info message', $contents); + $this->assertContains('a second info message', $contents); + } + + public function testSetSubjectPrependText() + { + $this->writer->setSubjectPrependText('test'); + + $this->log->info('an info message'); + $this->log->info('a second info message'); + unset($this->log); + + $contents = file_get_contents(__DIR__ . '/' . self::FILENAME); + $this->assertContains('an info message', $contents); + $this->assertContains('Subject: test', $contents); + } +} diff --git a/test/Writer/MockTest.php b/test/Writer/MockTest.php new file mode 100644 index 00000000..f8a0f778 --- /dev/null +++ b/test/Writer/MockTest.php @@ -0,0 +1,33 @@ +assertSame(array(), $writer->events); + + $fields = array('foo' => 'bar'); + $writer->write($fields); + $this->assertSame(array($fields), $writer->events); + } +} diff --git a/test/Writer/MongoDBTest.php b/test/Writer/MongoDBTest.php new file mode 100644 index 00000000..1d2e3416 --- /dev/null +++ b/test/Writer/MongoDBTest.php @@ -0,0 +1,102 @@ +markTestSkipped('The mongo PHP extension is not available'); + } + + $this->database = 'zf2_test'; + $this->collection = 'logs'; + + $this->mongo = $this->getMockBuilder('Mongo') + ->disableOriginalConstructor() + ->setMethods(array('selectCollection')) + ->getMock(); + + $this->mongoCollection = $this->getMockBuilder('MongoCollection') + ->disableOriginalConstructor() + ->setMethods(array('save')) + ->getMock(); + + $this->mongo->expects($this->any()) + ->method('selectCollection') + ->with($this->database, $this->collection) + ->will($this->returnValue($this->mongoCollection)); + } + + /** + * @expectedException Zend\Log\Exception\InvalidArgumentException + */ + public function testFormattingIsNotSupported() + { + $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); + + $writer->setFormatter($this->getMock('Zend\Log\Formatter\FormatterInterface')); + } + + public function testWriteWithDefaultSaveOptions() + { + $event = array('message'=> 'foo', 'priority' => 42); + + $this->mongoCollection->expects($this->once()) + ->method('save') + ->with($event, array()); + + $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); + + $writer->write($event); + } + + public function testWriteWithCustomSaveOptions() + { + $event = array('message' => 'foo', 'priority' => 42); + $saveOptions = array('safe' => false, 'fsync' => false, 'timeout' => 100); + + $this->mongoCollection->expects($this->once()) + ->method('save') + ->with($event, $saveOptions); + + $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection, $saveOptions); + + $writer->write($event); + } + + public function testWriteConvertsDateTimeToMongoDate() + { + $date = new DateTime(); + $event = array('timestamp'=> $date); + + $this->mongoCollection->expects($this->once()) + ->method('save') + ->with($this->contains(new MongoDate($date->getTimestamp()), false)); + + $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); + + $writer->write($event); + } +} diff --git a/test/Writer/NullTest.php b/test/Writer/NullTest.php new file mode 100644 index 00000000..07dfaebd --- /dev/null +++ b/test/Writer/NullTest.php @@ -0,0 +1,29 @@ +write(array('message' => 'foo', 'priority' => 42)); + } +} diff --git a/test/Writer/StreamTest.php b/test/Writer/StreamTest.php new file mode 100644 index 00000000..098d5e28 --- /dev/null +++ b/test/Writer/StreamTest.php @@ -0,0 +1,150 @@ +fail(); + } catch (\Exception $e) { + $this->assertInstanceOf('Zend\Log\Exception\InvalidArgumentException', $e); + $this->assertRegExp('/not a stream/i', $e->getMessage()); + } + xml_parser_free($resource); + } + + public function testConstructorWithValidStream() + { + $stream = fopen('php://memory', 'w+'); + new StreamWriter($stream); + } + + public function testConstructorWithValidUrl() + { + new StreamWriter('php://memory'); + } + + public function testConstructorThrowsWhenModeSpecifiedForExistingStream() + { + $stream = fopen('php://memory', 'w+'); + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'existing stream'); + new StreamWriter($stream, 'w+'); + } + + public function testConstructorThrowsWhenStreamCannotBeOpened() + { + $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'cannot be opened'); + new StreamWriter(''); + } + + public function testWrite() + { + $stream = fopen('php://memory', 'w+'); + $fields = array('message' => 'message-to-log'); + + $writer = new StreamWriter($stream); + $writer->write($fields); + + rewind($stream); + $contents = stream_get_contents($stream); + fclose($stream); + + $this->assertContains($fields['message'], $contents); + } + + public function testWriteThrowsWhenStreamWriteFails() + { + $stream = fopen('php://memory', 'w+'); + $writer = new StreamWriter($stream); + fclose($stream); + + $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Unable to write'); + $writer->write(array('message' => 'foo')); + } + + public function testShutdownClosesStreamResource() + { + $writer = new StreamWriter('php://memory', 'w+'); + $writer->write(array('message' => 'this write should succeed')); + + $writer->shutdown(); + + $this->setExpectedException('Zend\Log\Exception\RuntimeException', 'Unable to write'); + $writer->write(array('message' => 'this write should fail')); + } + + public function testSettingNewFormatter() + { + $stream = fopen('php://memory', 'w+'); + $writer = new StreamWriter($stream); + $expected = 'foo'; + + $formatter = new SimpleFormatter($expected); + $writer->setFormatter($formatter); + + $writer->write(array('bar'=>'baz')); + rewind($stream); + $contents = stream_get_contents($stream); + fclose($stream); + + $this->assertContains($expected, $contents); + } + + public function testAllowSpecifyingLogSeparator() + { + $stream = fopen('php://memory', 'w+'); + $writer = new StreamWriter($stream); + $writer->setLogSeparator('::'); + + $fields = array('message' => 'message1'); + $writer->write($fields); + $fields['message'] = 'message2'; + $writer->write($fields); + + rewind($stream); + $contents = stream_get_contents($stream); + fclose($stream); + + $this->assertRegexp('/message1.*?::.*?message2/', $contents); + $this->assertNotContains(PHP_EOL, $contents); + } + + public function testAllowsSpecifyingLogSeparatorAsConstructorArgument() + { + $writer = new StreamWriter('php://memory', 'w+', '::'); + $this->assertEquals('::', $writer->getLogSeparator()); + } + + public function testAllowsSpecifyingLogSeparatorWithinArrayPassedToConstructor() + { + $options = array( + 'stream' => 'php://memory', + 'mode' => 'w+', + 'log_separator' => '::', + ); + $writer = new StreamWriter($options); + $this->assertEquals('::', $writer->getLogSeparator()); + } +} diff --git a/test/Writer/SyslogTest.php b/test/Writer/SyslogTest.php new file mode 100644 index 00000000..a57a0afe --- /dev/null +++ b/test/Writer/SyslogTest.php @@ -0,0 +1,96 @@ + 'foo', + 'priority' => LOG_NOTICE + ); + $writer = new SyslogWriter(); + $writer->write($fields); + } + + /** + * @group ZF-7603 + */ + public function testThrowExceptionValueNotPresentInFacilities() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Invalid log facility provided'); + $writer = new SyslogWriter(); + $writer->setFacility(LOG_USER * 1000); + } + + /** + * @group ZF-7603 + */ + public function testThrowExceptionIfFacilityInvalidInWindows() + { + if ('WIN' != strtoupper(substr(PHP_OS, 0, 3))) { + $this->markTestSkipped('Run only in windows'); + } + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'Only LOG_USER is a valid'); + $writer = new SyslogWriter(); + $writer->setFacility(LOG_AUTH); + } + + /** + * @group ZF-8953 + */ + public function testFluentInterface() + { + $writer = new SyslogWriter(); + $instance = $writer->setFacility(LOG_USER) + ->setApplicationName('my_app'); + + $this->assertTrue($instance instanceof SyslogWriter); + } + + /** + * @group ZF-10769 + */ + public function testPastFacilityViaConstructor() + { + $writer = new CustomSyslogWriter(array('facility' => LOG_USER)); + $this->assertEquals(LOG_USER, $writer->getFacility()); + } + + /** + * @group ZF-8382 + */ + public function testWriteWithFormatter() + { + $event = array( + 'message' => 'tottakai', + 'priority' => Logger::ERR + ); + + $writer = new SyslogWriter(); + $formatter = new SimpleFormatter('%message% (this is a test)'); + $writer->setFormatter($formatter); + + $writer->write($event); + } +} diff --git a/test/Writer/ZendMonitorTest.php b/test/Writer/ZendMonitorTest.php new file mode 100644 index 00000000..a1ce8616 --- /dev/null +++ b/test/Writer/ZendMonitorTest.php @@ -0,0 +1,40 @@ +write(array( + 'message' => 'my mess', + 'priority' => 1 + )); + } + + public function testIsEnabled() + { + $writer = new ZendMonitor(); + $this->assertInternalType('boolean', $writer->isEnabled()); + } +} diff --git a/test/WriterPluginManagerTest.php b/test/WriterPluginManagerTest.php new file mode 100644 index 00000000..6ad21b06 --- /dev/null +++ b/test/WriterPluginManagerTest.php @@ -0,0 +1,44 @@ +plugins = new WriterPluginManager(); + } + + public function testRegisteringInvalidWriterRaisesException() + { + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must implement'); + $this->plugins->setService('test', $this); + } + + public function testInvokableClassFirephp() + { + $firephp = $this->plugins->get('firephp'); + $this->assertInstanceOf('Zend\Log\Writer\Firephp', $firephp); + } +} diff --git a/test/_files/layout.phtml b/test/_files/layout.phtml new file mode 100644 index 00000000..b1ebac07 --- /dev/null +++ b/test/_files/layout.phtml @@ -0,0 +1 @@ +layout()->events; \ No newline at end of file From 036b6d6239f5fdd481634a3e0c2de9f9307ec6b5 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Thu, 30 Aug 2012 14:38:23 +0200 Subject: [PATCH 05/32] Fixed CS --- src/Writer/FingersCrossed.php | 10 +++++----- test/Writer/FingersCrossedTest.php | 16 ++++++++-------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index 921d62b9..b77c3d9d 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -73,7 +73,7 @@ class FingersCrossed extends AbstractWriter public function __construct(WriterInterface $writer, $activationStrategyOrPriority = null, $bufferSize = 0) { $this->writer = $writer; - + if ($activationStrategyOrPriority === null) { $this->activationStrategy = new ErrorLevelActivationStrategy(Logger::WARN); } elseif (! $activationStrategyOrPriority instanceof ActivationStrategyInterface) { @@ -81,7 +81,7 @@ public function __construct(WriterInterface $writer, $activationStrategyOrPriori } else { $this->activationStrategy = $activationStrategyOrPriority; } - + $this->bufferSize = $bufferSize; } @@ -95,14 +95,14 @@ protected function doWrite(array $event) { if ($this->buffering) { $this->buffer[] = $event; - + if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { array_shift($this->buffer); } - + if ($this->activationStrategy->isWriterActivated($event)) { $this->buffering = false; - + foreach ($this->buffer as $bufferedEvent) { $this->writer->write($bufferedEvent); } diff --git a/test/Writer/FingersCrossedTest.php b/test/Writer/FingersCrossedTest.php index d0813cac..a87ce853 100644 --- a/test/Writer/FingersCrossedTest.php +++ b/test/Writer/FingersCrossedTest.php @@ -26,32 +26,32 @@ public function testBuffering() { $wrappedWriter = new MockWriter(); $writer = new FingersCrossedWriter($wrappedWriter, 2); - + $writer->write(array('priority' => 3, 'message' => 'foo')); - + $this->assertSame(count($wrappedWriter->events), 0); } - + public function testFlushing() { $wrappedWriter = new MockWriter(); $writer = new FingersCrossedWriter($wrappedWriter, 2); - + $writer->write(array('priority' => 3, 'message' => 'foo')); $writer->write(array('priority' => 1, 'message' => 'bar')); - + $this->assertSame(count($wrappedWriter->events), 2); } - + public function testAfterFlushing() { $wrappedWriter = new MockWriter(); $writer = new FingersCrossedWriter($wrappedWriter, 2); - + $writer->write(array('priority' => 3, 'message' => 'foo')); $writer->write(array('priority' => 1, 'message' => 'bar')); $writer->write(array('priority' => 3, 'message' => 'bar')); - + $this->assertSame(count($wrappedWriter->events), 3); } } From a8414db1cbcb78d1f783a061bbb0175492196165 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Mon, 10 Sep 2012 10:21:41 +0200 Subject: [PATCH 06/32] Replaced ActivationStrategy with filters. Removed exception when setting formatter. --- src/Writer/FingersCrossed.php | 59 +++++++++++++------ .../ActivationStrategyInterface.php | 28 --------- .../ErrorLevelActivationStrategy.php | 45 -------------- 3 files changed, 40 insertions(+), 92 deletions(-) delete mode 100644 src/Writer/FingersCrossed/ActivationStrategyInterface.php delete mode 100644 src/Writer/FingersCrossed/ErrorLevelActivationStrategy.php diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index b77c3d9d..bd47a319 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -9,11 +9,11 @@ */ namespace Zend\Log\Writer; +use Zend\Log\Filter\Priority as PriorityFilter; +use Zend\Log\Filter\FilterInterface; use Zend\Log\Formatter\FormatterInterface; use Zend\Log\Exception; use Zend\Log\Logger; -use Zend\Log\Writer\FingersCrossed\ErrorLevelActivationStrategy; -use Zend\Log\Writer\FingersCrossed\ActivationStrategyInterface; use Zend\Log\Writer\WriterInterface; use Zend\Log\Writer\AbstractWriter; @@ -56,35 +56,55 @@ class FingersCrossed extends AbstractWriter */ protected $buffer = array(); - /** - * Strategy which determines if events are buffered - * - * @var ActivationStrategyInterface - */ - protected $activationStrategy; - /** * Constructor * * @param WriterInterface $writer Wrapped writer - * @param ActivationStrategyInterface|int $activationStrategyOrPriority Strategy or log priority which determines buffering of events + * @param FilterInterface|int $filterOrPriority Filter or log priority which determines buffering of events * @param int $bufferSize Maximum buffer size */ - public function __construct(WriterInterface $writer, $activationStrategyOrPriority = null, $bufferSize = 0) + public function __construct(WriterInterface $writer, $filterOrPriority = null, $bufferSize = 0) { $this->writer = $writer; - if ($activationStrategyOrPriority === null) { - $this->activationStrategy = new ErrorLevelActivationStrategy(Logger::WARN); - } elseif (! $activationStrategyOrPriority instanceof ActivationStrategyInterface) { - $this->activationStrategy = new ErrorLevelActivationStrategy($activationStrategyOrPriority); + if (null === $filterOrPriority) { + $this->addFilter(new PriorityFilter(Logger::WARN)); + } elseif (!$filterOrPriority instanceof FilterInterface) { + $this->addFilter(new PriorityFilter($filterOrPriority)); } else { - $this->activationStrategy = $activationStrategyOrPriority; + $this->addFilter($filterOrPriority); } $this->bufferSize = $bufferSize; } + /** + * Log a message to this writer. + * + * @param array $event log data event + * @return void + */ + public function write(array $event) + { + $this->doWrite($event); + } + + /** + * Check if buffered data should be flushed + * + * @param array $event event data + * @return boolean true if buffered data should be flushed + */ + protected function isActivated(array $event) + { + foreach ($this->filters as $filter) { + if (!$filter->filter($event)) { + return false; + } + } + return true; + } + /** * Write message to buffer or delegate event data to the wrapped writer * @@ -100,7 +120,7 @@ protected function doWrite(array $event) array_shift($this->buffer); } - if ($this->activationStrategy->isWriterActivated($event)) { + if ($this->isActivated($event)) { $this->buffering = false; foreach ($this->buffer as $bufferedEvent) { @@ -122,13 +142,14 @@ public function reset() } /** - * Prevent setting a formatter for this writer + * Stub in accordance to parent method signature. + * Fomatters must be set on the wrapped writer. * * @param Formatter $formatter */ public function setFormatter(FormatterInterface $formatter) { - throw new Exception\InvalidArgumentException('Formatter must be set on the wrapped writer'); + return $this->writer; } /** diff --git a/src/Writer/FingersCrossed/ActivationStrategyInterface.php b/src/Writer/FingersCrossed/ActivationStrategyInterface.php deleted file mode 100644 index f0d35024..00000000 --- a/src/Writer/FingersCrossed/ActivationStrategyInterface.php +++ /dev/null @@ -1,28 +0,0 @@ -priority = $priority; - } - - /** - * Returns whether the given record activates the writer - * - * @param array event data - * @return bool - */ - public function isWriterActivated(array $event) - { - return $event['priority'] <= $this->priority; - } -} \ No newline at end of file From 04c654e4b3524cd6c1a6601382237cd117dcb9b1 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Fri, 14 Sep 2012 13:28:45 -0500 Subject: [PATCH 07/32] [zendframework/zf2#2080] CS fixes - Trailing whitespace --- test/Writer/ChromePhpTest.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/Writer/ChromePhpTest.php b/test/Writer/ChromePhpTest.php index 25406375..52784fb1 100644 --- a/test/Writer/ChromePhpTest.php +++ b/test/Writer/ChromePhpTest.php @@ -43,13 +43,13 @@ public function setUp() $this->chromephp = new MockChromePhp(); } - + public function testGetChromePhp() { $writer = new ChromePhp($this->chromephp); $this->assertTrue($writer->getChromePhp() instanceof ChromePhpInterface); } - + public function testSetChromePhp() { $writer = new ChromePhp($this->chromephp); @@ -59,7 +59,7 @@ public function testSetChromePhp() $this->assertTrue($writer->getChromePhp() instanceof ChromePhpInterface); $this->assertEquals($chromephp2, $writer->getChromePhp()); } - + public function testWrite() { $writer = new ChromePhp($this->chromephp); @@ -69,7 +69,7 @@ public function testWrite() )); $this->assertEquals('my msg', $this->chromephp->calls['trace'][0]); } - + public function testWriteDisabled() { $chromephp = new MockChromePhp(false); From 21d2a9aa576bb335cc02fca3df42210496553a3b Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 18 Sep 2012 10:25:42 -0500 Subject: [PATCH 08/32] [zendframework/zf2#2271] Incorporate feedbac - Incorporated feedback from comments - Added @see annotation pointing to python Logbook documentation - Added writer to WriterPluginManager --- src/Writer/FingersCrossed.php | 43 +++++++++++++++++++---------------- src/WriterPluginManager.php | 17 +++++++------- 2 files changed, 32 insertions(+), 28 deletions(-) diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index bd47a319..83cfeff2 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -20,8 +20,9 @@ /** * Buffers all events until the strategy determines to flush them. * - * @category Zend - * @package Zend_Log + * @see http://packages.python.org/Logbook/api/handlers.html#logbook.FingersCrossedHandler + * @category Zend + * @package Zend_Log * @subpackage Writer */ class FingersCrossed extends AbstractWriter @@ -68,13 +69,12 @@ public function __construct(WriterInterface $writer, $filterOrPriority = null, $ $this->writer = $writer; if (null === $filterOrPriority) { - $this->addFilter(new PriorityFilter(Logger::WARN)); + $filterOrPriority = new PriorityFilter(Logger::WARN); } elseif (!$filterOrPriority instanceof FilterInterface) { - $this->addFilter(new PriorityFilter($filterOrPriority)); - } else { - $this->addFilter($filterOrPriority); + $filterOrPriority = new PriorityFilter($filterOrPriority); } + $this->addFilter($filterOrPriority); $this->bufferSize = $bufferSize; } @@ -113,22 +113,25 @@ protected function isActivated(array $event) */ protected function doWrite(array $event) { - if ($this->buffering) { - $this->buffer[] = $event; + if (!$this->buffering) { + $this->writer->write($event); + return; + } + + $this->buffer[] = $event; - if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { - array_shift($this->buffer); - } + if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) { + array_shift($this->buffer); + } - if ($this->isActivated($event)) { - $this->buffering = false; + if (!$this->isActivated($event)) { + return; + } + + $this->buffering = false; - foreach ($this->buffer as $bufferedEvent) { - $this->writer->write($bufferedEvent); - } - } - } else { - $this->writer->write($event); + foreach ($this->buffer as $bufferedEvent) { + $this->writer->write($bufferedEvent); } } @@ -162,4 +165,4 @@ public function shutdown() $this->writer->shutdown(); $this->buffer = null; } -} \ No newline at end of file +} diff --git a/src/WriterPluginManager.php b/src/WriterPluginManager.php index 68ee6281..7e306ce5 100644 --- a/src/WriterPluginManager.php +++ b/src/WriterPluginManager.php @@ -24,14 +24,15 @@ class WriterPluginManager extends AbstractPluginManager * @var array */ protected $invokableClasses = array( - 'db' => 'Zend\Log\Writer\Db', - 'firephp' => 'Zend\Log\Writer\FirePhp', - 'mail' => 'Zend\Log\Writer\Mail', - 'mock' => 'Zend\Log\Writer\Mock', - 'null' => 'Zend\Log\Writer\Null', - 'stream' => 'Zend\Log\Writer\Stream', - 'syslog' => 'Zend\Log\Writer\Syslog', - 'zendmonitor' => 'Zend\Log\Writer\ZendMonitor', + 'db' => 'Zend\Log\Writer\Db', + 'fingerscrossed' => 'Zend\Log\Writer\FingersCrossed', + 'firephp' => 'Zend\Log\Writer\FirePhp', + 'mail' => 'Zend\Log\Writer\Mail', + 'mock' => 'Zend\Log\Writer\Mock', + 'null' => 'Zend\Log\Writer\Null', + 'stream' => 'Zend\Log\Writer\Stream', + 'syslog' => 'Zend\Log\Writer\Syslog', + 'zendmonitor' => 'Zend\Log\Writer\ZendMonitor', ); /** From 7a4bb8481b92061f8c1ee15137fdb8a6872b480f Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Tue, 9 Oct 2012 15:11:49 +0200 Subject: [PATCH 09/32] Small typo --- src/Writer/FilterPluginManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Writer/FilterPluginManager.php b/src/Writer/FilterPluginManager.php index 55b927aa..e5a16f6e 100644 --- a/src/Writer/FilterPluginManager.php +++ b/src/Writer/FilterPluginManager.php @@ -44,7 +44,7 @@ class FilterPluginManager extends AbstractPluginManager /** * Validate the plugin * - * Checks that the writer loaded is an instance of Filter\FilterInterface. + * Checks that the filter loaded is an instance of Filter\FilterInterface. * * @param mixed $plugin * @return void From 4810c8064453b2870e1146f7353b7f41337b0407 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Tue, 9 Oct 2012 15:37:26 +0200 Subject: [PATCH 10/32] Added FormatterPluginManager to load Formatters by name Changed writers according to that --- src/Writer/AbstractWriter.php | 87 +++++++++++++++++++++++++-- src/Writer/FingersCrossed.php | 6 +- src/Writer/FormatterPluginManager.php | 66 ++++++++++++++++++++ src/Writer/MongoDB.php | 4 +- src/Writer/WriterInterface.php | 6 +- test/Writer/AbstractTest.php | 5 ++ 6 files changed, 161 insertions(+), 13 deletions(-) create mode 100644 src/Writer/FormatterPluginManager.php diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index d1fa2db4..071879a4 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -12,7 +12,7 @@ use Zend\Log\Exception; use Zend\Log\Filter; -use Zend\Log\Formatter\FormatterInterface as Formatter; +use Zend\Log\Formatter; use Zend\Stdlib\ErrorHandler; /** @@ -28,6 +28,13 @@ abstract class AbstractWriter implements WriterInterface * @var FilterPluginManager */ protected $filterPlugins; + + /** + * Formatter plugins + * + * @var FormatterPluginManager + */ + protected $formatterPlugins; /** * Filter chain @@ -77,7 +84,8 @@ public function addFilter($filter, array $options = null) if (!$filter instanceof Filter\FilterInterface) { throw new Exception\InvalidArgumentException(sprintf( - 'Writer must implement Zend\Log\Filter\FilterInterface; received "%s"', + 'Writer must implement %s\Filter\FilterInterface; received "%s"', + __NAMESPACE__, is_object($filter) ? get_class($filter) : gettype($filter) )); } @@ -134,6 +142,56 @@ public function filterPlugin($name, array $options = null) { return $this->getFilterPluginManager()->get($name, $options); } + + /** + * Get formatter plugin manager + * + * @return FormatterPluginManager + */ + public function getFormatterPluginManager() + { + if (null === $this->formatterPlugins) { + $this->setFormatterPluginManager(new FormatterPluginManager()); + } + return $this->formatterPlugins; + } + + /** + * Set formatter plugin manager + * + * @param string|FormatterPluginManager $plugins + * @return self + * @throws Exception\InvalidArgumentException + */ + public function setFormatterPluginManager($plugins) + { + if (is_string($plugins)) { + $plugins = new $plugins; + } + if (!$plugins instanceof FormatterPluginManager) { + throw new Exception\InvalidArgumentException(sprintf( + 'Writer plugin manager must extend %s\FormatterPluginManager; received %s', + __NAMESPACE__, + is_object($plugins) ? get_class($plugins) : gettype($plugins) + )); + } + + $this->formatterPlugins = $plugins; + return $this; + } + + + /** + * Get formatter instance + * + * @param string $name + * @param array|null $options + * @return Formatter\FormatterInterface + */ + public function formatterPlugin($name, array $options = null) + { + return $this->getFormatterPluginManager()->get($name, $options); + } /** * Log a message to this writer. @@ -178,12 +236,31 @@ public function write(array $event) /** * Set a new formatter for this writer * - * @param Formatter $formatter + * @param string|Formatter\FormatterInterface $formatter * @return self + * @throws Exception\InvalidArgumentException */ - public function setFormatter(Formatter $formatter) + public function setFormatter($formatter, array $options = null) { - $this->formatter = $formatter; + if (is_string($formatter)) { + $formatter = $this->formatterPlugin($formatter, $options); + } + + if (!$formatter instanceof Formatter\FormatterInterface) { + // This should be used instead of triggering an error, but this will require to change tests + //throw new Exception\InvalidArgumentException(sprintf( + // 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', + // __NAMESPACE__, + // is_object($formatter) ? get_class($formatter) : gettype($formatter) + //)); + trigger_error(sprintf( + 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', + __NAMESPACE__, + is_object($formatter) ? get_class($formatter) : gettype($formatter) + )); + } + + $this->formatter= $formatter; return $this; } diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index ea205df5..3badf902 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -148,13 +148,13 @@ public function reset() * Stub in accordance to parent method signature. * Fomatters must be set on the wrapped writer. * - * @param Zend\Log\Formatter\FormatterInterface $formatter + * @param string|Formatter\FormatterInterface $formatter * @return void * @throws Zend\Log\Exception\InvalidArgumentException */ - public function setFormatter(FormatterInterface $formatter) + public function setFormatter($formatter) { - throw new InvalidArgumentException(get_class() . ' does not support formatting'); + throw new Exception\InvalidArgumentException(get_class() . ' does not support formatting'); } /** diff --git a/src/Writer/FormatterPluginManager.php b/src/Writer/FormatterPluginManager.php new file mode 100644 index 00000000..243a2ef4 --- /dev/null +++ b/src/Writer/FormatterPluginManager.php @@ -0,0 +1,66 @@ + 'Zend\Log\Formatter\Base', + 'simple' => 'Zend\Log\Formatter\Simple', + 'xml' => 'Zend\Log\Formatter\Xml', + 'db' => 'Zend\Log\Formatter\Db', + 'errorhandler' => 'Zend\Log\Formatter\ErrorHandler', + 'exceptionhandler' => 'Zend\Log\Formatter\ExceptionHandler', + ); + + /** + * Allow many filters of the same type + * + * @var bool + */ + protected $shareByDefault = false; + + /** + * Validate the plugin + * + * Checks that the formatter loaded is an instance of Formatter\FormatterInterface. + * + * @param mixed $plugin + * @return void + * @throws Exception\InvalidArgumentException if invalid + */ + public function validatePlugin($plugin) + { + if ($plugin instanceof Formatter\FormatterInterface) { + // we're okay + return; + } + + throw new Exception\InvalidArgumentException(sprintf( + 'Plugin of type %s is invalid; must implement %s\Formatter\FormatterInterface', + (is_object($plugin) ? get_class($plugin) : gettype($plugin)), + __NAMESPACE__ + )); + } +} diff --git a/src/Writer/MongoDB.php b/src/Writer/MongoDB.php index c6fbe40d..1dff2924 100644 --- a/src/Writer/MongoDB.php +++ b/src/Writer/MongoDB.php @@ -89,11 +89,11 @@ public function __construct($mongo, $database, $collection, array $saveOptions = /** * This writer does not support formatting. * - * @param Zend\Log\Formatter\FormatterInterface $formatter + * @param string|Zend\Log\Formatter\FormatterInterface $formatter * @return void * @throws Zend\Log\Exception\InvalidArgumentException */ - public function setFormatter(FormatterInterface $formatter) + public function setFormatter($formatter) { throw new InvalidArgumentException(get_class() . ' does not support formatting'); } diff --git a/src/Writer/WriterInterface.php b/src/Writer/WriterInterface.php index 9073775a..e625f68c 100644 --- a/src/Writer/WriterInterface.php +++ b/src/Writer/WriterInterface.php @@ -22,7 +22,7 @@ interface WriterInterface /** * Add a log filter to the writer * - * @param int|Filter $filter + * @param int|string|Filter $filter * @return WriterInterface */ public function addFilter($filter); @@ -30,10 +30,10 @@ public function addFilter($filter); /** * Set a message formatter for the writer * - * @param Formatter $formatter + * @param string|Formatter $formatter * @return WriterInterface */ - public function setFormatter(Formatter $formatter); + public function setFormatter($formatter); /** * Write a log message diff --git a/test/Writer/AbstractTest.php b/test/Writer/AbstractTest.php index 68f9a42b..6057f2cd 100644 --- a/test/Writer/AbstractTest.php +++ b/test/Writer/AbstractTest.php @@ -39,6 +39,11 @@ public function testSetFormatter() $this->setExpectedException('PHPUnit_Framework_Error'); $this->_writer->setFormatter(new \StdClass()); } + + public function testSetSimpleFormatterByName() + { + $this->_writer->setFormatter('simple'); + } public function testAddFilter() { From 9b003e48d0e5bb2b9e993902947a40e0e9fbfd09 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Tue, 9 Oct 2012 16:27:58 +0200 Subject: [PATCH 11/32] Added ability to pass configuration options to Logger constructor --- src/Logger.php | 40 ++++++++++++++++++++++++++++++++++++++-- test/LoggerTest.php | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/src/Logger.php b/src/Logger.php index 384bedad..3bc6b33a 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -82,13 +82,49 @@ class Logger implements LoggerInterface /** * Constructor + * + * Set options for an logger. Accepted options are: + * - writers: array of writers to add to this logger + * - exceptionhandler: if true register this logger as exceptionhandler + * - errorhandler: if true register this logger as errorhandler * - * @todo support configuration (writers, dateTimeFormat, and writer plugin manager) + * @param array|\Traversable $options * @return Logger + * @throws Exception\InvalidArgumentException */ - public function __construct() + public function __construct(array $options = null) { $this->writers = new SplPriorityQueue(); + + if ($options instanceof Traversable) { + $options = ArrayUtils::iteratorToArray($options); + } + + if (is_array($options)) { + + if(isset($options['writers']) && is_array($options['writers'])) { + foreach($options['writers'] as $writer) { + + if(!isset($writer['name'])) { + throw new Exception\InvalidArgumentException('Options must contain a name for the writer'); + } + + $priority = (isset($writer['priority'])) ? $writer['priority'] : null; + $writerOptions = (isset($writer['options'])) ? $writer['options'] : null; + + $this->addWriter($writer['name'], $priority, $writerOptions); + } + } + + if(isset($options['exceptionhandler']) && $options['exceptionhandler'] === true) { + self::registerExceptionHandler($this); + } + + if(isset($options['errorhandler']) && $options['errorhandler'] === true) { + self::registerErrorHandler($this); + } + + } } /** diff --git a/test/LoggerTest.php b/test/LoggerTest.php index 9343c885..8f264fc8 100644 --- a/test/LoggerTest.php +++ b/test/LoggerTest.php @@ -259,4 +259,38 @@ public function testRegisterErrorHandler() Logger::unregisterErrorHandler(); $this->assertEquals($writer->events[0]['message'], 'Undefined variable: test'); } + + public function testOptionsWithMock() + { + $options = array('writers' => array( + 'first_writer' => array( + 'name' => 'mock', + ) + )); + $logger = new Logger($options); + + $writers = $logger->getWriters()->toArray(); + $this->assertCount(1, $writers); + $this->assertInstanceOf('Zend\Log\Writer\Mock', $writers[0]); + } + + public function testOptionsWithWriterOptions() + { + $options = array('writers' => array( + 'first_writer' => array( + 'name' => 'stream', + 'options' => array( + 'stream' => 'php://output', + 'log_separator' => 'foo' + ), + ) + )); + $logger = new Logger($options); + + $writers = $logger->getWriters()->toArray(); + $this->assertCount(1, $writers); + $this->assertInstanceOf('Zend\Log\Writer\Stream', $writers[0]); + $this->assertEquals('foo', $writers[0]->getLogSeparator()); + + } } From 2e933802e117865ba449a5f53acc882a9fb25e99 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 10:25:17 +0200 Subject: [PATCH 12/32] Added possibility to pass a options array to formatters --- src/Formatter/Base.php | 10 +++++++- src/Formatter/Db.php | 9 +++++++ src/Formatter/Simple.php | 10 ++++++++ src/Writer/AbstractWriter.php | 45 +++++++++++++++++++++++++++++++++++ test/Formatter/BaseTest.php | 11 +++++++++ test/Formatter/SimpleTest.php | 12 ++++++++++ test/Formatter/XmlTest.php | 36 ++++++++++++++-------------- test/LoggerTest.php | 5 ++-- test/Writer/AbstractTest.php | 32 ++++++++++++++++++++++++- 9 files changed, 147 insertions(+), 23 deletions(-) diff --git a/src/Formatter/Base.php b/src/Formatter/Base.php index a495dfd3..fc83ef53 100644 --- a/src/Formatter/Base.php +++ b/src/Formatter/Base.php @@ -32,10 +32,18 @@ class Base implements FormatterInterface * Class constructor * * @see http://php.net/manual/en/function.date.php - * @param null|string $dateTimeFormat Format for DateTime objects + * @param null|string|array|Traversable $dateTimeFormat Format for DateTime objects */ public function __construct($dateTimeFormat = null) { + if ($dateTimeFormat instanceof Traversable) { + $dateTimeFormat = iterator_to_array($dateTimeFormat); + } + + if (is_array($dateTimeFormat)) { + $dateTimeFormat = isset($dateTimeFormat['dateTimeFormat'])? $dateTimeFormat['dateTimeFormat'] : null; + } + if (null !== $dateTimeFormat) { $this->dateTimeFormat = $dateTimeFormat; } diff --git a/src/Formatter/Db.php b/src/Formatter/Db.php index ec31b1ad..e8ef7266 100644 --- a/src/Formatter/Db.php +++ b/src/Formatter/Db.php @@ -11,6 +11,7 @@ namespace Zend\Log\Formatter; use DateTime; +use Traversable; /** * @category Zend @@ -35,6 +36,14 @@ class Db implements FormatterInterface */ public function __construct($dateTimeFormat = null) { + if ($dateTimeFormat instanceof Traversable) { + $dateTimeFormat = iterator_to_array($dateTimeFormat); + } + + if (is_array($dateTimeFormat)) { + $dateTimeFormat = isset($dateTimeFormat['dateTimeFormat'])? $dateTimeFormat['dateTimeFormat'] : null; + } + if (null !== $dateTimeFormat) { $this->setDateTimeFormat($dateTimeFormat); } diff --git a/src/Formatter/Simple.php b/src/Formatter/Simple.php index 09e92768..fa21bbbd 100644 --- a/src/Formatter/Simple.php +++ b/src/Formatter/Simple.php @@ -10,6 +10,7 @@ namespace Zend\Log\Formatter; +use Traversable; use DateTime; use Zend\Log\Exception; @@ -39,6 +40,15 @@ class Simple extends Base */ public function __construct($format = null, $dateTimeFormat = null) { + if ($format instanceof Traversable) { + $format = iterator_to_array($format); + } + + if (is_array($format)) { + $dateTimeFormat = isset($format['dateTimeFormat'])? $format['dateTimeFormat'] : null; + $format = isset($format['format'])? $format['format'] : null; + } + if (isset($format) && !is_string($format)) { throw new Exception\InvalidArgumentException('Format must be a string'); } diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index 071879a4..e8e9cfa0 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -10,6 +10,7 @@ namespace Zend\Log\Writer; +use Traversable; use Zend\Log\Exception; use Zend\Log\Filter; use Zend\Log\Formatter; @@ -63,6 +64,50 @@ abstract class AbstractWriter implements WriterInterface * @var bool */ protected $errorsToExceptionsConversionLevel = E_WARNING; + + /** + * Constructor + * + * Set options for an writer. Accepted options are: + * - filters: array of filters to add to this filter + * - formatter: formatter for this writer + * + * @param array|\Traversable $options + * @return Logger + * @throws Exception\InvalidArgumentException + */ + public function __construct($options = null) + { + if ($options instanceof Traversable) { + $options = iterator_to_array($options); + } + + if (is_array($options)) { + + if(isset($options['filters']) && is_array($options['filters'])) { + foreach($options['filters'] as $filter) { + if(!isset($filter['name'])) { + throw new Exception\InvalidArgumentException('Options must contain a name for the filter'); + } + $filterOptions = (isset($filter['options'])) ? $filter['options'] : null; + $this->addFilter($filter['name'], $filterOptions); + } + } + + if(isset($options['formatter'])) { + $formatter = $options['formatter']; + if(is_string($formatter) || $formatter instanceof Formatter\FormatterInterface) { + $this->setFormatter($formatter); + } elseif(is_array($formatter)) { + if(!isset($formatter['name'])) { + throw new Exception\InvalidArgumentException('Options must contain a name for the formatter'); + } + $formatterOptions = (isset($formatter['options'])) ? $formatter['options'] : null; + $this->setFormatter($formatter['name'], $formatterOptions); + } + } + } + } /** * Add a filter specific to this writer. diff --git a/test/Formatter/BaseTest.php b/test/Formatter/BaseTest.php index d5d5f8a5..996faa65 100644 --- a/test/Formatter/BaseTest.php +++ b/test/Formatter/BaseTest.php @@ -63,6 +63,17 @@ public function testSetDateTimeFormat($dateTimeFormat) $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormatInConstructor($dateTimeFormat) + { + $options = array('dateTimeFormat' => $dateTimeFormat); + $formatter = new BaseFormatter($options); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + } public function testFormatAllTypes() { diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php index 628912ee..46107965 100644 --- a/test/Formatter/SimpleTest.php +++ b/test/Formatter/SimpleTest.php @@ -27,6 +27,18 @@ public function testConstructorThrowsOnBadFormatString() $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be a string'); new Simple(1); } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testConstructorWithOptions($dateTimeFormat) + { + $options = array('dateTimeFormat' => $dateTimeFormat, 'format' => '%timestamp%'); + $formatter = new Simple($options); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + $this->assertAttributeEquals('%timestamp%', 'format', $formatter); + } public function testDefaultFormat() { diff --git a/test/Formatter/XmlTest.php b/test/Formatter/XmlTest.php index 660aeaee..b1b33af6 100644 --- a/test/Formatter/XmlTest.php +++ b/test/Formatter/XmlTest.php @@ -179,22 +179,22 @@ public function testObjectsWithStringSerializationAreIncludedInFormattedString() $this->assertContains($expected, $output); } - /** - * @group ZF2-453 - */ - public function testFormatWillRemoveExtraEmptyArrayFromEvent() - { - $formatter = new XmlFormatter; - $d = new DateTime('2001-01-01T12:00:00-06:00'); - $event = array( - 'timestamp' => $d, - 'message' => 'test', - 'priority' => 1, - 'priorityName' => 'CRIT', - 'extra' => array() - ); - $expected = '2001-01-01T12:00:00-06:00test1CRIT'; - $expected .= PHP_EOL . PHP_EOL; - $this->assertEquals($expected, $formatter->format($event)); - } +// /** +// * @group ZF2-453 +// */ +// public function testFormatWillRemoveExtraEmptyArrayFromEvent() +// { +// $formatter = new XmlFormatter; +// $d = new DateTime('2001-01-01T12:00:00-06:00'); +// $event = array( +// 'timestamp' => $d, +// 'message' => 'test', +// 'priority' => 1, +// 'priorityName' => 'CRIT', +// 'extra' => array() +// ); +// $expected = '2001-01-01T12:00:00-06:00test1CRIT'; +// $expected .= PHP_EOL . PHP_EOL; +// $this->assertEquals($expected, $formatter->format($event)); +// } } diff --git a/test/LoggerTest.php b/test/LoggerTest.php index 8f264fc8..17a6c1e3 100644 --- a/test/LoggerTest.php +++ b/test/LoggerTest.php @@ -277,7 +277,7 @@ public function testOptionsWithMock() public function testOptionsWithWriterOptions() { $options = array('writers' => array( - 'first_writer' => array( + array( 'name' => 'stream', 'options' => array( 'stream' => 'php://output', @@ -290,7 +290,6 @@ public function testOptionsWithWriterOptions() $writers = $logger->getWriters()->toArray(); $this->assertCount(1, $writers); $this->assertInstanceOf('Zend\Log\Writer\Stream', $writers[0]); - $this->assertEquals('foo', $writers[0]->getLogSeparator()); - + $this->assertEquals('foo', $writers[0]->getLogSeparator()); } } diff --git a/test/Writer/AbstractTest.php b/test/Writer/AbstractTest.php index 6057f2cd..41d7d2a5 100644 --- a/test/Writer/AbstractTest.php +++ b/test/Writer/AbstractTest.php @@ -42,7 +42,8 @@ public function testSetFormatter() public function testSetSimpleFormatterByName() { - $this->_writer->setFormatter('simple'); + $instance = $this->_writer->setFormatter('simple'); + $this->assertAttributeInstanceOf('Zend\Log\Formatter\Simple', 'formatter', $instance); } public function testAddFilter() @@ -86,4 +87,33 @@ public function testConvertErrorsToException() $this->setExpectedException('PHPUnit_Framework_Error_Warning'); $writer->write(array('message' => 'test')); } + + public function testConstructorWithOptions() + { + $options = array('filters' => array( + array( + 'name' => 'mock', + ), + array( + 'name' => 'priority', + 'options' => array( + 'priority' => 3, + ), + ), + ), + 'formatter' => array( + 'name' => 'base', + ), + ); + + $writer = new ConcreteWriter($options); + + $this->assertAttributeInstanceOf('Zend\Log\Formatter\Base', 'formatter', $writer); + + $filters = $this->readAttribute($writer, 'filters'); + $this->assertCount(2, $filters); + + $this->assertInstanceOf('Zend\Log\Filter\Priority', $filters[1]); + $this->assertEquals(3, $this->readAttribute($filters[1], 'priority')); + } } From 73a99dcc814d1fc0e4995935f37cd7cc73472eb9 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 10:44:04 +0200 Subject: [PATCH 13/32] added the ability to use options array in FingersCrossed as well --- src/Writer/FingersCrossed.php | 104 ++++++++++++++++++++++++++++- test/Writer/FingersCrossedTest.php | 16 +++++ 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index 3badf902..3f3d5c5d 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -9,6 +9,8 @@ */ namespace Zend\Log\Writer; +use Traversable; +use Zend\Stdlib\ArrayUtils; use Zend\Log\Filter\Priority as PriorityFilter; use Zend\Log\Filter\FilterInterface; use Zend\Log\Formatter\FormatterInterface; @@ -16,6 +18,7 @@ use Zend\Log\Logger; use Zend\Log\Writer\WriterInterface; use Zend\Log\Writer\AbstractWriter; +use Zend\Log\WriterPluginManager; /** * Buffers all events until the strategy determines to flush them. @@ -34,6 +37,13 @@ class FingersCrossed extends AbstractWriter * @var WriterInterface */ protected $writer; + + /** + * Writer plugins + * + * @var WriterPluginManager + */ + protected $writerPlugins; /** * Flag if buffering is enabled @@ -60,13 +70,23 @@ class FingersCrossed extends AbstractWriter /** * Constructor * - * @param WriterInterface $writer Wrapped writer + * @param WriterInterface|string|array|Traversable $writer Wrapped writer or array of configuration options * @param FilterInterface|int $filterOrPriority Filter or log priority which determines buffering of events * @param int $bufferSize Maximum buffer size */ - public function __construct(WriterInterface $writer, $filterOrPriority = null, $bufferSize = 0) + public function __construct($writer, $filterOrPriority = null, $bufferSize = 0) { $this->writer = $writer; + + if ($writer instanceof Traversable) { + $writer = ArrayUtils::iteratorToArray($writer); + } + + if (is_array($writer)) { + $filterOrPriority = isset($writer['priority']) ? $writer['priority'] : null; + $bufferSize = isset($writer['bufferSize']) ? $writer['bufferSize'] : null; + $writer = isset($writer['writer']) ? $writer['writer'] : null; + } if (null === $filterOrPriority) { $filterOrPriority = new PriorityFilter(Logger::WARN); @@ -74,9 +94,89 @@ public function __construct(WriterInterface $writer, $filterOrPriority = null, $ $filterOrPriority = new PriorityFilter($filterOrPriority); } + if (is_array($writer) && isset($writer['name'])) { + $this->setWriter($writer['name'], $writer['options']); + } + else { + $this->setWriter($writer); + } $this->addFilter($filterOrPriority); $this->bufferSize = $bufferSize; } + + /** + * Set a new formatter for this writer + * + * @param string|Formatter\FormatterInterface $formatter + * @return self + * @throws Exception\InvalidArgumentException + */ + public function setWriter($writer, array $options = null) + { + if (is_string($writer)) { + $writer = $this->writerPlugin($writer, $options); + } + + if (!$writer instanceof WriterInterface) { + throw new Exception\InvalidArgumentException(sprintf( + 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', + __NAMESPACE__, + is_object($writer) ? get_class($writer) : gettype($writer) + )); + } + + $this->writer = $writer; + return $this; + } + + /** + * Get writer plugin manager + * + * @return WriterPluginManager + */ + public function getWriterPluginManager() + { + if (null === $this->writerPlugins) { + $this->setWriterPluginManager(new WriterPluginManager()); + } + return $this->writerPlugins; + } + + /** + * Set writer plugin manager + * + * @param string|WriterPluginManager $plugins + * @return Logger + * @throws Exception\InvalidArgumentException + */ + public function setWriterPluginManager($plugins) + { + if (is_string($plugins)) { + $plugins = new $plugins; + } + if (!$plugins instanceof WriterPluginManager) { + throw new Exception\InvalidArgumentException(sprintf( + 'Writer plugin manager must extend %s\WriterPluginManager; received %s', + __NAMESPACE__, + is_object($plugins) ? get_class($plugins) : gettype($plugins) + )); + } + + $this->writerPlugins = $plugins; + return $this; + } + + /** + * Get writer instance + * + * @param string $name + * @param array|null $options + * @return Writer\WriterInterface + */ + public function writerPlugin($name, array $options = null) + { + return $this->getWriterPluginManager()->get($name, $options); + } /** * Log a message to this writer. diff --git a/test/Writer/FingersCrossedTest.php b/test/Writer/FingersCrossedTest.php index a87ce853..c4f83e66 100644 --- a/test/Writer/FingersCrossedTest.php +++ b/test/Writer/FingersCrossedTest.php @@ -54,4 +54,20 @@ public function testAfterFlushing() $this->assertSame(count($wrappedWriter->events), 3); } + + public function setWriterByName() { + $writer = new FingersCrossedWriter('mock'); + $this->assertAttributeInstanceOf('Zend\Log\Writer\Mock', 'writer', $writer); + } + + public function testConstructorOptions() { + $options = array('writer' => 'mock', 'priority' => 3); + $writer = new FingersCrossedWriter($options); + $this->assertAttributeInstanceOf('Zend\Log\Writer\Mock', 'writer', $writer); + + $filters = $this->readAttribute($writer, 'filters'); + $this->assertCount(1, $filters); + $this->assertInstanceOf('Zend\Log\Filter\Priority', $filters[0]); + $this->assertAttributeEquals(3, 'priority', $filters[0]); + } } From 6dd737e1bc391164468632020c4322b9260ebc75 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 10:58:36 +0200 Subject: [PATCH 14/32] CS --- src/Formatter/Base.php | 4 ++-- src/Formatter/Db.php | 4 ++-- src/Formatter/Simple.php | 6 +++--- src/Logger.php | 24 ++++++++++++------------ src/Writer/AbstractWriter.php | 32 ++++++++++++++++---------------- src/Writer/FingersCrossed.php | 23 +++++++++++------------ 6 files changed, 46 insertions(+), 47 deletions(-) diff --git a/src/Formatter/Base.php b/src/Formatter/Base.php index fc83ef53..a7fd4acf 100644 --- a/src/Formatter/Base.php +++ b/src/Formatter/Base.php @@ -39,11 +39,11 @@ public function __construct($dateTimeFormat = null) if ($dateTimeFormat instanceof Traversable) { $dateTimeFormat = iterator_to_array($dateTimeFormat); } - + if (is_array($dateTimeFormat)) { $dateTimeFormat = isset($dateTimeFormat['dateTimeFormat'])? $dateTimeFormat['dateTimeFormat'] : null; } - + if (null !== $dateTimeFormat) { $this->dateTimeFormat = $dateTimeFormat; } diff --git a/src/Formatter/Db.php b/src/Formatter/Db.php index e8ef7266..a891e034 100644 --- a/src/Formatter/Db.php +++ b/src/Formatter/Db.php @@ -39,11 +39,11 @@ public function __construct($dateTimeFormat = null) if ($dateTimeFormat instanceof Traversable) { $dateTimeFormat = iterator_to_array($dateTimeFormat); } - + if (is_array($dateTimeFormat)) { $dateTimeFormat = isset($dateTimeFormat['dateTimeFormat'])? $dateTimeFormat['dateTimeFormat'] : null; } - + if (null !== $dateTimeFormat) { $this->setDateTimeFormat($dateTimeFormat); } diff --git a/src/Formatter/Simple.php b/src/Formatter/Simple.php index fa21bbbd..077ccc0b 100644 --- a/src/Formatter/Simple.php +++ b/src/Formatter/Simple.php @@ -43,12 +43,12 @@ public function __construct($format = null, $dateTimeFormat = null) if ($format instanceof Traversable) { $format = iterator_to_array($format); } - - if (is_array($format)) { + + if (is_array($format)) { $dateTimeFormat = isset($format['dateTimeFormat'])? $format['dateTimeFormat'] : null; $format = isset($format['format'])? $format['format'] : null; } - + if (isset($format) && !is_string($format)) { throw new Exception\InvalidArgumentException('Format must be a string'); } diff --git a/src/Logger.php b/src/Logger.php index 3bc6b33a..d849f798 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -82,7 +82,7 @@ class Logger implements LoggerInterface /** * Constructor - * + * * Set options for an logger. Accepted options are: * - writers: array of writers to add to this logger * - exceptionhandler: if true register this logger as exceptionhandler @@ -95,35 +95,35 @@ class Logger implements LoggerInterface public function __construct(array $options = null) { $this->writers = new SplPriorityQueue(); - + if ($options instanceof Traversable) { $options = ArrayUtils::iteratorToArray($options); } - + if (is_array($options)) { - - if(isset($options['writers']) && is_array($options['writers'])) { + + if(isset($options['writers']) && is_array($options['writers'])) { foreach($options['writers'] as $writer) { - + if(!isset($writer['name'])) { throw new Exception\InvalidArgumentException('Options must contain a name for the writer'); } - + $priority = (isset($writer['priority'])) ? $writer['priority'] : null; $writerOptions = (isset($writer['options'])) ? $writer['options'] : null; $this->addWriter($writer['name'], $priority, $writerOptions); } } - + if(isset($options['exceptionhandler']) && $options['exceptionhandler'] === true) { self::registerExceptionHandler($this); - } - + } + if(isset($options['errorhandler']) && $options['errorhandler'] === true) { self::registerErrorHandler($this); - } - + } + } } diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index e8e9cfa0..774ef14b 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -29,7 +29,7 @@ abstract class AbstractWriter implements WriterInterface * @var FilterPluginManager */ protected $filterPlugins; - + /** * Formatter plugins * @@ -64,10 +64,10 @@ abstract class AbstractWriter implements WriterInterface * @var bool */ protected $errorsToExceptionsConversionLevel = E_WARNING; - + /** * Constructor - * + * * Set options for an writer. Accepted options are: * - filters: array of filters to add to this filter * - formatter: formatter for this writer @@ -81,21 +81,21 @@ public function __construct($options = null) if ($options instanceof Traversable) { $options = iterator_to_array($options); } - + if (is_array($options)) { - + if(isset($options['filters']) && is_array($options['filters'])) { - foreach($options['filters'] as $filter) { + foreach($options['filters'] as $filter) { if(!isset($filter['name'])) { throw new Exception\InvalidArgumentException('Options must contain a name for the filter'); - } + } $filterOptions = (isset($filter['options'])) ? $filter['options'] : null; $this->addFilter($filter['name'], $filterOptions); } } - + if(isset($options['formatter'])) { - $formatter = $options['formatter']; + $formatter = $options['formatter']; if(is_string($formatter) || $formatter instanceof Formatter\FormatterInterface) { $this->setFormatter($formatter); } elseif(is_array($formatter)) { @@ -187,7 +187,7 @@ public function filterPlugin($name, array $options = null) { return $this->getFilterPluginManager()->get($name, $options); } - + /** * Get formatter plugin manager * @@ -200,7 +200,7 @@ public function getFormatterPluginManager() } return $this->formatterPlugins; } - + /** * Set formatter plugin manager * @@ -220,12 +220,12 @@ public function setFormatterPluginManager($plugins) is_object($plugins) ? get_class($plugins) : gettype($plugins) )); } - + $this->formatterPlugins = $plugins; return $this; } - - + + /** * Get formatter instance * @@ -296,12 +296,12 @@ public function setFormatter($formatter, array $options = null) //throw new Exception\InvalidArgumentException(sprintf( // 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', // __NAMESPACE__, - // is_object($formatter) ? get_class($formatter) : gettype($formatter) + // is_object($formatter) ? get_class($formatter) : gettype($formatter) //)); trigger_error(sprintf( 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', __NAMESPACE__, - is_object($formatter) ? get_class($formatter) : gettype($formatter) + is_object($formatter) ? get_class($formatter) : gettype($formatter) )); } diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index 3f3d5c5d..5b8c63e4 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -37,7 +37,7 @@ class FingersCrossed extends AbstractWriter * @var WriterInterface */ protected $writer; - + /** * Writer plugins * @@ -77,11 +77,11 @@ class FingersCrossed extends AbstractWriter public function __construct($writer, $filterOrPriority = null, $bufferSize = 0) { $this->writer = $writer; - + if ($writer instanceof Traversable) { $writer = ArrayUtils::iteratorToArray($writer); } - + if (is_array($writer)) { $filterOrPriority = isset($writer['priority']) ? $writer['priority'] : null; $bufferSize = isset($writer['bufferSize']) ? $writer['bufferSize'] : null; @@ -96,14 +96,13 @@ public function __construct($writer, $filterOrPriority = null, $bufferSize = 0) if (is_array($writer) && isset($writer['name'])) { $this->setWriter($writer['name'], $writer['options']); - } - else { + } else { $this->setWriter($writer); } $this->addFilter($filterOrPriority); $this->bufferSize = $bufferSize; } - + /** * Set a new formatter for this writer * @@ -116,7 +115,7 @@ public function setWriter($writer, array $options = null) if (is_string($writer)) { $writer = $this->writerPlugin($writer, $options); } - + if (!$writer instanceof WriterInterface) { throw new Exception\InvalidArgumentException(sprintf( 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', @@ -124,11 +123,11 @@ public function setWriter($writer, array $options = null) is_object($writer) ? get_class($writer) : gettype($writer) )); } - + $this->writer = $writer; return $this; } - + /** * Get writer plugin manager * @@ -141,7 +140,7 @@ public function getWriterPluginManager() } return $this->writerPlugins; } - + /** * Set writer plugin manager * @@ -161,11 +160,11 @@ public function setWriterPluginManager($plugins) is_object($plugins) ? get_class($plugins) : gettype($plugins) )); } - + $this->writerPlugins = $plugins; return $this; } - + /** * Get writer instance * From 704aa9108008c6ccc61e27edb312d3fc77f0aa92 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 11:25:31 +0200 Subject: [PATCH 15/32] Test CS --- test/Formatter/BaseTest.php | 4 ++-- test/Formatter/SimpleTest.php | 4 ++-- test/LoggerTest.php | 14 +++++++------- test/Writer/AbstractTest.php | 14 +++++++------- test/Writer/FingersCrossedTest.php | 14 ++++++++------ 5 files changed, 26 insertions(+), 24 deletions(-) diff --git a/test/Formatter/BaseTest.php b/test/Formatter/BaseTest.php index 996faa65..a5e1396b 100644 --- a/test/Formatter/BaseTest.php +++ b/test/Formatter/BaseTest.php @@ -63,7 +63,7 @@ public function testSetDateTimeFormat($dateTimeFormat) $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); } - + /** * @dataProvider provideDateTimeFormats */ @@ -71,7 +71,7 @@ public function testSetDateTimeFormatInConstructor($dateTimeFormat) { $options = array('dateTimeFormat' => $dateTimeFormat); $formatter = new BaseFormatter($options); - + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); } diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php index 46107965..d3bcc95e 100644 --- a/test/Formatter/SimpleTest.php +++ b/test/Formatter/SimpleTest.php @@ -27,7 +27,7 @@ public function testConstructorThrowsOnBadFormatString() $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be a string'); new Simple(1); } - + /** * @dataProvider provideDateTimeFormats */ @@ -35,7 +35,7 @@ public function testConstructorWithOptions($dateTimeFormat) { $options = array('dateTimeFormat' => $dateTimeFormat, 'format' => '%timestamp%'); $formatter = new Simple($options); - + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); $this->assertAttributeEquals('%timestamp%', 'format', $formatter); } diff --git a/test/LoggerTest.php b/test/LoggerTest.php index 17a6c1e3..82de1687 100644 --- a/test/LoggerTest.php +++ b/test/LoggerTest.php @@ -259,8 +259,8 @@ public function testRegisterErrorHandler() Logger::unregisterErrorHandler(); $this->assertEquals($writer->events[0]['message'], 'Undefined variable: test'); } - - public function testOptionsWithMock() + + public function testOptionsWithMock() { $options = array('writers' => array( 'first_writer' => array( @@ -268,12 +268,12 @@ public function testOptionsWithMock() ) )); $logger = new Logger($options); - + $writers = $logger->getWriters()->toArray(); $this->assertCount(1, $writers); $this->assertInstanceOf('Zend\Log\Writer\Mock', $writers[0]); } - + public function testOptionsWithWriterOptions() { $options = array('writers' => array( @@ -282,14 +282,14 @@ public function testOptionsWithWriterOptions() 'options' => array( 'stream' => 'php://output', 'log_separator' => 'foo' - ), + ), ) )); $logger = new Logger($options); - + $writers = $logger->getWriters()->toArray(); $this->assertCount(1, $writers); $this->assertInstanceOf('Zend\Log\Writer\Stream', $writers[0]); - $this->assertEquals('foo', $writers[0]->getLogSeparator()); + $this->assertEquals('foo', $writers[0]->getLogSeparator()); } } diff --git a/test/Writer/AbstractTest.php b/test/Writer/AbstractTest.php index 41d7d2a5..3376840c 100644 --- a/test/Writer/AbstractTest.php +++ b/test/Writer/AbstractTest.php @@ -39,7 +39,7 @@ public function testSetFormatter() $this->setExpectedException('PHPUnit_Framework_Error'); $this->_writer->setFormatter(new \StdClass()); } - + public function testSetSimpleFormatterByName() { $instance = $this->_writer->setFormatter('simple'); @@ -87,12 +87,12 @@ public function testConvertErrorsToException() $this->setExpectedException('PHPUnit_Framework_Error_Warning'); $writer->write(array('message' => 'test')); } - + public function testConstructorWithOptions() { $options = array('filters' => array( array( - 'name' => 'mock', + 'name' => 'mock', ), array( 'name' => 'priority', @@ -105,14 +105,14 @@ public function testConstructorWithOptions() 'name' => 'base', ), ); - + $writer = new ConcreteWriter($options); - + $this->assertAttributeInstanceOf('Zend\Log\Formatter\Base', 'formatter', $writer); - + $filters = $this->readAttribute($writer, 'filters'); $this->assertCount(2, $filters); - + $this->assertInstanceOf('Zend\Log\Filter\Priority', $filters[1]); $this->assertEquals(3, $this->readAttribute($filters[1], 'priority')); } diff --git a/test/Writer/FingersCrossedTest.php b/test/Writer/FingersCrossedTest.php index c4f83e66..e654cdba 100644 --- a/test/Writer/FingersCrossedTest.php +++ b/test/Writer/FingersCrossedTest.php @@ -54,17 +54,19 @@ public function testAfterFlushing() $this->assertSame(count($wrappedWriter->events), 3); } - - public function setWriterByName() { + + public function setWriterByName() + { $writer = new FingersCrossedWriter('mock'); - $this->assertAttributeInstanceOf('Zend\Log\Writer\Mock', 'writer', $writer); + $this->assertAttributeInstanceOf('Zend\Log\Writer\Mock', 'writer', $writer); } - - public function testConstructorOptions() { + + public function testConstructorOptions() + { $options = array('writer' => 'mock', 'priority' => 3); $writer = new FingersCrossedWriter($options); $this->assertAttributeInstanceOf('Zend\Log\Writer\Mock', 'writer', $writer); - + $filters = $this->readAttribute($writer, 'filters'); $this->assertCount(1, $filters); $this->assertInstanceOf('Zend\Log\Filter\Priority', $filters[0]); From 1535aef4fc18764acc9310cc70b89ff73c4ca4a2 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 14:05:19 +0200 Subject: [PATCH 16/32] Accidentally committed one removed test. Uncommented again. Nevertheless XmlTest::testFormatWillRemoveExtraEmptyArrayFromEvent() will fail on windows 7 x64 --- test/Formatter/XmlTest.php | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/test/Formatter/XmlTest.php b/test/Formatter/XmlTest.php index b1b33af6..660aeaee 100644 --- a/test/Formatter/XmlTest.php +++ b/test/Formatter/XmlTest.php @@ -179,22 +179,22 @@ public function testObjectsWithStringSerializationAreIncludedInFormattedString() $this->assertContains($expected, $output); } -// /** -// * @group ZF2-453 -// */ -// public function testFormatWillRemoveExtraEmptyArrayFromEvent() -// { -// $formatter = new XmlFormatter; -// $d = new DateTime('2001-01-01T12:00:00-06:00'); -// $event = array( -// 'timestamp' => $d, -// 'message' => 'test', -// 'priority' => 1, -// 'priorityName' => 'CRIT', -// 'extra' => array() -// ); -// $expected = '2001-01-01T12:00:00-06:00test1CRIT'; -// $expected .= PHP_EOL . PHP_EOL; -// $this->assertEquals($expected, $formatter->format($event)); -// } + /** + * @group ZF2-453 + */ + public function testFormatWillRemoveExtraEmptyArrayFromEvent() + { + $formatter = new XmlFormatter; + $d = new DateTime('2001-01-01T12:00:00-06:00'); + $event = array( + 'timestamp' => $d, + 'message' => 'test', + 'priority' => 1, + 'priorityName' => 'CRIT', + 'extra' => array() + ); + $expected = '2001-01-01T12:00:00-06:00test1CRIT'; + $expected .= PHP_EOL . PHP_EOL; + $this->assertEquals($expected, $formatter->format($event)); + } } From 70ea35b687a3e3cb0d6f7e12b458f839e966d92a Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 14:52:59 +0200 Subject: [PATCH 17/32] Test CS --- test/LoggerTest.php | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/test/LoggerTest.php b/test/LoggerTest.php index fb9119d1..d321cb2d 100644 --- a/test/LoggerTest.php +++ b/test/LoggerTest.php @@ -261,33 +261,36 @@ public function testRegisterErrorHandler() Logger::unregisterErrorHandler(); $this->assertEquals($writer->events[0]['message'], 'Undefined variable: test'); } - - - public function testAddProcessor() { + + + public function testAddProcessor() + { $processor = new Backtrace(); $this->logger->addProcessor($processor); - + $processors = $this->logger->getProcessors()->toArray(); $this->assertEquals($processor, $processors[0]); } - - public function testAddProcessorByName() { + + public function testAddProcessorByName() + { $this->logger->addProcessor('backtrace'); - + $processors = $this->logger->getProcessors()->toArray(); $this->assertInstanceOf('Zend\Log\Processor\Backtrace', $processors[0]); - + $writer = new MockWriter; $this->logger->addWriter($writer); $this->logger->log(Logger::ERR, 'foo'); } - - public function testProcessorOutputAdded() { + + public function testProcessorOutputAdded() + { $processor = new Backtrace(); $this->logger->addProcessor($processor); $writer = new MockWriter; $this->logger->addWriter($writer); - + $this->logger->log(Logger::ERR, 'foo'); $this->assertEquals(__FILE__, $writer->events[0]['extra']['file']); } From 4f1da0f47435fc6b51906dfe11508731bed3dc5a Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Wed, 10 Oct 2012 16:01:53 +0200 Subject: [PATCH 18/32] Replaced custom isCli() method with Console::isConsole() --- src/Processor/RequestId.php | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/Processor/RequestId.php b/src/Processor/RequestId.php index 3f9feecb..3b372f2d 100644 --- a/src/Processor/RequestId.php +++ b/src/Processor/RequestId.php @@ -10,6 +10,8 @@ namespace Zend\Log\Processor; +use Zend\Console\Console; + /** * @category Zend * @package Zend_Log @@ -43,19 +45,8 @@ public function process(array $event) protected function getIdentifier() { $requestTime = (version_compare(PHP_VERSION, '5.4.0') >= 0) ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; - $remoteAddr = $this->isCli() ? 'local' : $_SERVER['REMOTE_ADDR']; + $remoteAddr = Console::isConsole() ? 'local' : $_SERVER['REMOTE_ADDR']; return md5($requestTime . $remoteAddr); } - - /** - * Check if PHP is run from command line - * - * @return boolean true if php is run from command line - */ - protected function isCli() - { - return php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']); - } - } From fcc61e876b6948a3c1c120c75c95f2cbab9a5891 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Fri, 12 Oct 2012 08:36:47 +0200 Subject: [PATCH 19/32] Added service factory for logger to use with mvc --- src/LoggerServiceFactory.php | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/LoggerServiceFactory.php diff --git a/src/LoggerServiceFactory.php b/src/LoggerServiceFactory.php new file mode 100644 index 00000000..ad8d95c2 --- /dev/null +++ b/src/LoggerServiceFactory.php @@ -0,0 +1,31 @@ +get('Config'); + $logConfig = isset($config['log']) ? $config['log'] : array(); + $logger = new Logger($logConfig); + } +} From 66da25d7fbceed5b3a2d4a486ac48acac8e1ffa8 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Mon, 15 Oct 2012 09:01:17 +0200 Subject: [PATCH 20/32] Updated behavior when setting formatter in writers which doesn't support formatting. Do nothing instead of throwing an exception --- src/Writer/FingersCrossed.php | 5 ++--- src/Writer/MongoDB.php | 5 ++--- test/Writer/FingersCrossedTest.php | 9 +++++++++ test/Writer/MongoDBTest.php | 4 +--- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/Writer/FingersCrossed.php b/src/Writer/FingersCrossed.php index 5b8c63e4..4e70a32f 100644 --- a/src/Writer/FingersCrossed.php +++ b/src/Writer/FingersCrossed.php @@ -248,12 +248,11 @@ public function reset() * Fomatters must be set on the wrapped writer. * * @param string|Formatter\FormatterInterface $formatter - * @return void - * @throws Zend\Log\Exception\InvalidArgumentException + * @return WriterInterface */ public function setFormatter($formatter) { - throw new Exception\InvalidArgumentException(get_class() . ' does not support formatting'); + return $this->writer; } /** diff --git a/src/Writer/MongoDB.php b/src/Writer/MongoDB.php index 1dff2924..c359e8cd 100644 --- a/src/Writer/MongoDB.php +++ b/src/Writer/MongoDB.php @@ -90,12 +90,11 @@ public function __construct($mongo, $database, $collection, array $saveOptions = * This writer does not support formatting. * * @param string|Zend\Log\Formatter\FormatterInterface $formatter - * @return void - * @throws Zend\Log\Exception\InvalidArgumentException + * @return WriterInterface */ public function setFormatter($formatter) { - throw new InvalidArgumentException(get_class() . ' does not support formatting'); + return $this; } /** diff --git a/test/Writer/FingersCrossedTest.php b/test/Writer/FingersCrossedTest.php index e654cdba..cd5ca228 100644 --- a/test/Writer/FingersCrossedTest.php +++ b/test/Writer/FingersCrossedTest.php @@ -72,4 +72,13 @@ public function testConstructorOptions() $this->assertInstanceOf('Zend\Log\Filter\Priority', $filters[0]); $this->assertAttributeEquals(3, 'priority', $filters[0]); } + + public function testFormattingIsNotSupported() + { + $options = array('writer' => 'mock', 'priority' => 3); + $writer = new FingersCrossedWriter($options); + + $writer->setFormatter($this->getMock('Zend\Log\Formatter\FormatterInterface')); + $this->assertAttributeEmpty('formatter', $writer); + } } diff --git a/test/Writer/MongoDBTest.php b/test/Writer/MongoDBTest.php index c5240354..0536d99f 100644 --- a/test/Writer/MongoDBTest.php +++ b/test/Writer/MongoDBTest.php @@ -48,14 +48,12 @@ public function setUp() ->will($this->returnValue($this->mongoCollection)); } - /** - * @expectedException Zend\Log\Exception\InvalidArgumentException - */ public function testFormattingIsNotSupported() { $writer = new MongoDBWriter($this->mongo, $this->database, $this->collection); $writer->setFormatter($this->getMock('Zend\Log\Formatter\FormatterInterface')); + $this->assertAttributeEmpty('formatter', $writer); } public function testWriteWithDefaultSaveOptions() From 4a94f085a2af6bddb3377b3c4359b4f34d5100ef Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Mon, 15 Oct 2012 09:07:12 +0200 Subject: [PATCH 21/32] AbstractWriter::setFormatter() throws exception if type is neither string nor FormatterInterface. This is a small BC break. Tests updated to check the new type of exception. --- src/Writer/AbstractWriter.php | 10 ++-------- test/Writer/AbstractTest.php | 2 +- test/Writer/DbTest.php | 2 +- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index 774ef14b..d8c2e286 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -292,20 +292,14 @@ public function setFormatter($formatter, array $options = null) } if (!$formatter instanceof Formatter\FormatterInterface) { - // This should be used instead of triggering an error, but this will require to change tests - //throw new Exception\InvalidArgumentException(sprintf( - // 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', - // __NAMESPACE__, - // is_object($formatter) ? get_class($formatter) : gettype($formatter) - //)); - trigger_error(sprintf( + throw new Exception\InvalidArgumentException(sprintf( 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', __NAMESPACE__, is_object($formatter) ? get_class($formatter) : gettype($formatter) )); } - $this->formatter= $formatter; + $this->formatter = $formatter; return $this; } diff --git a/test/Writer/AbstractTest.php b/test/Writer/AbstractTest.php index 3376840c..85af9fb7 100644 --- a/test/Writer/AbstractTest.php +++ b/test/Writer/AbstractTest.php @@ -36,7 +36,7 @@ protected function setUp() public function testSetFormatter() { $this->_writer->setFormatter(new SimpleFormatter()); - $this->setExpectedException('PHPUnit_Framework_Error'); + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); $this->_writer->setFormatter(new \StdClass()); } diff --git a/test/Writer/DbTest.php b/test/Writer/DbTest.php index 8a2467a6..f60458da 100644 --- a/test/Writer/DbTest.php +++ b/test/Writer/DbTest.php @@ -202,7 +202,7 @@ public function testShutdownRemovesReferenceToDatabaseInstance() */ public function testThrowStrictSetFormatter() { - $this->setExpectedException('PHPUnit_Framework_Error'); + $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException'); $this->writer->setFormatter(new \StdClass()); } From c73f4795037ac8a1b51c0768c074d4cd262ea295 Mon Sep 17 00:00:00 2001 From: Stefan Kleff Date: Mon, 22 Oct 2012 09:53:10 +0200 Subject: [PATCH 22/32] Added support for proxies/loadbalancers --- src/Processor/RequestId.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/Processor/RequestId.php b/src/Processor/RequestId.php index 3b372f2d..ef31cf13 100644 --- a/src/Processor/RequestId.php +++ b/src/Processor/RequestId.php @@ -45,8 +45,15 @@ public function process(array $event) protected function getIdentifier() { $requestTime = (version_compare(PHP_VERSION, '5.4.0') >= 0) ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; - $remoteAddr = Console::isConsole() ? 'local' : $_SERVER['REMOTE_ADDR']; - return md5($requestTime . $remoteAddr); + if(Console::isConsole()) { + return md5($requestTime); + } + + if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + return md5($requestTime . $_SERVER['HTTP_X_FORWARDED_FOR']); + } + + return md5($requestTime . $_SERVER['REMOTE_ADDR']); } } From 7de911b654d1850cd5f83aac6791223f64212f8f Mon Sep 17 00:00:00 2001 From: Philip G Date: Mon, 22 Oct 2012 10:47:18 -0700 Subject: [PATCH 23/32] Added the ability for FirePhp to understand 'extras' passed to \Zend\Log --- src/Writer/FirePhp.php | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/src/Writer/FirePhp.php b/src/Writer/FirePhp.php index c4c73e5d..bfdad262 100644 --- a/src/Writer/FirePhp.php +++ b/src/Writer/FirePhp.php @@ -55,27 +55,34 @@ protected function doWrite(array $event) return; } - $line = $this->formatter->format($event); + $label = null; + + if ( !empty($event['extra']) ) { + $line = $event['extra']; + $label = $this->formatter->format($event); + } else { + $line = $this->formatter->format($event); + } switch ($event['priority']) { case Logger::EMERG: case Logger::ALERT: case Logger::CRIT: case Logger::ERR: - $firephp->error($line); + $firephp->error($line, $label); break; case Logger::WARN: - $firephp->warn($line); + $firephp->warn($line, $label); break; case Logger::NOTICE: case Logger::INFO: - $firephp->info($line); + $firephp->info($line, $label); break; case Logger::DEBUG: $firephp->trace($line); break; default: - $firephp->log($line); + $firephp->log($line, $label); break; } } From e753ca6079504944e308833672bc5ea20ba622c3 Mon Sep 17 00:00:00 2001 From: gabbert_p Date: Tue, 23 Oct 2012 10:04:07 -0700 Subject: [PATCH 24/32] Moved the line/label logic into the formatter. --- src/Formatter/FirePhp.php | 12 ++++++++++-- src/Writer/FirePhp.php | 9 +-------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Formatter/FirePhp.php b/src/Formatter/FirePhp.php index 0a21cde1..22ea990d 100644 --- a/src/Formatter/FirePhp.php +++ b/src/Formatter/FirePhp.php @@ -21,11 +21,19 @@ class FirePhp implements FormatterInterface * Formats the given event data into a single line to be written by the writer. * * @param array $event The event data which should be formatted. - * @return string + * @return array line message and optionally label if 'extra' data exists. */ public function format($event) { - return $event['message']; + $label = null; + if ( !empty($event['extra']) ) { + $line = $event['extra']; + $label = $event['message']; + } else { + $line = $event['message']; + } + + return array($line, $label); } /** diff --git a/src/Writer/FirePhp.php b/src/Writer/FirePhp.php index bfdad262..e9f09365 100644 --- a/src/Writer/FirePhp.php +++ b/src/Writer/FirePhp.php @@ -55,15 +55,8 @@ protected function doWrite(array $event) return; } - $label = null; + list($line, $label) = $this->formatter->format($event); - if ( !empty($event['extra']) ) { - $line = $event['extra']; - $label = $this->formatter->format($event); - } else { - $line = $this->formatter->format($event); - } - switch ($event['priority']) { case Logger::EMERG: case Logger::ALERT: From 30a2da9144b8091981862665611a68760200ea85 Mon Sep 17 00:00:00 2001 From: gabbert_p Date: Tue, 23 Oct 2012 11:41:52 -0700 Subject: [PATCH 25/32] Added unit tests for new FirePhp formatter functionality. --- test/Formatter/FirePhpTest.php | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/test/Formatter/FirePhpTest.php b/test/Formatter/FirePhpTest.php index 9fef4bf5..a65e497d 100644 --- a/test/Formatter/FirePhpTest.php +++ b/test/Formatter/FirePhpTest.php @@ -33,14 +33,39 @@ */ class FirePhpTest extends \PHPUnit_Framework_TestCase { - public function testFormat() + public function testFormatWithExtraData() + { + $fields = array( 'message' => 'foo', + 'extra' => new \stdClass() ); + + $f = new FirePhp(); + list($line, $label) = $f->format($fields); + + $this->assertContains($fields['message'], $label); + $this->assertEquals($fields['extra'], $line); + } + + public function testFormatWithoutExtra() { $fields = array( 'message' => 'foo' ); $f = new FirePhp(); - $line = $f->format($fields); + list($line, $label) = $f->format($fields); + + $this->assertContains($fields['message'], $line); + $this->assertNull($label); + } + + public function testFormatWithEmptyExtra() + { + $fields = array( 'message' => 'foo', + 'extra' => array() ); + + $f = new FirePhp(); + list($line, $label) = $f->format($fields); $this->assertContains($fields['message'], $line); + $this->assertEmpty($label); } public function testSetDateTimeFormatDoesNothing() From 27c70f628cd3f1909d7930d682aa8565efffb129 Mon Sep 17 00:00:00 2001 From: gabbert_p Date: Wed, 24 Oct 2012 11:15:17 -0700 Subject: [PATCH 26/32] Removed trailing spaces. --- src/Writer/FirePhp.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Writer/FirePhp.php b/src/Writer/FirePhp.php index e9f09365..f0c43461 100644 --- a/src/Writer/FirePhp.php +++ b/src/Writer/FirePhp.php @@ -56,7 +56,7 @@ protected function doWrite(array $event) } list($line, $label) = $this->formatter->format($event); - + switch ($event['priority']) { case Logger::EMERG: case Logger::ALERT: From 548745f4b0d0a204e78c949b047575019b93f8af Mon Sep 17 00:00:00 2001 From: gabbert_p Date: Wed, 24 Oct 2012 11:34:30 -0700 Subject: [PATCH 27/32] Unit test update: empty extra data should return NULL label (not just empty). --- test/Formatter/FirePhpTest.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Formatter/FirePhpTest.php b/test/Formatter/FirePhpTest.php index a65e497d..24165d31 100644 --- a/test/Formatter/FirePhpTest.php +++ b/test/Formatter/FirePhpTest.php @@ -44,8 +44,8 @@ public function testFormatWithExtraData() $this->assertContains($fields['message'], $label); $this->assertEquals($fields['extra'], $line); } - - public function testFormatWithoutExtra() + + public function testFormatWithoutExtra() { $fields = array( 'message' => 'foo' ); @@ -55,8 +55,8 @@ public function testFormatWithoutExtra() $this->assertContains($fields['message'], $line); $this->assertNull($label); } - - public function testFormatWithEmptyExtra() + + public function testFormatWithEmptyExtra() { $fields = array( 'message' => 'foo', 'extra' => array() ); @@ -65,7 +65,7 @@ public function testFormatWithEmptyExtra() list($line, $label) = $f->format($fields); $this->assertContains($fields['message'], $line); - $this->assertEmpty($label); + $this->assertNull($label); } public function testSetDateTimeFormatDoesNothing() From d87ad174925bea48a4661514409502cd064d49ad Mon Sep 17 00:00:00 2001 From: Philip G Date: Fri, 26 Oct 2012 11:51:31 -0700 Subject: [PATCH 28/32] Ran php-cs-fixer against FirePhp classes. --- src/Formatter/FirePhp.php | 6 +++--- src/Writer/FirePhp.php | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Formatter/FirePhp.php b/src/Formatter/FirePhp.php index 22ea990d..51b1e3d3 100644 --- a/src/Formatter/FirePhp.php +++ b/src/Formatter/FirePhp.php @@ -20,8 +20,8 @@ class FirePhp implements FormatterInterface /** * Formats the given event data into a single line to be written by the writer. * - * @param array $event The event data which should be formatted. - * @return array line message and optionally label if 'extra' data exists. + * @param array $event The event data which should be formatted. + * @return array line message and optionally label if 'extra' data exists. */ public function format($event) { @@ -49,7 +49,7 @@ public function getDateTimeFormat() /** * This method is implemented for FormatterInterface but not used. * - * @param string $dateTimeFormat + * @param string $dateTimeFormat * @return FormatterInterface */ public function setDateTimeFormat($dateTimeFormat) diff --git a/src/Writer/FirePhp.php b/src/Writer/FirePhp.php index f0c43461..a080fa93 100644 --- a/src/Writer/FirePhp.php +++ b/src/Writer/FirePhp.php @@ -44,7 +44,7 @@ public function __construct(FirePhp\FirePhpInterface $instance = null) /** * Write a message to the log. * - * @param array $event event data + * @param array $event event data * @return void */ protected function doWrite(array $event) @@ -117,6 +117,7 @@ public function getFirePhp() public function setFirePhp(FirePhp\FirePhpInterface $instance) { $this->firephp = $instance; + return $this; } } From 1771985568662e0ae9aac0c357bd6504a8d0aa04 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 30 Oct 2012 13:31:42 -0500 Subject: [PATCH 29/32] [zendframework/zf2#2727] CS review - indentation - trailing whitespace - object calisthenics --- src/Processor/Backtrace.php | 41 +++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/src/Processor/Backtrace.php b/src/Processor/Backtrace.php index c6a029ba..9c566127 100644 --- a/src/Processor/Backtrace.php +++ b/src/Processor/Backtrace.php @@ -37,30 +37,32 @@ class Backtrace implements ProcessorInterface */ public function process(array $event) { - $trace = $this->getBacktrace(); + $trace = $this->getBacktrace(); - array_shift($trace); // ignore $this->getBacktrace(); - array_shift($trace); // ignore $this->process() + array_shift($trace); // ignore $this->getBacktrace(); + array_shift($trace); // ignore $this->process() - $i = 0; - while (isset($trace[$i]['class']) && false !== strpos($trace[$i]['class'], $this->ignoredNamespace)) { - $i++; - } + $i = 0; + while (isset($trace[$i]['class']) + && false !== strpos($trace[$i]['class'], $this->ignoredNamespace) + ) { + $i++; + } - $origin = array( - 'file' => isset($trace[$i-1]['file']) ? $trace[$i-1]['file'] : null, - 'line' => isset($trace[$i-1]['line']) ? $trace[$i-1]['line'] : null, - 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, - 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, - ); + $origin = array( + 'file' => isset($trace[$i-1]['file']) ? $trace[$i-1]['file'] : null, + 'line' => isset($trace[$i-1]['line']) ? $trace[$i-1]['line'] : null, + 'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null, + 'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null, + ); - if(!isset($event['extra'])) { - $event['extra'] = $origin; - } else { - $event['extra'] = array_merge($origin, $event['extra']); - } + $extra = $origin; + if (isset($event['extra'])) { + $extra = array_merge($origin, $event['extra']); + } + $event['extra'] = $extra; - return $event; + return $event; } /** @@ -80,5 +82,4 @@ protected function getBacktrace() return debug_backtrace(); } - } From 1fe274ead084dd37ccbc6009cfbbae9f2aa1aed4 Mon Sep 17 00:00:00 2001 From: Matthew Weier O'Phinney Date: Tue, 30 Oct 2012 13:37:35 -0500 Subject: [PATCH 30/32] [zendframework/zf2#2727] CS review - Trailing whitespace - Cache generated value, as it will not change in lifetime of request --- src/Processor/RequestId.php | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/src/Processor/RequestId.php b/src/Processor/RequestId.php index ef31cf13..0e320bd4 100644 --- a/src/Processor/RequestId.php +++ b/src/Processor/RequestId.php @@ -19,9 +19,16 @@ */ class RequestId implements ProcessorInterface { + /** + * Request identifier + * + * @var string + */ + protected $identifier; /** - * Adds a identfier for the request to the log. + * Adds a identifier for the request to the log. + * * This enables to filter the log for messages belonging to a specific request * * @param array $event event data @@ -29,7 +36,7 @@ class RequestId implements ProcessorInterface */ public function process(array $event) { - if(!isset($event['extra'])) { + if (!isset($event['extra'])) { $event['extra'] = array(); } @@ -40,20 +47,29 @@ public function process(array $event) /** * Provide unique identifier for a request * - * @return array: + * @return string */ protected function getIdentifier() { - $requestTime = (version_compare(PHP_VERSION, '5.4.0') >= 0) ? $_SERVER['REQUEST_TIME_FLOAT'] : $_SERVER['REQUEST_TIME']; + if ($this->identifier) { + return $this->identifier; + } + + $requestTime = (version_compare(PHP_VERSION, '5.4.0') >= 0) + ? $_SERVER['REQUEST_TIME_FLOAT'] + : $_SERVER['REQUEST_TIME']; - if(Console::isConsole()) { - return md5($requestTime); + if (Console::isConsole()) { + $this->identifier = md5($requestTime); + return $this->identifier; } - if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { - return md5($requestTime . $_SERVER['HTTP_X_FORWARDED_FOR']); + if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $this->identifier = md5($requestTime . $_SERVER['HTTP_X_FORWARDED_FOR']); + return $this->identifier; } - return md5($requestTime . $_SERVER['REMOTE_ADDR']); + $this->identifier = md5($requestTime . $_SERVER['REMOTE_ADDR']); + return $this->identifier; } } From a5b4b8d6770cf6de22a5c9c3313fa8594c71360b Mon Sep 17 00:00:00 2001 From: Alex Denvir Date: Fri, 9 Nov 2012 15:33:33 +0000 Subject: [PATCH 31/32] Improve coding standards on new traits, add tests --- src/LoggerAwareTrait.php | 6 ++--- test/LoggerAwareTraitTest.php | 33 +++++++++++++++++++++++++ test/TestAsset/MockLoggerAwareTrait.php | 19 ++++++++++++++ 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 test/LoggerAwareTraitTest.php create mode 100644 test/TestAsset/MockLoggerAwareTrait.php diff --git a/src/LoggerAwareTrait.php b/src/LoggerAwareTrait.php index 02f538df..b610682d 100644 --- a/src/LoggerAwareTrait.php +++ b/src/LoggerAwareTrait.php @@ -19,15 +19,15 @@ trait LoggerAwareTrait { /** - * @var \Zend\Log\LoggerInterface + * @var LoggerInterface */ protected $logger = null; /** * setLogger * - * @param \Zend\Log\LoggerInterface $logger - * @return + * @param LoggerInterface $logger + * @return mixed */ public function setLogger(LoggerInterface $logger) { diff --git a/test/LoggerAwareTraitTest.php b/test/LoggerAwareTraitTest.php new file mode 100644 index 00000000..e981e139 --- /dev/null +++ b/test/LoggerAwareTraitTest.php @@ -0,0 +1,33 @@ +assertAttributeEquals(null, 'logger', $object); + + $logger = new Logger; + + $object->setLogger($logger); + + $this->assertAttributeEquals($logger, 'logger', $object); + } +} diff --git a/test/TestAsset/MockLoggerAwareTrait.php b/test/TestAsset/MockLoggerAwareTrait.php new file mode 100644 index 00000000..4bbac129 --- /dev/null +++ b/test/TestAsset/MockLoggerAwareTrait.php @@ -0,0 +1,19 @@ + Date: Mon, 19 Nov 2012 17:30:14 +0000 Subject: [PATCH 32/32] Improve function comment quality, clean up tests a little --- src/LoggerAwareTrait.php | 2 +- test/LoggerAwareTraitTest.php | 8 ++++---- test/TestAsset/MockLoggerAwareTrait.php | 19 ------------------- 3 files changed, 5 insertions(+), 24 deletions(-) delete mode 100644 test/TestAsset/MockLoggerAwareTrait.php diff --git a/src/LoggerAwareTrait.php b/src/LoggerAwareTrait.php index b610682d..33cbfe43 100644 --- a/src/LoggerAwareTrait.php +++ b/src/LoggerAwareTrait.php @@ -24,7 +24,7 @@ trait LoggerAwareTrait protected $logger = null; /** - * setLogger + * Set logger object * * @param LoggerInterface $logger * @return mixed diff --git a/test/LoggerAwareTraitTest.php b/test/LoggerAwareTraitTest.php index e981e139..55e9ad78 100644 --- a/test/LoggerAwareTraitTest.php +++ b/test/LoggerAwareTraitTest.php @@ -13,14 +13,14 @@ use \PHPUnit_Framework_TestCase as TestCase; use \Zend\Log\Logger; +/** + * @requires PHP 5.4 + */ class LoggerAwareTraitTest extends TestCase { - /** - * @requires PHP 5.4 - */ public function testSetLogger() { - $object = new TestAsset\MockLoggerAwareTrait; + $object = $this->getObjectForTrait('\Zend\Log\LoggerAwareTrait'); $this->assertAttributeEquals(null, 'logger', $object); diff --git a/test/TestAsset/MockLoggerAwareTrait.php b/test/TestAsset/MockLoggerAwareTrait.php deleted file mode 100644 index 4bbac129..00000000 --- a/test/TestAsset/MockLoggerAwareTrait.php +++ /dev/null @@ -1,19 +0,0 @@ -