diff --git a/src/Filter/Regex.php b/src/Filter/Regex.php index 5aa8e4dc..b699480d 100644 --- a/src/Filter/Regex.php +++ b/src/Filter/Regex.php @@ -45,12 +45,12 @@ public function __construct($regex) } ErrorHandler::start(E_WARNING); $result = preg_match($regex, ''); - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if ($result === false) { throw new Exception\InvalidArgumentException(sprintf( 'Invalid regular expression "%s"', $regex - )); + ), 0, $error); } $this->regex = $regex; } diff --git a/src/Formatter/Base.php b/src/Formatter/Base.php new file mode 100644 index 00000000..162b95ce --- /dev/null +++ b/src/Formatter/Base.php @@ -0,0 +1,114 @@ +dateTimeFormat = $dateTimeFormat; + } + } + + /** + * Formats data to be written by the writer. + * + * @param array $event event data + * @return array + */ + public function format($event) + { + foreach ($event as $key => $value) { + // Keep extra as an array + if ('extra' === $key) { + $event[$key] = self::format($value); + } else { + $event[$key] = $this->normalize($value); + } + } + + return $event; + } + + /** + * Normalize all non-scalar data types (except null) in a string value + * + * @param mixed $value + * @return mixed + */ + protected function normalize($value) + { + if (is_scalar($value) || null === $value) { + return $value; + } + + if ($value instanceof DateTime) { + $value = $value->format($this->getDateTimeFormat()); + } elseif (is_array($value) || $value instanceof Traversable) { + if ($value instanceof Traversable) { + $value = iterator_to_array($value); + } + foreach ($value as $key => $subvalue) { + $value[$key] = $this->normalize($subvalue); + } + $value = json_encode($value); + } elseif (is_object($value) && !method_exists($value,'__toString')) { + $value = sprintf('object(%s) %s', get_class($value), json_encode($value)); + } elseif (is_resource($value)) { + $value = sprintf('resource(%s)', get_resource_type($value)); + } elseif (!is_object($value)) { + $value = gettype($value); + } + + return (string) $value; + } + + /** + * {@inheritDoc} + */ + public function getDateTimeFormat() + { + return $this->dateTimeFormat; + } + + /** + * {@inheritDoc} + */ + public function setDateTimeFormat($dateTimeFormat) + { + $this->dateTimeFormat = (string) $dateTimeFormat; + return $this; + } +} \ No newline at end of file diff --git a/src/Formatter/Db.php b/src/Formatter/Db.php new file mode 100644 index 00000000..6f8a45d2 --- /dev/null +++ b/src/Formatter/Db.php @@ -0,0 +1,78 @@ +setDateTimeFormat($dateTimeFormat); + } + } + + /** + * Formats data to be written by the writer. + * + * @param array $event event data + * @return array + */ + public function format($event) + { + $format = $this->getDateTimeFormat(); + array_walk_recursive($event, function (&$value) use ($format) { + if ($value instanceof DateTime) { + $value = $value->format($format); + } + }); + + return $event; + } + + /** + * {@inheritDoc} + */ + public function getDateTimeFormat() + { + return $this->dateTimeFormat; + } + + /** + * {@inheritDoc} + */ + public function setDateTimeFormat($dateTimeFormat) + { + $this->dateTimeFormat = (string) $dateTimeFormat; + return $this; + } +} diff --git a/src/Formatter/Simple.php b/src/Formatter/Simple.php index 761ed799..09e92768 100644 --- a/src/Formatter/Simple.php +++ b/src/Formatter/Simple.php @@ -18,9 +18,9 @@ * @package Zend_Log * @subpackage Formatter */ -class Simple implements FormatterInterface +class Simple extends Base { - const DEFAULT_FORMAT = '%timestamp% %priorityName% (%priority%): %message% %info%'; + const DEFAULT_FORMAT = '%timestamp% %priorityName% (%priority%): %message% %extra%'; /** * Format specifier for log messages @@ -29,14 +29,6 @@ class Simple implements FormatterInterface */ protected $format; - /** - * Format specifier for DateTime objects in event data (default: ISO 8601) - * - * @see http://php.net/manual/en/function.date.php - * @var string - */ - protected $dateTimeFormat = self::DEFAULT_DATETIME_FORMAT; - /** * Class constructor * @@ -53,9 +45,7 @@ public function __construct($format = null, $dateTimeFormat = null) $this->format = isset($format) ? $format : static::DEFAULT_FORMAT; - if (isset($dateTimeFormat)) { - $this->dateTimeFormat = $dateTimeFormat; - } + parent::__construct($dateTimeFormat); } /** @@ -68,41 +58,22 @@ public function format($event) { $output = $this->format; - if (!isset($event['info'])) { - $event['info'] = ''; - } - - if (isset($event['timestamp']) && $event['timestamp'] instanceof DateTime) { - $event['timestamp'] = $event['timestamp']->format($this->getDateTimeFormat()); - } - + $event = parent::format($event); foreach ($event as $name => $value) { - if ((is_object($value) && !method_exists($value,'__toString')) - || is_array($value) - ) { - $value = gettype($value); + if ('extra' == $name && count($value)) { + $value = $this->normalize($value); + } elseif ('extra' == $name) { + // Don't print an empty array + $value = ''; } - $output = str_replace("%$name%", $value, $output); } + if (isset($event['extra']) && empty($event['extra']) + && false !== strpos($this->format, '%extra%') + ) { + $output = rtrim($output, ' '); + } return $output; } - - /** - * {@inheritDoc} - */ - public function getDateTimeFormat() - { - return $this->dateTimeFormat; - } - - /** - * {@inheritDoc} - */ - public function setDateTimeFormat($dateTimeFormat) - { - $this->dateTimeFormat = (string) $dateTimeFormat; - return $this; - } } diff --git a/src/Formatter/Xml.php b/src/Formatter/Xml.php index d928a418..64bb6da2 100644 --- a/src/Formatter/Xml.php +++ b/src/Formatter/Xml.php @@ -153,6 +153,8 @@ public function format($event) ) { if ($key == "message") { $value = htmlspecialchars($value, ENT_COMPAT, $enc); + } elseif ($key == "extra" && empty($value)) { + continue; } $elt->appendChild(new DOMElement($key, (string)$value)); } diff --git a/src/Logger.php b/src/Logger.php index e8e7cdc2..e6b54814 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -172,7 +172,6 @@ public function addWriter($writer, $priority = 1, array $options = null) is_object($writer) ? get_class($writer) : gettype($writer) )); } - $this->writers->insert($writer, $priority); return $this; @@ -426,7 +425,7 @@ public static function registerExceptionHandler(Logger $logger) throw new Exception\InvalidArgumentException('Invalid Logger specified'); } - set_exception_handler(function ($exception) use ($logger){ + set_exception_handler(function ($exception) use ($logger) { $extra = array( 'file' => $exception->getFile(), 'line' => $exception->getLine(), diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index 12e77aba..dd59f398 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -150,7 +150,7 @@ public function setFormatter(Formatter $formatter) } /** - * Perform shutdown activites such as closing open resources + * Perform shutdown activities such as closing open resources * * @return void */ diff --git a/src/Writer/Db.php b/src/Writer/Db.php index 99e141b0..0d35606e 100644 --- a/src/Writer/Db.php +++ b/src/Writer/Db.php @@ -14,6 +14,7 @@ use Zend\Db\Adapter\Adapter; use Zend\Log\Exception; use Zend\Log\Formatter; +use Zend\Log\Formatter\Db as DbFormatter; /** * @category Zend @@ -62,7 +63,7 @@ class Db extends AbstractWriter * @return Db * @throw Exception\InvalidArgumentException */ - public function __construct($db, $tableName, array $columnMap = null, $separator = null) + public function __construct($db, $tableName = null, array $columnMap = null, $separator = null) { if ($db instanceof Traversable) { $db = iterator_to_array($db); @@ -79,6 +80,11 @@ public function __construct($db, $tableName, array $columnMap = null, $separator throw new Exception\InvalidArgumentException('You must pass a valid Zend\Db\Adapter\Adapter'); } + $tableName = (string) $tableName; + if ('' === $tableName){ + throw new Exception\InvalidArgumentException('You must specify a table name. Either directly in the constructor, or via options'); + } + $this->db = $db; $this->tableName = $tableName; $this->columnMap = $columnMap; @@ -86,18 +92,8 @@ public function __construct($db, $tableName, array $columnMap = null, $separator if (!empty($separator)) { $this->separator = $separator; } - } - /** - * Formatting is not possible on this writer - * - * @param Formatter\FormatterInterface $formatter - * @return void - * @throws Exception\InvalidArgumentException - */ - public function setFormatter(Formatter\FormatterInterface $formatter) - { - throw new Exception\InvalidArgumentException(get_class() . ' does not support formatting'); + $this->setFormatter(new DbFormatter()); } /** @@ -123,6 +119,8 @@ protected function doWrite(array $event) throw new Exception\RuntimeException('Database adapter is null'); } + $event = $this->formatter->format($event); + // Transform the event array into fields if (null === $this->columnMap) { $dataToInsert = $this->eventIntoColumn($event); diff --git a/src/Writer/FirePhp.php b/src/Writer/FirePhp.php index 66d2d70d..a96de9aa 100644 --- a/src/Writer/FirePhp.php +++ b/src/Writer/FirePhp.php @@ -22,7 +22,7 @@ class FirePhp extends AbstractWriter { /** - * The instance of FirePhp that is used to log messages to. + * A FirePhpInterface instance that is used to log messages to. * * @var FirePhp\FirePhpInterface */ @@ -48,7 +48,9 @@ public function __construct(FirePhp\FirePhpInterface $instance = null) */ protected function doWrite(array $event) { - if (!$this->firephp->getEnabled()) { + $firephp = $this->getFirePhp(); + + if (!$firephp->getEnabled()) { return; } @@ -59,26 +61,26 @@ protected function doWrite(array $event) case Logger::ALERT: case Logger::CRIT: case Logger::ERR: - $this->firephp->error($line); + $firephp->error($line); break; case Logger::WARN: - $this->firephp->warn($line); + $firephp->warn($line); break; case Logger::NOTICE: case Logger::INFO: - $this->firephp->info($line); + $firephp->info($line); break; case Logger::DEBUG: - $this->firephp->trace($line); + $firephp->trace($line); break; default: - $this->firephp->log($line); + $firephp->log($line); break; } } /** - * Gets the FirePhp instance that is used for logging. + * Gets the FirePhpInterface instance that is used for logging. * * @return FirePhp\FirePhpInterface */ @@ -97,9 +99,9 @@ public function getFirePhp() } /** - * Sets the FirePhp instance that is used for logging. + * Sets the FirePhpInterface instance that is used for logging. * - * @param FirePhp\FirePhpInterface $instance The FirePhp instance to set. + * @param FirePhp\FirePhpInterface $instance A FirePhpInterface instance to set. * @return FirePhp */ public function setFirePhp(FirePhp\FirePhpInterface $instance) diff --git a/src/Writer/FirePhp/FirePhpBridge.php b/src/Writer/FirePhp/FirePhpBridge.php index e08d269b..806c81d3 100644 --- a/src/Writer/FirePhp/FirePhpBridge.php +++ b/src/Writer/FirePhp/FirePhpBridge.php @@ -21,6 +21,7 @@ class FirePhpBridge implements FirePhpInterface { /** * FirePHP instance + * * @var FirePHP */ protected $firephp; diff --git a/src/Writer/FirePhp/FirePhpInterface.php b/src/Writer/FirePhp/FirePhpInterface.php index 6acd370a..23cf4b9d 100644 --- a/src/Writer/FirePhp/FirePhpInterface.php +++ b/src/Writer/FirePhp/FirePhpInterface.php @@ -17,10 +17,45 @@ */ interface FirePhpInterface { + /** + * Determine whether or not FirePHP is enabled + * + * @return bool + */ public function getEnabled(); + + /** + * Log an error message + * + * @param string $line + */ public function error($line); + + /** + * Log a warning + * + * @param string $line + */ public function warn($line); + + /** + * Log informational message + * + * @param string $line + */ public function info($line); + + /** + * Log a trace + * + * @param string $line + */ public function trace($line); + + /** + * Log a message + * + * @param string $line + */ public function log($line); } diff --git a/src/Writer/Mail.php b/src/Writer/Mail.php index 1bbfe17d..d34a7410 100644 --- a/src/Writer/Mail.php +++ b/src/Writer/Mail.php @@ -91,10 +91,10 @@ public function __construct($mail, Transport\TransportInterface $transport = nul // Ensure we have a valid mail message if (!$mail instanceof MailMessage) { - throw new Exception\InvalidArgumentException( + throw new Exception\InvalidArgumentException(sprintf( 'Mail parameter of type %s is invalid; must be of type Zend\Mail\Message', (is_object($mail) ? get_class($mail) : gettype($mail)) - ); + )); } $this->mail = $mail; @@ -103,10 +103,10 @@ public function __construct($mail, Transport\TransportInterface $transport = nul $transport = new Transport\Sendmail(); } if (!$transport instanceof Transport\TransportInterface) { - throw new Exception\InvalidArgumentException( + throw new Exception\InvalidArgumentException(sprintf( 'Transport parameter of type %s is invalid; must be of type Zend\Mail\Transport\TransportInterface', (is_object($transport) ? get_class($transport) : gettype($transport)) - ); + )); } $this->setTransport($transport); diff --git a/src/Writer/MongoDB.php b/src/Writer/MongoDB.php index 306e015c..f9cae3dc 100644 --- a/src/Writer/MongoDB.php +++ b/src/Writer/MongoDB.php @@ -47,10 +47,9 @@ class MongoDB extends AbstractWriter * Constructor * * @param Mongo|array|Traversable $mongo - * @param string $database + * @param string|MongoDB $database * @param string $collection - * @param array $saveOptions - * @return Zend\Log\Writer\MongoDB + * @param array $saveOptions */ public function __construct($mongo, $database, $collection, array $saveOptions = array()) { @@ -63,13 +62,13 @@ public function __construct($mongo, $database, $collection, array $saveOptions = $collection = isset($mongo['collection']) ? $mongo['collection'] : null; if (null === $collection) { throw new Exception\InvalidArgumentException( - 'The collection parameter cannot be emtpy' + 'The collection parameter cannot be empty' ); } $database = isset($mongo['database']) ? $mongo['database'] : null; if (null === $database) { throw new Exception\InvalidArgumentException( - 'The database parameter cannot be emtpy' + 'The database parameter cannot be empty' ); } $mongo = isset($mongo['mongo']) ? $mongo['mongo'] : null; diff --git a/src/Writer/Stream.php b/src/Writer/Stream.php index dd5e18b3..c5db6d1a 100644 --- a/src/Writer/Stream.php +++ b/src/Writer/Stream.php @@ -80,12 +80,15 @@ public function __construct($streamOrUrl, $mode = null, $logSeparator = null) $this->stream = $streamOrUrl; } else { - if (!$this->stream = @fopen($streamOrUrl, $mode, false)) { + ErrorHandler::start(); + $this->stream = fopen($streamOrUrl, $mode, false); + $error = ErrorHandler::stop(); + if (!$this->stream) { throw new Exception\RuntimeException(sprintf( '"%s" cannot be opened with mode "%s"', $streamOrUrl, $mode - )); + ), 0, $error); } } @@ -109,9 +112,9 @@ protected function doWrite(array $event) ErrorHandler::start(E_WARNING); $result = fwrite($this->stream, $line); - ErrorHandler::stop(); + $error = ErrorHandler::stop(); if (false === $result) { - throw new Exception\RuntimeException("Unable to write to stream"); + throw new Exception\RuntimeException("Unable to write to stream", 0, $error); } } diff --git a/src/Writer/Syslog.php b/src/Writer/Syslog.php index 2db625c0..aebf4fdc 100644 --- a/src/Writer/Syslog.php +++ b/src/Writer/Syslog.php @@ -11,8 +11,8 @@ namespace Zend\Log\Writer; use Zend\Log\Exception; -use Zend\Log\Formatter; use Zend\Log\Logger; +use Zend\Log\Formatter\Simple as SimpleFormatter; /** * Writes log messages to syslog @@ -102,6 +102,8 @@ public function __construct(array $params = array()) if ($runInitializeSyslog) { $this->initializeSyslog(); } + + $this->setFormatter(new SimpleFormatter('%message%')); } /** @@ -235,11 +237,7 @@ protected function doWrite(array $event) $this->initializeSyslog(); } - if ($this->formatter instanceof Formatter) { - $message = $this->formatter->format($event); - } else { - $message = $event['message']; - } + $message = $this->formatter->format($event); syslog($priority, $message); } diff --git a/test/Formatter/BaseTest.php b/test/Formatter/BaseTest.php new file mode 100644 index 00000000..d5d5f8a5 --- /dev/null +++ b/test/Formatter/BaseTest.php @@ -0,0 +1,113 @@ +assertEquals(BaseFormatter::DEFAULT_DATETIME_FORMAT, $formatter->getDateTimeFormat()); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testAllowsSpecifyingDateTimeFormatAsConstructorArgument($dateTimeFormat) + { + $formatter = new BaseFormatter($dateTimeFormat); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + } + + /** + * @return array + */ + public function provideDateTimeFormats() + { + return array( + array('r'), + array('U'), + array(DateTime::RSS), + ); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormat($dateTimeFormat) + { + $formatter = new BaseFormatter(); + $formatter->setDateTimeFormat($dateTimeFormat); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + } + + public function testFormatAllTypes() + { + $datetime = new DateTime(); + $object = new stdClass(); + $object->foo = 'bar'; + $formatter = new BaseFormatter(); + + $event = array( + 'timestamp' => $datetime, + 'priority' => 1, + 'message' => 'tottakai', + 'extra' => array( + 'float' => 0.2, + 'boolean' => false, + 'array_empty' => array(), + 'array' => range(0, 4), + 'traversable_empty' => new EmptyIterator(), + 'traversable' => new ArrayIterator(array('id', 42)), + 'null' => null, + 'object_empty' => new stdClass(), + 'object' => $object, + 'string object' => new StringObject(), + 'resource' => fopen('php://stdout', 'w'), + ), + ); + $outputExpected = array( + 'timestamp' => $datetime->format($formatter->getDateTimeFormat()), + 'priority' => 1, + 'message' => 'tottakai', + 'extra' => array( + 'boolean' => false, + 'float' => 0.2, + 'array_empty' => '[]', + 'array' => '[0,1,2,3,4]', + 'traversable_empty' => '[]', + 'traversable' => '["id",42]', + 'null' => null, + 'object_empty' => 'object(stdClass) {}', + 'object' => 'object(stdClass) {"foo":"bar"}', + 'string object' => 'Hello World', + 'resource' => 'resource(stream)', + ), + ); + + $this->assertEquals($outputExpected, $formatter->format($event)); + } +} diff --git a/test/Formatter/DbTest.php b/test/Formatter/DbTest.php new file mode 100644 index 00000000..b1de2ee2 --- /dev/null +++ b/test/Formatter/DbTest.php @@ -0,0 +1,73 @@ +assertEquals(DbFormatter::DEFAULT_DATETIME_FORMAT, $formatter->getDateTimeFormat()); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testSetDateTimeFormat($dateTimeFormat) + { + $formatter = new DbFormatter(); + $formatter->setDateTimeFormat($dateTimeFormat); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + } + + /** + * @return array + */ + public function provideDateTimeFormats() + { + return array( + array('r'), + array('U'), + array(DateTime::RSS), + ); + } + + /** + * @dataProvider provideDateTimeFormats + */ + public function testAllowsSpecifyingDateTimeFormatAsConstructorArgument($dateTimeFormat) + { + $formatter = new DbFormatter($dateTimeFormat); + + $this->assertEquals($dateTimeFormat, $formatter->getDateTimeFormat()); + } + + public function testFormatDateTimeInEvent() + { + $datetime = new DateTime(); + $event = array('timestamp' => $datetime); + $formatter = new DbFormatter(); + + $format = DbFormatter::DEFAULT_DATETIME_FORMAT; + $this->assertContains($datetime->format($format), $formatter->format($event)); + } +} diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php index 8db4f10a..18fe0f62 100644 --- a/test/Formatter/SimpleTest.php +++ b/test/Formatter/SimpleTest.php @@ -13,6 +13,8 @@ use DateTime; use ZendTest\Log\TestAsset\StringObject; use Zend\Log\Formatter\Simple; +use stdClass; +use RuntimeException; /** * @category Zend @@ -30,61 +32,19 @@ public function testConstructorThrowsOnBadFormatString() 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); + $date = new DateTime('2012-08-28T18:15:00Z'); + $fields = array( + 'timestamp' => $date, + 'message' => 'foo', + 'priority' => 42, + 'priorityName' => 'bar', + 'extra' => array() + ); - $fields['message'] = new StringObject(); - $line = $f->format($fields); - $this->assertContains($fields['message']->__toString(), $line); + $outputExpected = '2012-08-28T18:15:00+00:00 bar (42): foo'; + $formatter = new Simple(); - $fields['message'] = new \stdClass(); - $line = $f->format($fields); - $this->assertContains('object', $line); + $this->assertEquals($outputExpected, $formatter->format($fields)); } /** @@ -127,13 +87,13 @@ public function provideDateTimeFormats() public function testDefaultFormatShouldDisplayExtraInformations() { $message = 'custom message'; - $exception = new \RuntimeException($message); + $exception = new RuntimeException($message); $event = array( 'timestamp' => new DateTime(), 'message' => 'Application error', 'priority' => 2, 'priorityName' => 'CRIT', - 'info' => $exception, + 'extra' => array($exception), ); $formatter = new Simple(); @@ -141,4 +101,11 @@ public function testDefaultFormatShouldDisplayExtraInformations() $this->assertContains($message, $output); } + + public function testAllowsSpecifyingFormatAsConstructorArgument() + { + $format = '[%timestamp%] %message%'; + $formatter = new Simple($format); + $this->assertEquals($format, $formatter->format(array())); + } } diff --git a/test/Formatter/XmlTest.php b/test/Formatter/XmlTest.php index dc58a41c..660aeaee 100644 --- a/test/Formatter/XmlTest.php +++ b/test/Formatter/XmlTest.php @@ -178,4 +178,23 @@ public function testObjectsWithStringSerializationAreIncludedInFormattedString() $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/Writer/DbTest.php b/test/Writer/DbTest.php index 789df5e5..65d68230 100644 --- a/test/Writer/DbTest.php +++ b/test/Writer/DbTest.php @@ -10,11 +10,11 @@ namespace ZendTest\Log\Writer; +use DateTime; use ZendTest\Log\TestAsset\MockDbAdapter; use ZendTest\Log\TestAsset\MockDbDriver; use Zend\Log\Writer\Db as DbWriter; -use Zend\Log\Logger; -use Zend\Log\Formatter\Simple as SimpleFormatter; +use Zend\Log\Formatter\FormatterInterface; /** * @category Zend @@ -32,10 +32,27 @@ public function setUp() $this->writer = new DbWriter($this->db, $this->tableName); } - public function testFormattingIsNotSupported() + public function testNotPassingTableNameToConstructorThrowsException() { - $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'does not support formatting'); - $this->writer->setFormatter(new SimpleFormatter); + $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() @@ -189,4 +206,36 @@ public function testThrowStrictSetFormatter() $this->setExpectedException('PHPUnit_Framework_Error'); $this->writer->setFormatter(new \StdClass()); } + + public function testWriteDateTimeAsTimestamp() + { + $date = new DateTime(); + $event = array('timestamp'=> $date); + $this->writer->write($event); + + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + + $this->assertEquals(array(array( + 'timestamp' => $date->format(FormatterInterface::DEFAULT_DATETIME_FORMAT) + )), $this->db->calls['execute'][0]); + } + + public function testWriteDateTimeAsExtraValue() + { + $date = new DateTime(); + $event = array( + 'extra'=> array( + 'request_time' => $date + ) + ); + $this->writer->write($event); + + $this->assertContains('query', array_keys($this->db->calls)); + $this->assertEquals(1, count($this->db->calls['query'])); + + $this->assertEquals(array(array( + 'extra_request_time' => $date->format(FormatterInterface::DEFAULT_DATETIME_FORMAT) + )), $this->db->calls['execute'][0]); + } }