-
-
Notifications
You must be signed in to change notification settings - Fork 40
/
JsonTransformer.php
42 lines (36 loc) · 1.08 KB
/
JsonTransformer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php
declare(strict_types=1);
namespace MartinGeorgiev\Doctrine\DBAL\Types;
use Doctrine\DBAL\Types\ConversionException;
/**
* Helpers for converting PHP values into PostgreSql JSOn and vice versa.
*
* @since 0.1
*
* @author Martin Georgiev <martin.georgiev@gmail.com>
*/
trait JsonTransformer
{
/**
* @param mixed $phpValue Value must be suitable for JSON encoding
*
* @throws ConversionException When given value cannot be encoded
*/
protected function transformToPostgresJson(mixed $phpValue): string
{
try {
$postgresValue = \json_encode($phpValue, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
throw new ConversionException(\sprintf('Value %s can\'t be resolved to valid JSON', \var_export($phpValue, true)));
}
return $postgresValue;
}
/**
* @return array|float|int|string|null
*/
protected function transformFromPostgresJson(string $postgresValue)
{
// @phpstan-ignore-next-line
return \json_decode($postgresValue, true, 512, JSON_THROW_ON_ERROR);
}
}