Completed
Push — master ( ae7699...183a1b )
by Ivannis Suárez
02:08
created

EventListener::replacePersistentCollections()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 13
nc 5
nop 2
1
<?php
2
/**
3
 * This file is part of the Cubiche package.
4
 *
5
 * Copyright (c) Cubiche
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Cubiche\Infrastructure\Collections\Doctrine\ODM\MongoDB\EventListener;
12
13
use Cubiche\Core\Collections\CollectionInterface;
14
use Cubiche\Core\Metadata\PropertyMetadata;
15
use Cubiche\Infrastructure\Collections\Doctrine\ODM\MongoDB\Metadata\Driver\XmlDriver;
16
use Cubiche\Infrastructure\Doctrine\ODM\MongoDB\Event\RegisterDriverMetadataEventArgs;
17
use Cubiche\Infrastructure\Doctrine\ODM\MongoDB\Metadata\Exception\MappingException;
18
use Doctrine\Common\Collections\ArrayCollection as DoctrineArrayCollection;
19
use Doctrine\ODM\MongoDB\DocumentManager;
20
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
21
use Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs;
22
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
23
use Doctrine\ODM\MongoDB\PersistentCollection;
24
use Doctrine\ODM\MongoDB\Types\Type;
25
26
/**
27
 * EventListener class.
28
 *
29
 * @author Karel Osorio Ramírez <[email protected]>
30
 * @author Ivannis Suárez Jerez <[email protected]>
31
 */
32
class EventListener
33
{
34
    /**
35
     * @param RegisterDriverMetadataEventArgs $eventArgs
36
     */
37
    public function registerDriverMetadata(RegisterDriverMetadataEventArgs $eventArgs)
38
    {
39
        $eventArgs->driverFactory()->registerXmlDriver(XmlDriver::class);
40
    }
41
42
    /**
43
     * @param LifecycleEventArgs $eventArgs
44
     */
45
    public function prePersist(LifecycleEventArgs $eventArgs)
46
    {
47
        $this->replaceCollections($eventArgs->getDocument(), $eventArgs->getDocumentManager());
48
    }
49
50
    /**
51
     * @param LifecycleEventArgs $eventArgs
52
     */
53
    public function postPersist(LifecycleEventArgs $eventArgs)
54
    {
55
        $this->replacePersistentCollections($eventArgs->getDocument(), $eventArgs->getDocumentManager());
56
    }
57
58
    /**
59
     * @param LifecycleEventArgs $eventArgs
60
     */
61
    public function postLoad(LifecycleEventArgs $eventArgs)
62
    {
63
        $this->replacePersistentCollections($eventArgs->getDocument(), $eventArgs->getDocumentManager());
64
    }
65
66
    /**
67
     * @param LoadClassMetadataEventArgs $eventArgs
68
     */
69
    public function postLoadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
70
    {
71
        $this->checkArrayCollectionType($eventArgs->getClassMetadata());
0 ignored issues
show
Compatibility introduced by
$eventArgs->getClassMetadata() of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
72
    }
73
74
    /**
75
     * @param object          $document
76
     * @param DocumentManager $dm
77
     */
78
    protected function replaceCollections($document, DocumentManager $dm)
79
    {
80
        $classMetadata = $dm->getClassMetadata(\get_class($document));
81
        /** @var \ReflectionProperty $reflectionProperty */
82
        foreach ($classMetadata->getReflectionProperties() as $propertyName => $reflectionProperty) {
83
            $mapping = $classMetadata->getFieldMapping($propertyName);
84
            $value = $reflectionProperty->getValue($document);
85
86
            if ((isset($mapping['association']) && $mapping['type'] === 'many')
87
                && $value !== null && !($value instanceof PersistentCollection)
88
            ) {
89
                if ($value instanceof CollectionInterface) {
90
                    $value = new DoctrineArrayCollection($value->toArray());
91
                    $reflectionProperty->setValue($document, $value);
92
                }
93
            }
94
        }
95
    }
96
97
    /**
98
     * @param object          $document
99
     * @param DocumentManager $dm
100
     */
101
    protected function replacePersistentCollections($document, DocumentManager $dm)
102
    {
103
        $classMetadata = $dm->getClassMetadata(\get_class($document));
104
        /** @var \ReflectionProperty $reflectionProperty */
105
        foreach ($classMetadata->getReflectionProperties() as $propertyName => $reflectionProperty) {
106
            $mapping = $classMetadata->getFieldMapping($propertyName);
107
            $value = $reflectionProperty->getValue($document);
108
109
            if ((isset($mapping['association']) && $mapping['type'] === 'many') && $value !== null) {
110
                if (isset($mapping['cubiche:collection'])) {
111
                    /** @var PropertyMetadata $propertyMetadata */
112
                    $propertyMetadata = $mapping['cubiche:collection'];
113
                    $className = $propertyMetadata->getMetadata('persistenClassName');
114
115
                    $value = new $className($value);
116
                    if ($reflectionProperty->isPrivate()) {
117
                        $reflectionProperty->setAccessible(true);
118
                    }
119
120
                    $reflectionProperty->setValue($document, $value);
121
                }
122
            }
123
        }
124
    }
125
126
    /**
127
     * @param ClassMetadata $classMetadata
128
     *
129
     * @throws MappingException
130
     */
131
    protected function checkArrayCollectionType(ClassMetadata $classMetadata)
132
    {
133
        foreach ($classMetadata->fieldMappings as $fieldName => $mapping) {
134
            if (isset($mapping['embedded']) || isset($mapping['reference'])) {
135
                continue;
136
            }
137
138
            if (isset($mapping['cubiche:collection'])) {
139
                /** @var PropertyMetadata $propertyMetadata */
140
                $propertyMetadata = $mapping['cubiche:collection'];
141
                if ($propertyMetadata->getMetadata('of') === null) {
142
                    throw MappingException::inField(
143
                        'The "of" option in '.$propertyMetadata->getMetadata('type').' type is missing',
144
                        $classMetadata->name,
145
                        $fieldName
146
                    );
147
                }
148
149
                $type = $propertyMetadata->getMetadata('of').$propertyMetadata->getMetadata('type');
150
                if (!Type::hasType($type)) {
151
                    Type::addType($type, $propertyMetadata->getMetadata('typeClassName'));
152
                    Type::getType($type)->setInnerType($propertyMetadata->getMetadata('of'));
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Doctrine\ODM\MongoDB\Types\Type as the method setInnerType() does only exist in the following sub-classes of Doctrine\ODM\MongoDB\Types\Type: Cubiche\Infrastructure\C...\Types\ArrayHashMapType, Cubiche\Infrastructure\C...oDB\Types\ArrayListType, Cubiche\Infrastructure\C...goDB\Types\ArraySetType. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
153
                }
154
155
                $classMetadata->fieldMappings[$fieldName]['type'] = $type;
156
            }
157
        }
158
    }
159
}
160