Parcourir la source

Fix serializability of Logger class, fixes #1792

Jordi Boggiano il y a 2 ans
Parent
commit
2ae044482c
2 fichiers modifiés avec 37 ajouts et 1 suppressions
  1. 30 0
      src/Monolog/Logger.php
  2. 7 1
      tests/Monolog/LoggerTest.php

+ 30 - 0
src/Monolog/Logger.php

@@ -722,4 +722,34 @@ class Logger implements LoggerInterface, ResettableInterface
 
         ($this->exceptionHandler)($e, $record);
     }
+
+    public function __serialize(): array
+    {
+        return [
+            'name' => $this->name,
+            'handlers' => $this->handlers,
+            'processors' => $this->processors,
+            'microsecondTimestamps' => $this->microsecondTimestamps,
+            'timezone' => $this->timezone,
+            'exceptionHandler' => $this->exceptionHandler,
+            'logDepth' => $this->logDepth,
+            'detectCycles' => $this->detectCycles,
+        ];
+    }
+
+    public function __unserialize(array $data): void
+    {
+        foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) {
+            if (isset($data[$property])) {
+                $this->$property = $data;
+            }
+        }
+
+        if (\PHP_VERSION_ID >= 80100) {
+            // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412
+            /** @var \WeakMap<\Fiber, int> $fiberLogDepth */
+            $fiberLogDepth = new \WeakMap();
+            $this->fiberLogDepth = $fiberLogDepth;
+        }
+    }
 }

+ 7 - 1
tests/Monolog/LoggerTest.php

@@ -697,6 +697,12 @@ class LoggerTest extends \PHPUnit\Framework\TestCase
         $logger->info('test');
     }
 
+    public function testSerializable()
+    {
+        $logger = new Logger(__METHOD__);
+        self::assertInstanceOf(Logger::class, unserialize(serialize($logger)));
+    }
+
     public function testReset()
     {
         $logger = new Logger('app');
@@ -901,4 +907,4 @@ class FiberSuspendHandler implements HandlerInterface
     public function close(): void
     {
     }
-}
+}