Browse Source

LoggedQuery now implements JsonSerializable

ADmad 6 years ago
parent
commit
bd0e4a50f6
2 changed files with 47 additions and 1 deletions
  1. 28 1
      src/Database/Log/LoggedQuery.php
  2. 19 0
      tests/TestCase/Database/Log/LoggedQueryTest.php

+ 28 - 1
src/Database/Log/LoggedQuery.php

@@ -16,13 +16,15 @@ declare(strict_types=1);
  */
 namespace Cake\Database\Log;
 
+use JsonSerializable;
+
 /**
  * Contains a query string, the params used to executed it, time taken to do it
  * and the number of rows found or affected by its execution.
  *
  * @internal
  */
-class LoggedQuery
+class LoggedQuery implements JsonSerializable
 {
     /**
      * Query string that was executed
@@ -100,6 +102,31 @@ class LoggedQuery
     }
 
     /**
+     * Returns data that will be serialized as JSON
+     *
+     * @return array
+     */
+    public function jsonSerialize(): array
+    {
+        $error = $this->error;
+        if ($error !== null) {
+            $error = [
+                'class' => get_class($error),
+                'message' => $error->getMessage(),
+                'code' => $error->getCode(),
+            ];
+        }
+
+        return [
+            'query' => $this->query,
+            'numRows' => $this->numRows,
+            'params' => $this->params,
+            'took' => $this->took,
+            'error' => $error,
+        ];
+    }
+
+    /**
      * Returns the string representation of this logged query
      *
      * @return string

+ 19 - 0
tests/TestCase/Database/Log/LoggedQueryTest.php

@@ -110,4 +110,23 @@ class LoggedQueryTest extends TestCase
         $expected = "duration=0 rows=0 SELECT a FROM b where a = '\$2y\$10\$dUAIj' AND b = '\$0.23' AND c = 'a\\\\0b\\\\1c\\\\d' AND d = 'a''b'";
         $this->assertEquals($expected, (string)$query);
     }
+
+    public function testJsonSerialize()
+    {
+        $query = new LoggedQuery();
+        $query->query = 'SELECT a FROM b where a = :p1';
+        $query->params = ['p1' => '$2y$10$dUAIj'];
+        $query->numRows = 4;
+        $query->error = new \Exception('You fail!');
+
+        $expected = json_encode([
+            'query' => $query->query,
+            'numRows' => 4,
+            'params' => $query->params,
+            'took' => 0,
+            'error' => $query->error,
+        ]);
+
+        $this->assertEquals($expected, json_encode($query));
+    }
 }