Completed
Push — 2.x-dev-kit ( 8d77e1 )
by
unknown
28:22 queued 25:50
created

MessageManager::getPager()   C

Complexity

Conditions 7
Paths 33

Size

Total Lines 41
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 41
rs 6.7272
cc 7
eloc 26
nc 33
nop 4
1
<?php
2
3
/*
4
 * This file is part of the Sonata project.
5
 *
6
 * (c) Thomas Rabaix <[email protected]>
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 Sonata\NotificationBundle\Entity;
13
14
use Doctrine\ORM\QueryBuilder;
15
use Sonata\CoreBundle\Model\BaseEntityManager;
16
use Sonata\DatagridBundle\Pager\Doctrine\Pager;
17
use Sonata\DatagridBundle\ProxyQuery\Doctrine\ProxyQuery;
18
use Sonata\NotificationBundle\Model\MessageInterface;
19
use Sonata\NotificationBundle\Model\MessageManagerInterface;
20
21
class MessageManager extends BaseEntityManager implements MessageManagerInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function save($message, $andFlush = true)
27
    {
28
        //Hack for ConsumerHandlerCommand->optimize()
29
        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...
30
            $message = $this->getEntityManager()->getUnitOfWork()->merge($message);
31
        }
32
33
        parent::save($message, $andFlush);
34
    }
35
36
    /**
37
     * {@inheritdoc}
38
     */
39
    public function findByTypes(array $types, $state, $batchSize)
40
    {
41
        $params = array();
42
        $query = $this->prepareStateQuery($state, $types, $batchSize, $params);
43
44
        $query->setParameters($params);
45
46
        return $query->getQuery()->execute();
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function findByAttempts(array $types, $state, $batchSize, $maxAttempts = null, $attemptDelay = 10)
53
    {
54
        $params = array();
55
        $query = $this->prepareStateQuery($state, $types, $batchSize, $params);
56
57
        if ($maxAttempts) {
58
            $query
59
                ->andWhere('m.restartCount < :maxAttempts')
60
                ->andWhere('m.updatedAt < :delayDate');
61
62
            $params['maxAttempts'] = $maxAttempts;
63
            $now = new \DateTime();
64
            $params['delayDate'] = $now->add(\DateInterval::createFromDateString(($attemptDelay * -1).' second'));
65
        }
66
67
        $query->setParameters($params);
68
69
        return $query->getQuery()->execute();
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function countStates()
76
    {
77
        $tableName = $this->getEntityManager()->getClassMetadata($this->class)->table['name'];
78
79
        $stm = $this->getConnection()->query(sprintf('SELECT state, count(state) as cnt FROM %s GROUP BY state', $tableName));
80
81
        $states = array(
82
            MessageInterface::STATE_DONE        => 0,
83
            MessageInterface::STATE_ERROR       => 0,
84
            MessageInterface::STATE_IN_PROGRESS => 0,
85
            MessageInterface::STATE_OPEN        => 0,
86
        );
87
88
        foreach ($stm->fetch() as $data) {
89
            $states[$data['state']] = $data['cnt'];
90
        }
91
92
        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...
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function cleanup($maxAge)
99
    {
100
        $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...
101
102
        $date = new \DateTime('now');
103
        $date->sub(new \DateInterval(sprintf('PT%sS', $maxAge)));
104
105
        $qb = $this->getRepository()->createQueryBuilder('message')
106
            ->delete()
107
            ->where('message.state = :state')
108
            ->andWhere('message.completedAt < :date')
109
            ->setParameter('state', MessageInterface::STATE_DONE)
110
            ->setParameter('date', $date);
111
112
        $qb->getQuery()->execute();
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function cancel(MessageInterface $message, $force = false)
119
    {
120
        if (($message->isRunning() || $message->isError()) && !$force) {
121
            return;
122
        }
123
124
        $message->setState(MessageInterface::STATE_CANCELLED);
125
126
        $this->save($message);
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function restart(MessageInterface $message)
133
    {
134
        if ($message->isOpen() || $message->isRunning() || $message->isCancelled()) {
135
            return;
136
        }
137
138
        $this->cancel($message, true);
139
140
        $newMessage = clone $message;
141
        $newMessage->setRestartCount($message->getRestartCount() + 1);
142
        $newMessage->setType($message->getType());
143
144
        return $newMessage;
145
    }
146
147
    /**
148
     * @param int   $state
149
     * @param array $types
150
     * @param int   $batchSize
151
     * @param array $parameters
152
     *
153
     * @return QueryBuilder
154
     */
155
    protected function prepareStateQuery($state, $types, $batchSize, &$parameters)
156
    {
157
        $query = $this->getRepository()
158
            ->createQueryBuilder('m')
159
            ->where('m.state = :state')
160
            ->orderBy('m.createdAt');
161
162
        $parameters['state'] = $state;
163
164
        if (count($types) > 0) {
165
            if (array_key_exists('exclude', $types) || array_key_exists('include', $types)) {
166
                if (array_key_exists('exclude', $types)) {
167
                    $query->andWhere('m.type NOT IN (:exclude)');
168
                    $parameters['exclude'] = $types['exclude'];
169
                }
170
171
                if (array_key_exists('include', $types)) {
172
                    $query->andWhere('m.type IN (:include)');
173
                    $parameters['include'] = $types['include'];
174
                }
175
            } else { // BC
176
                $query->andWhere('m.type IN (:types)');
177
                $parameters['types'] = $types;
178
            }
179
        }
180
181
        $query->setMaxResults($batchSize);
182
183
        return $query;
184
    }
185
186
    /**
187
     * {@inheritdoc}
188
     */
189
    public function getPager(array $criteria, $page, $limit = 10, array $sort = array())
190
    {
191
        $query = $this->getRepository()
192
            ->createQueryBuilder('m')
193
            ->select('m');
194
195
        $fields = $this->getEntityManager()->getClassMetadata($this->class)->getFieldNames();
196
        foreach ($sort as $field => $direction) {
197
            if (!in_array($field, $fields)) {
198
                throw new \RuntimeException(sprintf("Invalid sort field '%s' in '%s' class", $field, $this->class));
199
            }
200
        }
201
        if (count($sort) == 0) {
202
            $sort = array('type' => 'ASC');
203
        }
204
        foreach ($sort as $field => $direction) {
205
            $query->orderBy(sprintf('m.%s', $field), strtoupper($direction));
206
        }
207
208
        $parameters = array();
209
210
        if (isset($criteria['type'])) {
211
            $query->andWhere('m.type = :type');
212
            $parameters['type'] = $criteria['type'];
213
        }
214
215
        if (isset($criteria['state'])) {
216
            $query->andWhere('m.state = :state');
217
            $parameters['state'] = $criteria['state'];
218
        }
219
220
        $query->setParameters($parameters);
221
        $pager = new Pager();
222
223
        $pager->setMaxPerPage($limit);
224
        $pager->setQuery(new ProxyQuery($query));
225
        $pager->setPage($page);
226
        $pager->init();
227
228
        return $pager;
229
    }
230
}
231