From 388d4159cf32f02dc5420d7dbf6a991ba6576159 Mon Sep 17 00:00:00 2001 From: Pavel Janda Date: Mon, 9 Sep 2019 18:01:21 +0200 Subject: [PATCH] Connection: added option [result][formatJson] that sets json column decoding (text|object|array) --- src/Dibi/Connection.php | 9 ++++++++- src/Dibi/Result.php | 6 +++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Dibi/Connection.php b/src/Dibi/Connection.php index 6a12d7766..2efbf9cc6 100644 --- a/src/Dibi/Connection.php +++ b/src/Dibi/Connection.php @@ -43,6 +43,11 @@ class Connection implements IConnection * - lazy (bool) => if true, connection will be established only when required * - result (array) => result set options * - formatDateTime => date-time format (if empty, DateTime objects will be returned) + * - formatJson => json format ( + * "string" for leaving value as is, + * "object" for decoding json as \stdClass, + * "array" for decoding json as an array - default + * ) * - profiler (array) * - run (bool) => enable profiler? * - file => file to log @@ -59,6 +64,7 @@ public function __construct(array $config, string $name = null) Helpers::alias($config, 'result|formatDateTime', 'resultDateTime'); $config['driver'] = $config['driver'] ?? 'mysqli'; $config['name'] = $name; + $config['result']['formatJson'] = $config['result']['formatJson'] ?? 'array'; $this->config = $config; // profiler @@ -395,7 +401,8 @@ public function createResultSet(ResultDriver $resultDriver): Result { $res = new Result($resultDriver); return $res->setFormat(Type::DATE, $this->config['result']['formatDate']) - ->setFormat(Type::DATETIME, $this->config['result']['formatDateTime']); + ->setFormat(Type::DATETIME, $this->config['result']['formatDateTime']) + ->setFormat(Type::JSON, $this->config['result']['formatJson']); } diff --git a/src/Dibi/Result.php b/src/Dibi/Result.php index d612f5de1..38bad9a0a 100644 --- a/src/Dibi/Result.php +++ b/src/Dibi/Result.php @@ -496,7 +496,11 @@ private function normalize(array &$row): void $row[$key] = is_string($value) ? $this->getResultDriver()->unescapeBinary($value) : $value; } elseif ($type === Type::JSON) { - $row[$key] = json_decode($value, true); + if ($this->formats[$type] === 'string') { + $row[$key] = $value; + } else { + $row[$key] = json_decode($value, $this->formats[$type] === 'array'); + } } } }