Passed
Pull Request — master (#3)
by Igor
15:40
created

CollectionNormalizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
eloc 14
dl 0
loc 30
ccs 14
cts 14
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A denormalize() 0 13 2
A supportsDenormalization() 0 11 3
1
<?php
2
/*
3
 * This file is part of Goodwix Doctrine JSON ODM.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Goodwix\DoctrineJsonOdm\Serialization\RamseyCollection;
10
11
use Ramsey\Collection\CollectionInterface;
12
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
13
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareTrait;
14
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
15
16
class CollectionNormalizer implements DenormalizerInterface, DenormalizerAwareInterface
17
{
18
    use DenormalizerAwareTrait;
19
20 7
    public function supportsDenormalization($data, $type, $format = null): bool
21
    {
22 7
        $supports = false;
23
24 7
        if (class_exists($type)) {
25 6
            $reflectionClass = new \ReflectionClass($type);
26 6
            $inheritsClass   = $reflectionClass->isSubclassOf(CollectionInterface::class);
27 6
            $supports        = is_array($data) && $inheritsClass;
28
        }
29
30 7
        return $supports;
31
    }
32
33 2
    public function denormalize($data, $class, $format = null, array $context = []): CollectionInterface
34
    {
35
        /** @var CollectionInterface $collection */
36 2
        $collection = new $class();
37
38 2
        $itemType = $collection->getType();
39
40 2
        foreach ($data as $item) {
41 2
            $item = $this->denormalizer->denormalize($item, $itemType, $format, $context);
42 2
            $collection->add($item);
43
        }
44
45 2
        return $collection;
46
    }
47
}
48