Passed
Push — master ( 341743...0998b7 )
by Dominik
01:57
created

CollectionFieldSerializer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 1
dl 0
loc 48
ccs 0
cts 14
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A serializeField() 0 12 2
A serializerOrException() 0 6 2
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 CollectionFieldSerializer implements FieldSerializerInterface
12
{
13
    /**
14
     * @var AccessorInterface
15
     */
16
    private $accessor;
17
18
    /**
19
     * @param AccessorInterface $accessor
20
     */
21
    public function __construct(AccessorInterface $accessor)
22
    {
23
        $this->accessor = $accessor;
24
    }
25
26
    /**
27
     * @param string                   $path
28
     * @param Request                  $request
29
     * @param object                   $object
30
     * @param SerializerInterface|null $serializer
31
     *
32
     * @return mixed
33
     */
34
    public function serializeField(string $path, Request $request, $object, SerializerInterface $serializer = null)
35
    {
36
        $this->serializerOrException($serializer);
37
38
        $collection = [];
39
        foreach ($this->accessor->getValue($object) as $i => $childObject) {
40
            $subPath = $path.'.['.$i.']';
41
            $collection[$i] = $serializer->serialize($request, $childObject, $subPath);
0 ignored issues
show
Bug introduced by
It seems like $serializer is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
42
        }
43
44
        return $collection;
45
    }
46
47
    /**
48
     * @param SerializerInterface|null $serializer
49
     *
50
     * @throws \RuntimeException
51
     */
52
    private function serializerOrException(SerializerInterface $serializer = null)
53
    {
54
        if (null === $serializer) {
55
            throw new \RuntimeException(sprintf('Serializer needed: %s', SerializerInterface::class));
56
        }
57
    }
58
}
59