-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonType.php
70 lines (59 loc) · 1.47 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
<?php
/**
* PHP version 8.1
*
* @package Saschati\ValueObject\Types\Specials
*/
namespace Saschati\ValueObject\Types\Flats;
use RuntimeException;
use Saschati\ValueObject\Types\Flats\Interfaces\FlatInterface;
use yii\db\Expression;
use function is_array;
use function json_decode;
use function json_encode;
use function json_last_error;
use function json_last_error_msg;
/**
* Class JsonType
*
* Converting a value to an array from JSON.
*/
class JsonType implements FlatInterface
{
/**
* @param mixed $value
*
* @return array|null
*
* @throws RuntimeException
*/
public static function convertToPhpValue(mixed $value): ?array
{
if ($value === null) {
return null;
}
$value = (is_array($value) === true) ? $value : json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(json_last_error_msg());
}
return $value;
}
/**
* @param mixed $value
*
* @return Expression|null
*
* @throws RuntimeException
*/
public static function convertToDatabaseValue(mixed $value): ?Expression
{
if ($value === null) {
return null;
}
$encoded = json_encode($value, JSON_UNESCAPED_UNICODE);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(json_last_error_msg());
}
return new Expression("'{$encoded}'");
}
}