MessageManager::findByTypes()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NotificationBundle\Entity;
15
16
use Doctrine\ORM\QueryBuilder;
17
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
18
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
19
use Sonata\Doctrine\Entity\BaseEntityManager;
20
use Sonata\NotificationBundle\Model\MessageInterface;
21
use Sonata\NotificationBundle\Model\MessageManagerInterface;
22
23
class MessageManager extends BaseEntityManager implements MessageManagerInterface
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function save($message, $andFlush = true): void
29
    {
30
        //Hack for ConsumerHandlerCommand->optimize()
31
        if ($message->getId() && !$this->em->getUnitOfWork()->isInIdentityMap($message)) {
0 ignored issues
show
Documentation introduced by
The property em does not exist on object<Sonata\Notificati...\Entity\MessageManager>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
32
            $message = $this->getEntityManager()->getUnitOfWork()->merge($message);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ORM\UnitOfWork::merge() has been deprecated with message: 2.7 This method is being removed from the ORM and won't have any replacement

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

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
        $params = [];
44
        $query = $this->prepareStateQuery($state, $types, $batchSize, $params);
45
46
        $query->setParameters($params);
47
48
        return $query->getQuery()->execute();
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10)
55
    {
56
        $params = [];
57
        $query = $this->prepareStateQuery($state, $types, $batchSize, $params);
58
59
        if ($maxAttempts) {
60
            $query
61
                ->andWhere('m.restartCount < :maxAttempts')
62
                ->andWhere('m.updatedAt < :delayDate');
63
64
            $params['maxAttempts'] = $maxAttempts;
65
            $now = new \DateTime();
66
            $params['delayDate'] = $now->add(\DateInterval::createFromDateString(($attemptDelay * -1).' second'));
67
        }
68
69
        $query->setParameters($params);
70
71
        return $query->getQuery()->execute();
72
    }
73
74
    /**
75
     * {@inheritdoc}
76
     */
77
    public function countStates()
78
    {
79
        $tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
80
81
        $stm = $this->getConnection()->query(
82
            sprintf('SELECT state, count(state) as cnt FROM %s GROUP BY state', $tableName)
83
        );
84
85
        $states = [
86
            MessageInterface::STATE_DONE => 0,
87
            MessageInterface::STATE_ERROR => 0,
88
            MessageInterface::STATE_IN_PROGRESS => 0,
89
            MessageInterface::STATE_OPEN => 0,
90
        ];
91
92
        while ($data = $stm->fetch()) {
93
            $states[$data['state']] = $data['cnt'];
94
        }
95
96
        return $states;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $states; (array<*,integer>) is incompatible with the return type declared by the interface Sonata\NotificationBundl...rInterface::countStates of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
97
    }
98
99
    /**
100
     * {@inheritdoc}
101
     */
102
    public function cleanup($maxAge): void
103
    {
104
        $tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
0 ignored issues
show
Unused Code introduced by
$tableName 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...
105
106
        $date = new \DateTime('now');
107
        $date->sub(new \DateInterval(sprintf('PT%sS', $maxAge)));
108
109
        $qb = $this->getRepository()->createQueryBuilder('message')
110
            ->delete()
111
            ->where('message.state = :state')
112
            ->andWhere('message.completedAt < :date')
113
            ->setParameter('state', MessageInterface::STATE_DONE)
114
            ->setParameter('date', $date);
115
116
        $qb->getQuery()->execute();
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122
    public function cancel(MessageInterface $message, $force = false): void
123
    {
124
        if (($message->isRunning() || $message->isError()) && !$force) {
125
            return;
126
        }
127
128
        $message->setState(MessageInterface::STATE_CANCELLED);
129
130
        $this->save($message);
0 ignored issues
show
Documentation introduced by
$message is of type object<Sonata\Notificati...Model\MessageInterface>, but the function expects a object<Sonata\Doctrine\Model\T>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136
    public function restart(MessageInterface $message)
137
    {
138
        if ($message->isOpen() || $message->isRunning() || $message->isCancelled()) {
139
            return;
140
        }
141
142
        $this->cancel($message, true);
143
144
        $newMessage = clone $message;
145
        $newMessage->setRestartCount($message->getRestartCount() + 1);
146
        $newMessage->setType($message->getType());
147
148
        return $newMessage;
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    public function getPager(array $criteria, $page, $limit = 10, array $sort = [])
155
    {
156
        $query = $this->getRepository()
157
            ->createQueryBuilder('m')
158
            ->select('m');
159
160
        $fields = $this->getEntityManager()->getClassMetadata($this->class)->getFieldNames();
161
        foreach ($sort as $field => $direction) {
162
            if (!\in_array($field, $fields, true)) {
163
                throw new \RuntimeException(sprintf("Invalid sort field '%s' in '%s' class", $field, $this->class));
164
            }
165
        }
166
        if (0 === \count($sort)) {
167
            $sort = ['type' => 'ASC'];
168
        }
169
        foreach ($sort as $field => $direction) {
170
            $query->orderBy(sprintf('m.%s', $field), strtoupper($direction));
171
        }
172
173
        $parameters = [];
174
175
        if (isset($criteria['type'])) {
176
            $query->andWhere('m.type = :type');
177
            $parameters['type'] = $criteria['type'];
178
        }
179
180
        if (isset($criteria['state'])) {
181
            $query->andWhere('m.state = :state');
182
            $parameters['state'] = $criteria['state'];
183
        }
184
185
        $query->setParameters($parameters);
186
        $pager = new Pager();
187
188
        $pager->setMaxPerPage($limit);
189
        $pager->setQuery(new ProxyQuery($query));
190
        $pager->setPage($page);
191
        $pager->init();
192
193
        return $pager;
194
    }
195
196
    /**
197
     * @param int   $state
198
     * @param array $types
199
     * @param int   $batchSize
200
     * @param array $parameters
201
     *
202
     * @return QueryBuilder
203
     */
204
    protected function prepareStateQuery($state, $types, $batchSize, &$parameters)
205
    {
206
        $query = $this->getRepository()
207
            ->createQueryBuilder('m')
208
            ->where('m.state = :state')
209
            ->orderBy('m.createdAt');
210
211
        $parameters['state'] = $state;
212
213
        if (\count($types) > 0) {
214
            if (\array_key_exists('exclude', $types) || \array_key_exists('include', $types)) {
215
                if (\array_key_exists('exclude', $types)) {
216
                    $query->andWhere('m.type NOT IN (:exclude)');
217
                    $parameters['exclude'] = $types['exclude'];
218
                }
219
220
                if (\array_key_exists('include', $types)) {
221
                    $query->andWhere('m.type IN (:include)');
222
                    $parameters['include'] = $types['include'];
223
                }
224
            } else { // BC
225
                $query->andWhere('m.type IN (:types)');
226
                $parameters['types'] = $types;
227
            }
228
        }
229
230
        $query->setMaxResults($batchSize);
231
232
        return $query;
233
    }
234
}
235