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

src/Normalizer/ObjectNormalizer.php (1 issue)

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 (isset($data['#type'])) {
64
            $type = $data['#type'];
65
            unset($data['#type']);
66
67
            $data = $this->denormalize($data, $type, $format, $context);
68
            $data = $this->objectNormalizer->denormalize($data, $type, $format, $context);
69
70
            return $data;
71
        }
72
73
        if (is_array($data) || $data instanceof \Traversable) {
74
            foreach ($data as $key => $value) {
75
                $data[$key] = $this->serializer->denormalize($value, $class, $format, $context);
76
            }
77
        }
78
79
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $data; (array|object|integer|double|string|null|boolean) 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...
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function supportsDenormalization($data, $type, $format = null)
86
    {
87
        return true;
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function setSerializer(SerializerInterface $serializer)
94
    {
95
        if (!$serializer instanceof NormalizerInterface || !$serializer instanceof DenormalizerInterface) {
96
            throw new \InvalidArgumentException(
97
                sprintf('The injected serializer must implement "%s" and "%s".', NormalizerInterface::class, DenormalizerInterface::class)
98
            );
99
        }
100
101
        $this->serializer = $serializer;
102
103
        if ($this->objectNormalizer instanceof SerializerAwareInterface) {
104
            $this->objectNormalizer->setSerializer($serializer);
105
        }
106
    }
107
}
108