Completed
Push — master ( 9640c3...f2881e )
by Dominik
02:05
created

ValueSerializer::__construct()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4.5435

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 4
cts 9
cp 0.4444
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 2
crap 4.5435
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 ValueSerializer 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 1
    public function __construct(AccessorInterface $accessor, string $cast = null)
32
    {
33 1
        $this->accessor = $accessor;
34
35 1
        if (null !== $cast) {
36
            $supportedCasts = [self::CAST_BOOL, self::CAST_FLOAT, self::CAST_INT];
37
            if (!in_array($cast, $supportedCasts, true)) {
38
                throw new \InvalidArgumentException(
39
                    sprintf('Cast %s is not support, supported casts: %s', $cast, implode(', ', $supportedCasts))
40
                );
41
            }
42
            $this->cast = $cast;
43
        }
44 1
    }
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 1
    public function serializeField(string $path, Request $request, $object, SerializerInterface $serializer = null)
55
    {
56 1
        $value = $this->accessor->getValue($object);
57
58 1
        if (null !== $this->cast) {
59
            switch ($this->cast) {
60
                case self::CAST_BOOL:
61
                    $value = (bool) $value;
62
                    break;
63
                case self::CAST_FLOAT:
64
                    $value = (float) $value;
65
                    break;
66
                case self::CAST_INT:
67
                    $value = (int) $value;
68
                    break;
69
            }
70
        }
71
72 1
        return $value;
73
    }
74
}
75