EventListener::postLoadClassMetadata()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\EventListener;
13
14
use Cubiche\Core\Metadata\PropertyMetadata;
15
use Cubiche\Infrastructure\Doctrine\ODM\MongoDB\Event\RegisterDriverMetadataEventArgs;
16
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Metadata\Driver\XmlDriver;
17
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Types\DecimalType;
18
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Types\DynamicEnumType;
19
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Types\IntegerType;
20
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Types\RealType;
21
use Cubiche\Infrastructure\System\Doctrine\ODM\MongoDB\Types\StringLiteralType;
22
use Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs;
23
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
24
use Doctrine\ODM\MongoDB\Mapping\MappingException;
25
use Doctrine\ODM\MongoDB\Types\Type;
26
27
/**
28
 * Event Listener Class.
29
 *
30
 * @author Karel Osorio Ramírez <[email protected]>
31
 * @author Ivannis Suárez Jerez <[email protected]>
32
 */
33
class EventListener
34
{
35
    /**
36
     * @var array
37
     */
38
    protected $typeMapping = array(
39
        'decimal' => DecimalType::class,
40
        'integer' => IntegerType::class,
41
        'real' => RealType::class,
42
        'string' => StringLiteralType::class,
43
    );
44
45
    /**
46
     * @param RegisterDriverMetadataEventArgs $eventArgs
47
     */
48
    public function registerDriverMetadata(RegisterDriverMetadataEventArgs $eventArgs)
49
    {
50
        $eventArgs->driverFactory()->registerXmlDriver(XmlDriver::class);
51
    }
52
53
    /**
54
     * @param LoadClassMetadataEventArgs $eventArgs
55
     */
56
    public function postLoadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
57
    {
58
        $this->checkEnumType($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...
59
        $this->checkTypes($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...
60
    }
61
62
    /**
63
     * @param ClassMetadata $classMetadata
64
     *
65
     * @throws MappingException
66
     */
67
    protected function checkEnumType(ClassMetadata $classMetadata)
68
    {
69
        foreach ($classMetadata->fieldMappings as $fieldName => $mapping) {
70
            if (isset($mapping['cubiche:enum'])) {
71
                /** @var PropertyMetadata $propertyMetadata */
72
                $propertyMetadata = $mapping['cubiche:enum'];
73
74
                $type = str_replace('\\', '.', $propertyMetadata->getMetadata('type'));
75
                if (!Type::hasType($type)) {
76
                    Type::registerType($type, DynamicEnumType::class);
77
                    Type::getType($type)->setTargetClass($propertyMetadata->getMetadata('type'));
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 setTargetClass() does only exist in the following sub-classes of Doctrine\ODM\MongoDB\Types\Type: Cubiche\Infrastructure\M...icNativeValueObjectType, Cubiche\Infrastructure\S...B\Types\DynamicEnumType. 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...
78
                }
79
80
                $classMetadata->fieldMappings[$fieldName]['type'] = $type;
81
            }
82
        }
83
    }
84
85
    /**
86
     * @param ClassMetadata $classMetadata
87
     */
88
    protected function checkTypes(ClassMetadata $classMetadata)
89
    {
90
        $types = array_keys($this->typeMapping);
91
        foreach ($classMetadata->fieldMappings as $fieldName => $mapping) {
92
            foreach ($types as $type) {
93
                if (isset($mapping['cubiche:'.$type])) {
94
                    $typeName = substr(
95
                        $this->typeMapping[$type],
96
                        strrpos($this->typeMapping[$type], '\\') + 1
97
                    );
98
99
                    if (!Type::hasType($typeName)) {
100
                        Type::registerType($typeName, $this->typeMapping[$type]);
101
                    }
102
103
                    $classMetadata->fieldMappings[$fieldName]['type'] = $typeName;
104
                    break;
105
                }
106
            }
107
        }
108
    }
109
}
110