Completed
Pull Request — master (#53)
by Matthew
12:05
created

DtcQueueListener   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Test Coverage

Coverage 84.15%

Importance

Changes 2
Bugs 2 Features 0
Metric Value
wmc 30
lcom 1
cbo 11
dl 0
loc 141
ccs 69
cts 82
cp 0.8415
rs 10
c 2
b 2
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A setRegistry() 0 4 1
A setEntityManagerName() 0 4 1
A preRemove() 0 12 3
B getObjectManager() 0 15 5
B processRun() 0 23 4
B adjustIdGenerator() 0 10 5
B processJob() 0 27 5
A preUpdate() 0 8 2
A prePersist() 0 12 3
1
<?php
2
3
namespace Dtc\QueueBundle\Doctrine;
4
5
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
6
use Doctrine\ODM\MongoDB\DocumentManager;
7
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
8
use Doctrine\ORM\EntityManager;
9
use Doctrine\ORM\Id\AssignedGenerator;
10
use Dtc\QueueBundle\Model\StallableJob;
11
use Dtc\QueueBundle\Model\Run;
12
use Dtc\QueueBundle\Util\Util;
13
use Symfony\Bridge\Doctrine\RegistryInterface;
14
15
class DtcQueueListener
16
{
17
    private $jobArchiveClass;
18
    private $runArchiveClass;
19
    private $entityManagerName;
20
    private $objectManager;
21
    private $registry;
22
23 18
    public function __construct($jobArchiveClass, $runArchiveClass)
24
    {
25 18
        $this->jobArchiveClass = $jobArchiveClass;
26 18
        $this->runArchiveClass = $runArchiveClass;
27 18
    }
28
29
    public function setRegistry(RegistryInterface $registry)
30
    {
31
        $this->registry = $registry;
32
    }
33
34
    public function setEntityManagerName($entityManagerName)
35
    {
36
        $this->entityManagerName = $entityManagerName;
37
    }
38
39 36
    public function preRemove(LifecycleEventArgs $eventArgs)
40
    {
41 36
        $object = $eventArgs->getObject();
42 36
        $objectManager = $eventArgs->getObjectManager();
43 36
        $this->objectManager = $objectManager;
44
45 36
        if ($object instanceof \Dtc\QueueBundle\Model\Job) {
46 33
            $this->processJob($object);
47 9
        } elseif ($object instanceof Run) {
48 9
            $this->processRun($object);
49
        }
50 36
    }
51
52 36
    protected function getObjectManager()
53
    {
54 36
        if (!$this->registry) {
55 36
            return $this->objectManager;
56
        }
57
58
        if ($this->objectManager instanceof EntityManager && !$this->objectManager->isOpen()) {
59
            $this->objectManager = $this->registry->getManager($this->entityManagerName);
60
            if (!$this->objectManager->isOpen()) {
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 isOpen() does only exist in the following implementations of said interface: Doctrine\ODM\MongoDB\DocumentManager, 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...
61
                $this->objectManager = $this->registry->resetManager($this->entityManagerName);
62
            }
63
        }
64
65
        return $this->objectManager;
66
    }
67
68 9
    public function processRun(Run $object)
69
    {
70 9
        $runArchiveClass = $this->runArchiveClass;
71 9
        if ($object instanceof $runArchiveClass) {
72
            return;
73
        }
74
75 9
        $objectManager = $this->getObjectManager();
76
77 9
        $repository = $objectManager->getRepository($runArchiveClass);
78 9
        if (!$runArchive = $repository->find($object->getId())) {
79 9
            $runArchive = new $runArchiveClass();
80 9
            $newArchive = true;
81
        }
82
83 9
        Util::copy($object, $runArchive);
84 9
        if ($newArchive) {
0 ignored issues
show
Bug introduced by
The variable $newArchive does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
85 9
            $metadata = $objectManager->getClassMetadata($runArchiveClass);
86 9
            $this->adjustIdGenerator($metadata, $objectManager);
0 ignored issues
show
Unused Code introduced by
The call to DtcQueueListener::adjustIdGenerator() has too many arguments starting with $objectManager.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
87
        }
88
89 9
        $objectManager->persist($runArchive);
90 9
    }
91
92
    /**
93
     * @param $metadata
94
     */
95 36
    protected function adjustIdGenerator(\Doctrine\Common\Persistence\Mapping\ClassMetadata $metadata)
96
    {
97 36
        $objectManager = $this->getObjectManager();
98 36
        if ($objectManager instanceof EntityManager && $metadata instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
99 17
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
100 17
            $metadata->setIdGenerator(new AssignedGenerator());
101 19
        } elseif ($objectManager instanceof DocumentManager && $metadata instanceof ClassMetadata) {
102 19
            $metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
103
        }
104 36
    }
105
106 33
    public function processJob(\Dtc\QueueBundle\Model\Job $object)
107
    {
108 33
        if ($object instanceof \Dtc\QueueBundle\Document\Job ||
109 33
            $object instanceof \Dtc\QueueBundle\Entity\Job) {
110
            /** @var JobManager $jobManager */
111 33
            $archiveObjectName = $this->jobArchiveClass;
112 33
            $objectManager = $this->getObjectManager();
113 33
            $repository = $objectManager->getRepository($archiveObjectName);
114 33
            $className = $repository->getClassName();
115
116
            /** @var StallableJob $jobArchive */
117 33
            $newArchive = false;
118 33
            if (!$jobArchive = $repository->find($object->getId())) {
119 33
                $jobArchive = new $className();
120 33
                $newArchive = true;
121
            }
122
123 33
            if ($newArchive) {
124 33
                $metadata = $objectManager->getClassMetadata($className);
125 33
                $this->adjustIdGenerator($metadata, $objectManager);
0 ignored issues
show
Unused Code introduced by
The call to DtcQueueListener::adjustIdGenerator() has too many arguments starting with $objectManager.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
126
            }
127
128 33
            Util::copy($object, $jobArchive);
129 33
            $jobArchive->setUpdatedAt(new \DateTime());
130 33
            $objectManager->persist($jobArchive);
131
        }
132 33
    }
133
134 20
    public function preUpdate(LifecycleEventArgs $eventArgs)
135
    {
136 20
        $object = $eventArgs->getObject();
137 20
        if ($object instanceof \Dtc\QueueBundle\Model\StallableJob) {
138 20
            $dateTime = \Dtc\QueueBundle\Util\Util::getMicrotimeDateTime();
139 20
            $object->setUpdatedAt($dateTime);
140
        }
141 20
    }
142
143 48
    public function prePersist(LifecycleEventArgs $eventArgs)
144
    {
145 48
        $object = $eventArgs->getObject();
146
147 48
        if ($object instanceof \Dtc\QueueBundle\Model\StallableJob) {
148 43
            $dateTime = \Dtc\QueueBundle\Util\Util::getMicrotimeDateTime();
149 43
            if (!$object->getCreatedAt()) {
150
                $object->setCreatedAt($dateTime);
151
            }
152 43
            $object->setUpdatedAt($dateTime);
153
        }
154 48
    }
155
}
156