Jelajahi Sumber

Max depth formatter (#1633)

Geoffrey 3 tahun lalu
induk
melakukan
09769e4238

+ 5 - 3
src/Monolog/Formatter/JsonFormatter.php

@@ -38,9 +38,11 @@ class JsonFormatter extends NormalizerFormatter
     /**
      * @param int $batchMode
      * @param bool $appendNewline
+     * @param int $maxDepth
      */
-    public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true)
+    public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true, $maxDepth = 9)
     {
+        parent::__construct(null, $maxDepth);
         $this->batchMode = $batchMode;
         $this->appendNewline = $appendNewline;
     }
@@ -141,8 +143,8 @@ class JsonFormatter extends NormalizerFormatter
      */
     protected function normalize($data, $depth = 0)
     {
-        if ($depth > 9) {
-            return 'Over 9 levels deep, aborting normalization';
+        if ($depth > $this->maxDepth) {
+            return 'Over '.$this->maxDepth.' levels deep, aborting normalization';
         }
 
         if (is_array($data)) {

+ 23 - 4
src/Monolog/Formatter/NormalizerFormatter.php

@@ -24,13 +24,16 @@ class NormalizerFormatter implements FormatterInterface
     const SIMPLE_DATE = "Y-m-d H:i:s";
 
     protected $dateFormat;
+    protected $maxDepth;
 
     /**
      * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
+     * @param int $maxDepth
      */
-    public function __construct($dateFormat = null)
+    public function __construct($dateFormat = null, $maxDepth = 9)
     {
         $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
+        $this->maxDepth = $maxDepth;
         if (!function_exists('json_encode')) {
             throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
         }
@@ -56,10 +59,26 @@ class NormalizerFormatter implements FormatterInterface
         return $records;
     }
 
+    /**
+     * @return int
+     */
+    public function getMaxDepth()
+    {
+        return $this->maxDepth;
+    }
+
+    /**
+     * @param int $maxDepth
+     */
+    public function setMaxDepth($maxDepth)
+    {
+        $this->maxDepth = $maxDepth;
+    }
+
     protected function normalize($data, $depth = 0)
     {
-        if ($depth > 9) {
-            return 'Over 9 levels deep, aborting normalization';
+        if ($depth > $this->maxDepth) {
+            return 'Over '.$this->maxDepth.' levels deep, aborting normalization';
         }
 
         if (null === $data || is_scalar($data)) {
@@ -177,4 +196,4 @@ class NormalizerFormatter implements FormatterInterface
     {
         return Utils::jsonEncode($data, null, $ignoreErrors);
     }
-}
+}