Explorar o código

Check if monolog runs in web context (#1024)

* Check if monolog runs in web context
Pascal %!s(int64=7) %!d(string=hai) anos
pai
achega
5bb1c5fb4f

+ 11 - 0
src/Monolog/Handler/ChromePHPHandler.php

@@ -24,6 +24,9 @@ use Monolog\Logger;
  */
 class ChromePHPHandler extends AbstractProcessingHandler
 {
+
+    use WebRequestRecognizerTrait;
+
     /**
      * Version of the extension
      */
@@ -75,6 +78,10 @@ class ChromePHPHandler extends AbstractProcessingHandler
      */
     public function handleBatch(array $records)
     {
+        if (!$this->isWebRequest()) {
+            return;
+        }
+
         $messages = [];
 
         foreach ($records as $record) {
@@ -108,6 +115,10 @@ class ChromePHPHandler extends AbstractProcessingHandler
      */
     protected function write(array $record)
     {
+        if (!$this->isWebRequest()) {
+            return;
+        }
+
         self::$json['rows'][] = $record['formatted'];
 
         $this->send();

+ 4 - 1
src/Monolog/Handler/FirePHPHandler.php

@@ -21,6 +21,9 @@ use Monolog\Formatter\FormatterInterface;
  */
 class FirePHPHandler extends AbstractProcessingHandler
 {
+
+    use WebRequestRecognizerTrait;
+
     /**
      * WildFire JSON header message format
      */
@@ -130,7 +133,7 @@ class FirePHPHandler extends AbstractProcessingHandler
      */
     protected function write(array $record)
     {
-        if (!self::$sendHeaders) {
+        if (!self::$sendHeaders || !$this->isWebRequest()) {
             return;
         }
 

+ 16 - 0
src/Monolog/Handler/WebRequestRecognizerTrait.php

@@ -0,0 +1,16 @@
+<?php declare(strict_types=1);
+
+namespace Monolog\Handler;
+
+trait WebRequestRecognizerTrait
+{
+
+    /**
+     * Checks if PHP's serving a web request
+     * @return bool
+     */
+    protected function isWebRequest(): bool
+    {
+        return 'cli' !== \PHP_SAPI && 'phpdbg' !== \PHP_SAPI;
+    }
+}

+ 5 - 0
tests/Monolog/Handler/ChromePHPHandlerTest.php

@@ -153,4 +153,9 @@ class TestChromePHPHandler extends ChromePHPHandler
     {
         return $this->headers;
     }
+
+    protected function isWebRequest(): bool
+    {
+        return true;
+    }
 }

+ 5 - 0
tests/Monolog/Handler/FirePHPHandlerTest.php

@@ -93,4 +93,9 @@ class TestFirePHPHandler extends FirePHPHandler
     {
         return $this->headers;
     }
+
+    protected function isWebRequest(): bool
+    {
+        return true;
+    }
 }