Преглед изворни кода

Added Logger::setHandlers()

Logger::setHandlers() is intended to help dependency injection systems
that deal more elegantly with property setters than constructor
arguments. Alongside getHandlers(), pushHandler(), popHandler(), it is
a logical addition to the API.

It also attempts to address some possible errors in the format of the
data passed:

 - If a map is passed, the keys are removed, as these aren’t expected
   by Monolog
 - If falsey values are included, these are stripped

It relies on Logger::pushHandler() internally, so that if any special
behaviour is added in the future, this only needs to be added in one
place.
Sam Minnee пре 10 година
родитељ
комит
60c96cfa2a
2 измењених фајлова са 43 додато и 0 уклоњено
  1. 19 0
      src/Monolog/Logger.php
  2. 24 0
      tests/Monolog/LoggerTest.php

+ 19 - 0
src/Monolog/Logger.php

@@ -175,6 +175,25 @@ class Logger implements LoggerInterface
         return array_shift($this->handlers);
     }
 
+    /**
+     * Set handlers, removing all existing ones.
+     * Falsey values will be ignored, and if a map is passed, keys will be ignored.
+     *
+     * @param array $handlers All elements must be of type HandlerInterface
+     * @return $this
+     */
+    public function setHandlers(array $handlers)
+    {
+        $this->handlers = array();
+        foreach ($handlers as $handler) {
+            if ($handler) {
+                $this->pushHandler($handler);
+            }
+        }
+
+        return $this;
+    }
+
     /**
      * @return HandlerInterface[]
      */

+ 24 - 0
tests/Monolog/LoggerTest.php

@@ -139,6 +139,30 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
         $logger->popHandler();
     }
 
+    /**
+     * @covers Monolog\Logger::setHandlers
+     */
+    public function testSetHandlers()
+    {
+        $logger = new Logger(__METHOD__);
+        $handler1 = new TestHandler;
+        $handler2 = new TestHandler;
+
+        $logger->pushHandler($handler1);
+        $logger->setHandlers(array($handler2));
+
+        // handler1 has been removed
+        $this->assertEquals(array($handler2), $logger->getHandlers());
+
+        $logger->setHandlers(array(
+            "AMapKey" => $handler1,
+            "Falsey" => null,
+        ));
+
+        // Keys have been scrubbed
+        $this->assertEquals(array($handler1), $logger->getHandlers());
+    }
+
     /**
      * @covers Monolog\Logger::pushProcessor
      * @covers Monolog\Logger::popProcessor