TraversableNormalizer::denormalize()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 3
rs 10
1
<?php
2
3
namespace Bdf\Serializer\Normalizer;
4
5
use Bdf\Serializer\Context\DenormalizationContext;
6
use Bdf\Serializer\Context\NormalizationContext;
7
use Bdf\Serializer\Type\Type;
8
use Bdf\Serializer\Type\TypeFactory;
9
use Traversable;
10
11
/**
12
 * TraversableNormalizer
13
 *
14
 * @implements NormalizerInterface<Traversable>
15
 */
16
class TraversableNormalizer implements NormalizerInterface
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21 4
    public function normalize($data, NormalizationContext $context)
22
    {
23 4
        $normalized = [];
24
25 4
        foreach ($data as $key => $value) {
26 4
            $normalized[$key] = $context->root()->normalize($value, $context);
27
        }
28
29 4
        return $normalized;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 6
    public function denormalize($data, Type $type, DenormalizationContext $context)
36
    {
37 6
        $className = $type->name();
38
        /** @var \ArrayAccess&Traversable $denormalized */
39 6
        $denormalized = new $className();
40
41 6
        foreach ((array)$data as $key => $value) {
42 6
            $denormalized[$key] = $context->root()->denormalize(
43 6
                $value,
44 6
                $type->isParametrized() ? $type->subType() : TypeFactory::mixedType(),
45 6
                $context
46 6
            );
47
        }
48
49 6
        return $denormalized;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $denormalized returns the type ArrayAccess&Traversable which is incompatible with the return type mandated by Bdf\Serializer\Normalize...nterface::denormalize() of Bdf\Serializer\Normalizer\T.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 164
    public function supports(string $className): bool
56
    {
57 164
        return is_subclass_of($className, Traversable::class);
58
    }
59
}
60