Completed
Push — master ( 664fb1...60ffba )
by
unknown
26:32
created

RFMMetricStateManager   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 141
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 21
lcom 1
cbo 6
dl 0
loc 141
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B resetMetrics() 0 31 6
A executeResetQuery() 0 23 3
C scheduleRecalculation() 0 49 11
1
<?php
2
3
namespace Oro\Bundle\AnalyticsBundle\Model;
4
5
use JMS\JobQueueBundle\Entity\Job;
6
7
use Oro\Bundle\EntityBundle\ORM\DoctrineHelper;
8
use Oro\Bundle\AnalyticsBundle\Command\CalculateAnalyticsCommand;
9
use Oro\Bundle\AnalyticsBundle\Entity\RFMMetricCategory;
10
use Oro\Bundle\ChannelBundle\Entity\Channel;
11
12
class RFMMetricStateManager extends StateManager
13
{
14
    /**
15
     * @var string
16
     */
17
    protected $interface;
18
19
    /**
20
     * @var string
21
     */
22
    protected $channelClass;
23
24
    /**
25
     * @param DoctrineHelper $doctrineHelper
26
     * @param string         $interface
27
     * @param string         $channelClass
28
     */
29
    public function __construct(DoctrineHelper $doctrineHelper, $interface, $channelClass)
30
    {
31
        parent::__construct($doctrineHelper);
32
33
        $this->interface    = $interface;
34
        $this->channelClass = $channelClass;
35
    }
36
37
    /**
38
     * @param Channel $channel
39
     */
40
    public function resetMetrics(Channel $channel = null)
41
    {
42
        $criteria = [];
43
44
        if ($channel) {
45
            $criteria = ['id' => $this->doctrineHelper->getSingleEntityIdentifier($channel)];
46
        }
47
48
        /** @var Channel[] $channels */
49
        $channels = $this->doctrineHelper->getEntityRepository($this->channelClass)->findBy($criteria);
50
51
        $channelsByCustomerIdentity = [];
52
        foreach ($channels as $channel) {
53
            $customerIdentity = $channel->getCustomerIdentity();
54
55
            if (!$customerIdentity) {
56
                continue;
57
            }
58
59
            if (!in_array($this->interface, class_implements($customerIdentity), true)) {
60
                continue;
61
            }
62
63
            $channelsByCustomerIdentity[$customerIdentity][] = $this->doctrineHelper
64
                ->getSingleEntityIdentifier($channel);
65
        }
66
67
        foreach ($channelsByCustomerIdentity as $className => $channelIds) {
68
            $this->executeResetQuery($className, $channelIds);
69
        }
70
    }
71
72
    /**
73
     * @param string $className
74
     * @param array  $ids
75
     */
76
    protected function executeResetQuery($className, $ids)
77
    {
78
        if (!$ids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
79
            return;
80
        }
81
82
        $qb = $this->doctrineHelper
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 createQueryBuilder() does only exist in the following implementations of said interface: Doctrine\ORM\Decorator\EntityManagerDecorator, Doctrine\ORM\EntityManager, Oro\Bundle\EntityBundle\ORM\OroEntityManager, Oro\Bundle\TestFramework...Mocks\EntityManagerMock, Oro\Component\TestUtils\...Mocks\EntityManagerMock.

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...
83
            ->getEntityManager($className)
84
            ->createQueryBuilder()
85
            ->update($className, 'e');
86
87
        foreach (RFMMetricCategory::$types as $type) {
88
            $qb
89
                ->set(sprintf('e.%s', $type), sprintf(':%s', $type))
90
                ->setParameter($type, null);
91
        }
92
93
        $qb
94
            ->where($qb->expr()->in('e.dataChannel', ':dataChannels'))
95
            ->setParameter('dataChannels', $ids);
96
97
        $qb->getQuery()->execute();
98
    }
99
100
    /**
101
     * @param Channel $channel
102
     */
103
    public function scheduleRecalculation(Channel $channel = null)
104
    {
105
        if ($channel) {
106
            $argument = sprintf('--channel=%s', $channel->getId());
107
108
            if ($this->isJobRunning($argument)) {
109
                return;
110
            }
111
112
            $isActiveChannel = $channel->getStatus() === Channel::STATUS_ACTIVE;
113
            $channelData = $channel->getData();
114
            $rfmEnabled = !empty($channelData[RFMAwareInterface::RFM_STATE_KEY]);
115
116
            if (!$isActiveChannel || !$rfmEnabled) {
117
                return;
118
            }
119
        }
120
121
        if ($this->getJob()) {
122
            return;
123
        }
124
125
        $args = [];
126
        if ($channel) {
127
            $argument = sprintf('--channel=%s', $channel->getId());
128
            $channelJob = $this->getJob($argument);
129
            if ($channelJob) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $channelJob of type JMS\JobQueueBundle\Entity\Job[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
130
                return;
131
            }
132
133
            $args = [$argument];
134
        }
135
136
        $job = new Job(CalculateAnalyticsCommand::COMMAND_NAME, $args);
137
        $em = $this->doctrineHelper->getEntityManager($job);
138
139
        if (!$channel) {
140
            $channelJobs = $this->getJob('--channel');
141
142
            if ($channelJobs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $channelJobs of type JMS\JobQueueBundle\Entity\Job[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
143
                foreach ($channelJobs as $channelJob) {
144
                    $em->remove($channelJob);
145
                }
146
            }
147
        }
148
149
        $em->persist($job);
150
        $em->flush($job);
151
    }
152
}
153