Completed
Push — master ( f44af3...a50383 )
by Kévin
8s
created

ObjectNormalizer::denormalize()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 17
rs 8.2222
cc 7
eloc 9
nc 3
nop 4
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 Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
13
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
14
use Symfony\Component\Serializer\SerializerAwareInterface;
15
use Symfony\Component\Serializer\SerializerInterface;
16
17
/**
18
 * Transforms an object to an array with the following keys:
19
 * * _type: the class name
20
 * * _value: a representation of the values of the object.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 */
24
final class ObjectNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
25
{
26
    /**
27
     * @var SerializerInterface
28
     */
29
    private $serializer;
30
    private $objectNormalizer;
31
32
    public function __construct(NormalizerInterface $objectNormalizer)
33
    {
34
        if (!$objectNormalizer instanceof DenormalizerInterface) {
35
            throw new \InvalidArgumentException(sprintf('The normalizer used must implement the "%s" interface.', DenormalizerInterface::class));
36
        }
37
38
        $this->objectNormalizer = $objectNormalizer;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function normalize($object, $format = null, array $context = [])
45
    {
46
        return [
47
            '_type' => get_class($object),
48
            '_value' => $this->objectNormalizer->normalize($object, $format, $context),
49
        ];
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function supportsNormalization($data, $format = null)
56
    {
57
        return is_object($data);
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function denormalize($data, $class, $format = null, array $context = [])
64
    {
65
        if (isset($data['_value']) && isset($data['_type']) && is_array($data['_value'])) {
66
            $data['_value'] = $this->denormalize($data['_value'], $data['_type'], $format, $context);
67
            $data = $this->objectNormalizer->denormalize($data['_value'], $data['_type'], $format, $context);
68
69
            return $data;
70
        }
71
72
        if (is_array($data) || $data instanceof \Traversable) {
73
            foreach ($data as $key => $value) {
74
                $data[$key] = $this->serializer->denormalize($value, $class, $format, $context);
0 ignored issues
show
Bug introduced by Kévin Dunglas
It seems like you code against a concrete implementation and not the interface Symfony\Component\Serializer\SerializerInterface as the method denormalize() does only exist in the following implementations of said interface: Symfony\Component\Serializer\Serializer.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
75
            }
76
        }
77
78
        return $data;
0 ignored issues
show
Bug Best Practice introduced by Kévin Dunglas
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...
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function supportsDenormalization($data, $type, $format = null)
85
    {
86
        return true;
87
    }
88
89
    /**
90
     * {@inheritdoc}
91
     */
92
    public function setSerializer(SerializerInterface $serializer)
93
    {
94
        $this->serializer = $serializer;
95
96
        if ($this->objectNormalizer instanceof SerializerAwareInterface) {
97
            $this->objectNormalizer->setSerializer($serializer);
98
        }
99
    }
100
}
101