-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializedType.php
82 lines (69 loc) · 1.75 KB
/
SerializedType.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
73
74
75
76
77
78
79
80
81
82
<?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 function json_decode;
use function json_last_error;
use function json_last_error_msg;
use function quoted_printable_decode;
use function serialize;
use function unserialize;
/**
* Class ClassConservativeType
*
* Serialization and deserialization of values from DB.
*/
class SerializedType implements FlatInterface
{
/**
* @param mixed $value
*
* @return mixed
*
* @throws RuntimeException
*/
public static function convertToPhpValue(mixed $value): mixed
{
if ($value === null || $value === '') {
return null;
}
if (is_resource($value) === true) {
$value = stream_get_contents($value);
}
$value = (string)$value;
/**
* @var array $val
*/
$val = unserialize(
quoted_printable_decode((string)json_decode($value, true)),
['allowed_classes' => true]
);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(json_last_error_msg());
}
return $val;
}
/**
* @param mixed $value
*
* @return mixed
*
* @throws RuntimeException
*/
public static function convertToDatabaseValue(mixed $value): mixed
{
if ($value === null) {
return null;
}
$encoded = json_encode(quoted_printable_encode(serialize($value)));
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(json_last_error_msg());
}
return $encoded;
}
}