Completed
Push — master ( c2c0b4...47e138 )
by Kévin
10s
created

src/Normalizer/ObjectNormalizer.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * (c) Kévin Dunglas <[email protected]>
5
 *
6
 * This source file is subject to the MIT license that is bundled
7
 * with this source code in the file LICENSE.
8
 */
9
10
namespace Dunglas\DoctrineJsonOdm\Normalizer;
11
12
use Doctrine\Common\Util\ClassUtils;
13
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
14
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
15
use Symfony\Component\Serializer\SerializerAwareInterface;
16
use Symfony\Component\Serializer\SerializerInterface;
17
18
/**
19
 * Transforms an object to an array with the following keys:
20
 * * _type: the class name
21
 * * _value: a representation of the values of the object.
22
 *
23
 * @author Kévin Dunglas <[email protected]>
24
 */
25
final class ObjectNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
26
{
27
    /**
28
     * @var NormalizerInterface|DenormalizerInterface
29
     */
30
    private $serializer;
31
    private $objectNormalizer;
32
33
    public function __construct(NormalizerInterface $objectNormalizer)
34
    {
35
        if (!$objectNormalizer instanceof DenormalizerInterface) {
36
            throw new \InvalidArgumentException(sprintf('The normalizer used must implement the "%s" interface.', DenormalizerInterface::class));
37
        }
38
39
        $this->objectNormalizer = $objectNormalizer;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function normalize($object, $format = null, array $context = [])
46
    {
47
        return array_merge(['#type' => ClassUtils::getClass($object)], $this->objectNormalizer->normalize($object, $format, $context));
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function supportsNormalization($data, $format = null)
54
    {
55
        return is_object($data);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function denormalize($data, $class, $format = null, array $context = [])
62
    {
63
        if (is_object($data)) {
64
            return $data;
65
        }
66
67
        if (isset($data['#type'])) {
68
            $type = $data['#type'];
69
            unset($data['#type']);
70
71
            $data = $this->denormalize($data, $type, $format, $context);
72
            $data = $this->objectNormalizer->denormalize($data, $type, $format, $context);
73
74
            return $data;
75
        }
76
77
        if (is_array($data) || $data instanceof \Traversable) {
78
            foreach ($data as $key => $value) {
79
                $data[$key] = $this->serializer->denormalize($value, $class, $format, $context);
0 ignored issues
show
The method denormalize does only exist in Symfony\Component\Serial...r\DenormalizerInterface, but not in Symfony\Component\Serial...zer\NormalizerInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
80
            }
81
        }
82
83
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $data; (integer|double|string|boolean|resource|array) is incompatible with the return type declared by the interface Symfony\Component\Serial...rInterface::denormalize of type object.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function supportsDenormalization($data, $type, $format = null)
90
    {
91
        return true;
92
    }
93
94
    /**
95
     * {@inheritdoc}
96
     */
97
    public function setSerializer(SerializerInterface $serializer)
98
    {
99
        if (!$serializer instanceof NormalizerInterface || !$serializer instanceof DenormalizerInterface) {
100
            throw new \InvalidArgumentException(
101
                sprintf('The injected serializer must implement "%s" and "%s".', NormalizerInterface::class, DenormalizerInterface::class)
102
            );
103
        }
104
105
        $this->serializer = $serializer;
106
107
        if ($this->objectNormalizer instanceof SerializerAwareInterface) {
108
            $this->objectNormalizer->setSerializer($serializer);
109
        }
110
    }
111
}
112