forked from doctrine/dbal
-
Notifications
You must be signed in to change notification settings - Fork 1
/
JsonType.php
72 lines (59 loc) · 1.79 KB
/
JsonType.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
declare(strict_types=1);
namespace Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Exception\SerializationFailed;
use Doctrine\DBAL\Types\Exception\ValueNotConvertible;
use JsonException;
use function is_resource;
use function json_decode;
use function json_encode;
use function stream_get_contents;
use const JSON_PRESERVE_ZERO_FRACTION;
use const JSON_THROW_ON_ERROR;
/**
* Type generating json objects values
*/
class JsonType extends Type
{
/**
* {@inheritdoc}
*/
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
return $platform->getJsonTypeDeclarationSQL($column);
}
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string
{
if ($value === null) {
return null;
}
try {
return json_encode($value, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION);
} catch (JsonException $e) {
throw SerializationFailed::new($value, 'json', $e->getMessage(), $e);
}
}
public function convertToPHPValue(mixed $value, AbstractPlatform $platform): mixed
{
if ($value === null || $value === '') {
return null;
}
if (is_resource($value)) {
$value = stream_get_contents($value);
}
try {
return json_decode($value, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
throw ValueNotConvertible::new($value, $this->getName(), $e->getMessage(), $e);
}
}
public function getName(): string
{
return Types::JSON;
}
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return ! $platform->hasNativeJsonType();
}
}