Completed
Pull Request — 3.x (#246)
by
unknown
13:12
created

MessageManager::getPager()   C

Complexity

Conditions 7
Paths 33

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 22
nc 33
nop 4
1
<?php
2
3
/*
4
 * This file is part of the Sonata Project package.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
7
 * (c) Salma Khemiri Chakroun <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
namespace Sonata\NotificationBundle\Document;
14
15
use Sonata\CoreBundle\Model\BaseDocumentManager;
16
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
17
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
18
use NotificationEngine\Sonata\NotificationBundle\Model\MessageInterface;
19
use NotificationEngine\Sonata\NotificationBundle\Model\MessageManagerInterface;
20
use Doctrine\ODM\MongoDB\Cursor;
21
use Doctrine\MongoDB\ArrayIterator;
22
23
class MessageManager extends BaseDocumentManager implements MessageManagerInterface
24
{
25
    /**
26
     * {@inheritDoc}
27
     */
28
    public function save($message, $andFlush = true)
29
    {
30
        //Hack for ConsumerHandlerCommand->optimize()
31
        if ($message->getId() && !$this->dm->getUnitOfWork()->isInIdentityMap($message)) {
32
            $this->getDocumentManager()->getUnitOfWork()->merge($message);
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 getUnitOfWork() 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...
33
        }
34
        
35
        parent::save($message, $andFlush);
36
    }
37
38
    /**
39
     * {@inheritDoc}
40
     */
41
    public function findByTypes(array $types, $state, $batchSize)
42
    {
43
        $query = $this->prepareStateQuery($state, $types, $batchSize);
44
45
        $result = $query->getQuery()->execute();
46
        
47
        if ($result instanceof Cursor) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ODM\MongoDB\Cursor does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
48
            $result = $result->toArray();
49
        }
50
        
51
        return $result;
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57
    public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10)
58
    {
59
        $query = $this->prepareStateQuery($state, $types, $batchSize);
60
61
        if ($maxAttempts) {
62
            $now = new \DateTime();
63
            $delayDate = $now->add(\DateInterval::createFromDateString(($attemptDelay * -1) . ' second'));
64
            
65
            $query
66
                ->field('restartCount')->lt($maxAttempts)
67
                ->field('updatedAt')->lt($delayDate);
68
            
69
        }
70
71
        $result = $query->getQuery()->execute();
72
        
73
        if ($result instanceof Cursor) {
0 ignored issues
show
Bug introduced by
The class Doctrine\ODM\MongoDB\Cursor does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
74
            $result = $result->toArray();
75
        }
76
        
77
        return $result;
78
    }
79
80
    /**
81
     * {@inheritDoc}
82
     */
83
    public function countStates()
84
    {        
85
        $result = $this->getRepository()->createQueryBuilder('message')
86
                                        ->group(array('state' => 1), array('count' => 0))
87
                                        ->reduce('function (curr, result) { result.count++; }')
88
                                        ->getQuery()
89
                                        ->execute();
90
        
91
        $states = array(
92
            MessageInterface::STATE_DONE        => 0,
93
            MessageInterface::STATE_ERROR       => 0,
94
            MessageInterface::STATE_IN_PROGRESS => 0,
95
            MessageInterface::STATE_OPEN        => 0,
96
        );
97
        
98
        if ($result instanceof ArrayIterator) 
0 ignored issues
show
Bug introduced by
The class Doctrine\MongoDB\ArrayIterator does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
99
        {
100
            $result = $result->toArray();
101
            
102
            foreach ($result as $data) 
103
            {
104
                $states[$data['state']] = $data['count'];
105
            }
106
        }
107
108
        return $states;
109
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114
    public function cleanup($maxAge)
115
    {
116
        $date = new \DateTime('now');
117
        $date->sub(new \DateInterval(sprintf('PT%sS', $maxAge)));
118
        
119
        $qb = $this->getRepository()->createQueryBuilder('message')
0 ignored issues
show
Unused Code introduced by
$qb is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
120
                                    ->remove()
121
                                    ->field('state')->equals(MessageInterface::STATE_DONE)
122
                                    ->field('completedAt')->lt($date)
123
                                    ->getQuery()
124
                                    ->execute();
125
    }
126
127
    /**
128
     * {@inheritdoc}
129
     */
130
    public function cancel(MessageInterface $message, $force = false)
131
    {
132
        if (($message->isRunning() || $message->isError()) && !$force) {
133
            return;
134
        }
135
136
        $message->setState(MessageInterface::STATE_CANCELLED);
137
138
        $this->save($message);
139
    }
140
141
    /**
142
     * {@inheritdoc}
143
     */
144
    public function restart(MessageInterface $message)
145
    {
146
        if ($message->isOpen() || $message->isRunning() || $message->isCancelled()) {
147
            return;
148
        }
149
150
        $this->cancel($message, true);
151
152
        $newMessage = clone $message;
153
        $newMessage->setRestartCount($message->getRestartCount() + 1);
154
        $newMessage->setType($message->getType());
155
156
        return $newMessage;
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
163
    {
164
        $query = $this->getRepository()
165
            ->createQueryBuilder('message');
166
167
        $fields = $this->getDocumentManager()->getClassMetadata($this->class)->getFieldNames();
168
        foreach ($sort as $field => $direction) {
169
            if (!in_array($field, $fields)) {
170
                throw new \RuntimeException(sprintf("Invalid sort field '%s' in '%s' class", $field, $this->class));
171
            }
172
        }
173
        if (count($sort) == 0) {
174
            $sort = array('type' => 'ASC');
175
        }
176
        foreach ($sort as $field => $direction) {
177
            $query->sort(sprintf('m.%s', $field), strtoupper($direction));
178
        }
179
180
        $parameters = array();
0 ignored issues
show
Unused Code introduced by
$parameters is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
181
182
        if (isset($criteria['type'])) {
183
            $query->field('type')->equals($criteria['type']);
184
        }
185
186
        if (isset($criteria['state'])) {
187
            $query->field('state')->equals($criteria['state']);
188
        }
189
190
        $pager = new Pager();
191
192
        $pager->setMaxPerPage($limit);
193
        $pager->setQuery(new ProxyQuery($query));
194
        $pager->setPage($page);
195
        $pager->init();
196
197
        return $pager;
198
    }
199
200
    /**
201
     * @param int   $state
202
     * @param array $types
203
     * @param int   $batchSize
204
     * @param array $parameters
0 ignored issues
show
Bug introduced by
There is no parameter named $parameters. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
205
     *
206
     * @return QueryBuilder
207
     */
208
    protected function prepareStateQuery($state, $types, $batchSize)
209
    {
210
        $query = $this->getRepository()
211
            ->createQueryBuilder('message')
212
            ->field('state')->equals($state)
213
            ->sort('createdAt');
214
        
215
        if (count($types) > 0) {
216
            if (array_key_exists('exclude', $types) || array_key_exists('include', $types)) {
217
                if (array_key_exists('exclude', $types)) {
218
                    $query->field('type')->notIn(array($types['exclude']));
219
                }
220
221
                if (array_key_exists('include', $types)) {
222
                    $query->field('type')->in(array($types['include']));
223
                }
224
            } else {
225
                $query->field('type')->in(array($types));
226
            }
227
        }
228
229
        $query->limit($batchSize);
230
231
        return $query;
232
    }
233
}
234