Test Failed
Pull Request — master (#11)
by Pavel
07:46
created

RelationsHandler::deserializeIdentifier()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
namespace Bankiru\Api\JsonRpc\Adapters\JMS;
4
5
use Doctrine\Common\Persistence\ObjectManager;
6
use Doctrine\ORM\Mapping\ClassMetadata;
7
use JMS\Serializer\JsonDeserializationVisitor;
8
use JMS\Serializer\JsonSerializationVisitor;
9
10
final class RelationsHandler
11
{
12
    /**
13
     * @var ObjectManager
14
     */
15
    private $manager;
16
17
    /**
18
     * RelationsHandler constructor.
19
     *
20
     * @param ObjectManager $manager
21
     */
22
    public function __construct(ObjectManager $manager)
23
    {
24
        $this->manager = $manager;
25
    }
26
27
    public function serializeRelation(JsonSerializationVisitor $visitor, $relation)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
28
    {
29
        if ($relation instanceof \Traversable) {
30
            $relation = iterator_to_array($relation);
31
        }
32
33
        if (is_array($relation)) {
34
            return array_map([$this, 'getSingleEntityRelation'], $relation);
35
        }
36
37
        return $this->getSingleEntityRelation($relation);
38
    }
39
40
    public function deserializeRelation(JsonDeserializationVisitor $visitor, $relation, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
41
    {
42
        $className = isset($type['params'][0]['name']) ? $type['params'][0]['name'] : null;
43
44
        if (!class_exists($className)) {
45
            throw new \InvalidArgumentException('Class name should be explicitly set for deserialization');
46
        }
47
48
        /** @var ClassMetadata $metadata */
49
        $metadata = $this->manager->getClassMetadata($className);
50
51
        if (!is_array($relation)) {
52
            return $this->deserializeIdentifier($className, $relation);
53
        }
54
55
        $single = false;
56
        if ($metadata->isIdentifierComposite) {
57
            $single = true;
58
            foreach ($metadata->getIdentifierFieldNames() as $idName) {
59
                $single = $single && array_key_exists($idName, $relation);
60
            }
61
        }
62
63
        if ($single) {
64
            return $this->deserializeIdentifier($className, $relation);
65
        }
66
67
        $objects = [];
68
        foreach ($relation as $idSet) {
69
            $objects[] = $this->deserializeIdentifier($className, $idSet);
70
        }
71
72
        return $objects;
73
    }
74
75
    /**
76
     * @param $relation
77
     *
78
     * @return array|mixed
79
     */
80
    private function getSingleEntityRelation($relation)
81
    {
82
        $metadata = $this->manager->getClassMetadata(get_class($relation));
83
84
        $ids = $metadata->getIdentifierValues($relation);
85
        if (1 === count($metadata->getIdentifierFieldNames())) {
86
            $ids = array_shift($ids);
87
        }
88
89
        return $ids;
90
    }
91
92
    /**
93
     * @param string $className
94
     * @param mixed  $identifier
95
     *
96
     * @return object
97
     */
98
    private function deserializeIdentifier($className, $identifier)
99
    {
100
        if (method_exists($this->manager, 'getReference')) {
101
            return $this->manager->getReference($className, $identifier);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\Common\Persistence\ObjectManager as the method getReference() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager.

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...
102
        }
103
104
        return $this->manager->find($className, $identifier);
105
    }
106
}
107