|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Ecodev\Felix\DBAL\Types; |
|
6
|
|
|
|
|
7
|
|
|
use Doctrine\DBAL\Platforms\AbstractPlatform; |
|
8
|
|
|
use Doctrine\DBAL\Types\Exception\SerializationFailed; |
|
9
|
|
|
use Doctrine\DBAL\Types\Exception\ValueNotConvertible; |
|
10
|
|
|
use Doctrine\DBAL\Types\JsonType; |
|
11
|
|
|
use JsonException; |
|
12
|
|
|
|
|
13
|
|
|
/** |
|
14
|
|
|
* Type specialized to store localized data as JSON. |
|
15
|
|
|
* |
|
16
|
|
|
* PHP values are expected to be an array of localized values indexed by language. The array |
|
17
|
|
|
* might be empty, but it can never be null or empty string. |
|
18
|
|
|
* |
|
19
|
|
|
* DB values are constrained by the database, so they must always be valid JSON, such as the minimal data `{}`. |
|
20
|
|
|
*/ |
|
21
|
|
|
final class LocalizedType extends JsonType |
|
22
|
|
|
{ |
|
23
|
|
|
/** |
|
24
|
|
|
* @param null|string $value |
|
25
|
|
|
*/ |
|
26
|
3 |
|
public function convertToPHPValue(mixed $value, AbstractPlatform $platform): array |
|
27
|
|
|
{ |
|
28
|
3 |
|
if ($value === null || $value === '') { |
|
29
|
1 |
|
return []; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
3 |
|
$val = parent::convertToPHPValue($value, $platform); |
|
33
|
|
|
|
|
34
|
3 |
|
if (!is_array($val)) { |
|
35
|
1 |
|
throw ValueNotConvertible::new($value, 'json', 'value in DB is not a JSON encoded associative array'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
2 |
|
return $val; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
4 |
|
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): string |
|
42
|
|
|
{ |
|
43
|
4 |
|
if (!is_array($value)) { |
|
44
|
2 |
|
throw SerializationFailed::new($value, 'json', 'value must be a PHP array'); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
2 |
|
if (!$value) { |
|
48
|
1 |
|
return '{}'; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
try { |
|
52
|
2 |
|
return json_encode($value, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); |
|
53
|
|
|
} catch (JsonException $e) { |
|
54
|
|
|
throw SerializationFailed::new($value, 'json', $e->getMessage(), $e); |
|
55
|
|
|
} |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|