Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection: added option [result][formatJson] that sets json column decoding (string|object|array) #335

Merged
merged 1 commit into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Dibi/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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']);
}


Expand Down
6 changes: 5 additions & 1 deletion src/Dibi/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
}
}
Expand Down