1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Serialization\Serializer\Field; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\Serialization\Accessor\AccessorInterface; |
8
|
|
|
use Chubbyphp\Serialization\SerializerInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface as Request; |
10
|
|
|
|
11
|
|
|
final class ValueFieldSerializer implements FieldSerializerInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var AccessorInterface |
15
|
|
|
*/ |
16
|
|
|
private $accessor; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string|null |
20
|
|
|
*/ |
21
|
|
|
private $cast; |
22
|
|
|
|
23
|
|
|
const CAST_BOOL = 'bool'; |
24
|
|
|
const CAST_FLOAT = 'float'; |
25
|
|
|
const CAST_INT = 'int'; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @param AccessorInterface $accessor |
29
|
|
|
* @param string $cast |
30
|
|
|
*/ |
31
|
6 |
|
public function __construct(AccessorInterface $accessor, string $cast = null) |
32
|
|
|
{ |
33
|
6 |
|
$this->accessor = $accessor; |
34
|
|
|
|
35
|
6 |
|
if (null !== $cast) { |
36
|
4 |
|
$supportedCasts = [self::CAST_BOOL, self::CAST_FLOAT, self::CAST_INT]; |
37
|
4 |
|
if (!in_array($cast, $supportedCasts, true)) { |
38
|
1 |
|
throw new \InvalidArgumentException( |
39
|
1 |
|
sprintf('Cast %s is not support, supported casts: %s', $cast, implode(', ', $supportedCasts)) |
40
|
|
|
); |
41
|
|
|
} |
42
|
3 |
|
$this->cast = $cast; |
43
|
|
|
} |
44
|
5 |
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* @param string $path |
48
|
|
|
* @param Request $request |
49
|
|
|
* @param object $object |
50
|
|
|
* @param SerializerInterface|null $serializer |
51
|
|
|
* |
52
|
|
|
* @return mixed |
53
|
|
|
*/ |
54
|
5 |
|
public function serializeField(string $path, Request $request, $object, SerializerInterface $serializer = null) |
55
|
|
|
{ |
56
|
5 |
|
return $this->castValue($this->accessor->getValue($object)); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param mixed $value |
61
|
|
|
* |
62
|
|
|
* @return mixed |
63
|
|
|
*/ |
64
|
5 |
|
private function castValue($value) |
65
|
|
|
{ |
66
|
5 |
|
if (is_array($value)) { |
67
|
1 |
|
$castedValue = []; |
68
|
1 |
|
foreach ($value as $key => $subValue) { |
69
|
1 |
|
$castedValue[$key] = $this->castValue($subValue); |
70
|
|
|
} |
71
|
|
|
|
72
|
1 |
|
return $castedValue; |
73
|
|
|
} |
74
|
|
|
|
75
|
5 |
|
if (null !== $value && null !== $this->cast) { |
76
|
3 |
|
switch ($this->cast) { |
77
|
3 |
|
case self::CAST_BOOL: |
78
|
1 |
|
return (bool) $value; |
79
|
2 |
|
case self::CAST_FLOAT: |
80
|
1 |
|
return (float) $value; |
81
|
1 |
|
case self::CAST_INT: |
82
|
1 |
|
return (int) $value; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|
86
|
2 |
|
return $value; |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|