Completed
Pull Request — master (#24)
by Matthew
07:39
created

JobManager::getJob()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 59
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 3.0001

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 37
cts 38
cp 0.9737
rs 9.597
c 0
b 0
f 0
cc 3
eloc 40
nc 4
nop 4
crap 3.0001

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Dtc\QueueBundle\ORM;
4
5
use Doctrine\DBAL\LockMode;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityRepository;
8
use Doctrine\ORM\QueryBuilder;
9
use Dtc\QueueBundle\Doctrine\BaseJobManager;
10
use Dtc\QueueBundle\Entity\Job;
11
use Dtc\QueueBundle\Model\BaseJob;
12
use Dtc\QueueBundle\Model\RetryableJob;
13
use Symfony\Component\Process\Exception\LogicException;
14
15
class JobManager extends BaseJobManager
16
{
17
    use CommonTrait;
18
    protected static $saveInsertCalled = null;
19
    protected static $resetInsertCalled = null;
20
21 3
    public function countJobsByStatus($objectName, $status, $workerName = null, $method = null)
22
    {
23
        /** @var EntityManager $objectManager */
24 3
        $objectManager = $this->getObjectManager();
25
26
        $qb = $objectManager
27 3
            ->createQueryBuilder()
28 3
            ->select('count(a.id)')
29 3
            ->from($objectName, 'a')
30 3
            ->where('a.status = :status');
31
32 3
        if (null !== $workerName) {
33 1
            $qb->andWhere('a.workerName = :workerName')
34 1
                ->setParameter(':workerName', $workerName);
35
        }
36
37 3
        if (null !== $method) {
38 1
            $qb->andWhere('a.method = :method')
39 1
                ->setParameter(':method', $workerName);
40
        }
41
42 3
        $count = $qb->setParameter(':status', $status)
43 3
            ->getQuery()->getSingleScalarResult();
44
45 3
        if (!$count) {
46 1
            return 0;
47
        }
48
49 3
        return $count;
50
    }
51
52
    /**
53
     * @param string|null $workerName
54
     * @param string|null $method
55
     *
56
     * @return int Count of jobs pruned
57
     */
58 1
    public function pruneErroneousJobs($workerName = null, $method = null)
59
    {
60
        /** @var EntityManager $objectManager */
61 1
        $objectManager = $this->getObjectManager();
62 1
        $qb = $objectManager->createQueryBuilder()->delete($this->getArchiveObjectName(), 'j');
63 1
        $qb->where('j.status = :status')
64 1
            ->setParameter(':status', BaseJob::STATUS_ERROR);
65
66 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
67 1
        $query = $qb->getQuery();
68
69 1
        return intval($query->execute());
70
    }
71
72 14
    protected function resetSaveOk($function)
73
    {
74 14
        $objectManager = $this->getObjectManager();
75 14
        $splObjectHash = spl_object_hash($objectManager);
76
77 14
        if ('save' === $function) {
78
            $compare = static::$resetInsertCalled;
79
        } else {
80 14
            $compare = static::$saveInsertCalled;
81
        }
82
83 14
        if ($splObjectHash === $compare) {
84
            // Insert SQL is cached...
85
            $msg = "Can't call save and reset within the same process cycle (or using the same EntityManager)";
86
            throw new LogicException($msg);
87
        }
88
89 14
        if ('save' === $function) {
90
            static::$saveInsertCalled = spl_object_hash($objectManager);
91
        } else {
92 14
            static::$resetInsertCalled = spl_object_hash($objectManager);
93
        }
94 14
    }
95
96
    /**
97
     * @param string $workerName
98
     * @param string $method
99
     */
100 8
    protected function addWorkerNameCriterion(QueryBuilder $queryBuilder, $workerName = null, $method = null)
101
    {
102 8
        if (null !== $workerName) {
103 3
            $queryBuilder->andWhere('j.workerName = :workerName')->setParameter(':workerName', $workerName);
104
        }
105
106 8
        if (null !== $method) {
107 2
            $queryBuilder->andWhere('j.method = :method')->setParameter(':method', $method);
108
        }
109 8
    }
110
111 1
    protected function updateExpired($workerName = null, $method = null)
112
    {
113
        /** @var EntityManager $objectManager */
114 1
        $objectManager = $this->getObjectManager();
115 1
        $qb = $objectManager->createQueryBuilder()->update($this->getObjectName(), 'j');
116 1
        $qb->set('j.status', ':newStatus');
117 1
        $qb->where('j.expiresAt <= :expiresAt')
118 1
            ->setParameter(':expiresAt', new \DateTime());
119 1
        $qb->andWhere('j.status = :status')
120 1
            ->setParameter(':status', BaseJob::STATUS_NEW)
121 1
            ->setParameter(':newStatus', Job::STATUS_EXPIRED);
122
123 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
124 1
        $query = $qb->getQuery();
125
126 1
        return intval($query->execute());
127
    }
128
129 1
    protected function getJobCurrentStatus(\Dtc\QueueBundle\Model\Job $job)
130
    {
131
        /** @var EntityManager $objectManager */
132 1
        $objectManager = $this->getObjectManager();
133 1
        $qb = $objectManager->createQueryBuilder()->select('j.status')->from($this->getObjectName(), 'j');
134 1
        $qb->where('j.id = :id')->setParameter(':id', $job->getId());
135
136 1
        return $qb->getQuery()->getSingleScalarResult();
137
    }
138
139
    /**
140
     * Removes archived jobs older than $olderThan.
141
     *
142
     * @param \DateTime $olderThan
143
     */
144 1
    public function pruneArchivedJobs(\DateTime $olderThan)
145
    {
146 1
        return $this->removeOlderThan($this->getArchiveObjectName(),
147 1
                'updatedAt',
148 1
                $olderThan);
149
    }
150
151 2
    public function getJobCount($workerName = null, $method = null)
152
    {
153
        /** @var EntityManager $objectManager */
154 2
        $objectManager = $this->getObjectManager();
155 2
        $qb = $objectManager->createQueryBuilder();
156
157 2
        $qb = $qb->select('count(j)')->from($this->getObjectName(), 'j');
158
159 2
        $where = 'where';
160 2
        if (null !== $workerName) {
161
            if (null !== $method) {
162
                $qb->where($qb->expr()->andX(
163
                    $qb->expr()->eq('j.workerName', ':workerName'),
164
                                                $qb->expr()->eq('j.method', ':method')
165
                ))
166
                    ->setParameter(':method', $method);
167
            } else {
168
                $qb->where('j.workerName = :workerName');
169
            }
170
            $qb->setParameter(':workerName', $workerName);
171
            $where = 'andWhere';
172 2
        } elseif (null !== $method) {
173
            $qb->where('j.method = :method')->setParameter(':method', $method);
174
            $where = 'andWhere';
175
        }
176
177 2
        $dateTime = new \DateTime();
178
        // Filter
179
        $qb
180 2
            ->$where($qb->expr()->orX(
181 2
                $qb->expr()->isNull('j.whenAt'),
182 2
                                        $qb->expr()->lte('j.whenAt', ':whenAt')
183
            ))
184 2
            ->andWhere($qb->expr()->orX(
185 2
                $qb->expr()->isNull('j.expiresAt'),
186 2
                $qb->expr()->gt('j.expiresAt', ':expiresAt')
187
            ))
188 2
            ->andWhere('j.locked is NULL')
189 2
            ->setParameter(':whenAt', $dateTime)
190 2
            ->setParameter(':expiresAt', $dateTime);
191
192 2
        $query = $qb->getQuery();
193
194 2
        return $query->getSingleScalarResult();
195
    }
196
197
    /**
198
     * For ORM it's prudent to wrap things in a transaction.
199
     *
200
     * @param $i
201
     * @param $count
202
     * @param array $stalledJobs
203
     * @param $countProcessed
204
     */
205 1
    protected function runStalledLoop($i, $count, array $stalledJobs, &$countProcessed)
206
    {
207
        /** @var EntityManager $objectManager */
208 1
        $objectManager = $this->getObjectManager();
209
        try {
210 1
            $objectManager->beginTransaction();
211 1
            parent::runStalledLoop($i, $count, $stalledJobs, $countProcessed);
212 1
            $objectManager->commit();
213
        } catch (\Exception $exception) {
214
            $objectManager->rollback();
215
216
            // Try again
217
            parent::runStalledLoop($i, $count, $stalledJobs, $countProcessed);
218
        }
219 1
    }
220
221
    /**
222
     * Get Jobs statuses.
223
     */
224 2
    public function getStatus()
225
    {
226 2
        $result = [];
227 2
        $this->getStatusByEntityName($this->getObjectName(), $result);
228 2
        $this->getStatusByEntityName($this->getArchiveObjectName(), $result);
229
230 2
        $finalResult = [];
231 2
        foreach ($result as $key => $item) {
232 1
            ksort($item);
233 1
            foreach ($item as $status => $count) {
234 1
                if (isset($finalResult[$key][$status])) {
235
                    $finalResult[$key][$status] += $count;
236
                } else {
237 1
                    $finalResult[$key][$status] = $count;
238
                }
239
            }
240
        }
241
242 2
        return $finalResult;
243
    }
244
245
    /**
246
     * @param string $entityName
247
     */
248 2
    protected function getStatusByEntityName($entityName, array &$result)
249
    {
250
        /** @var EntityManager $objectManager */
251 2
        $objectManager = $this->getObjectManager();
252 2
        $result1 = $objectManager->getRepository($entityName)->createQueryBuilder('j')->select('j.workerName, j.method, j.status, count(j) as c')
253 2
            ->groupBy('j.workerName, j.method, j.status')->getQuery()->getArrayResult();
254
255 2
        foreach ($result1 as $item) {
256 1
            $method = $item['workerName'].'->'.$item['method'].'()';
257 1
            if (!isset($result[$method])) {
258 1
                $result[$method] = [BaseJob::STATUS_NEW => 0,
259
                    BaseJob::STATUS_RUNNING => 0,
260
                    RetryableJob::STATUS_EXPIRED => 0,
261
                    RetryableJob::STATUS_MAX_ERROR => 0,
262
                    RetryableJob::STATUS_MAX_STALLED => 0,
263
                    RetryableJob::STATUS_MAX_RETRIES => 0,
264
                    BaseJob::STATUS_SUCCESS => 0,
265
                    BaseJob::STATUS_ERROR => 0, ];
266
            }
267 1
            $result[$method][$item['status']] += intval($item['c']);
268
        }
269 2
    }
270
271
    /**
272
     * Get the next job to run (can be filtered by workername and method name).
273
     *
274
     * @param string $workerName
275
     * @param string $methodName
276
     * @param bool   $prioritize
277
     *
278
     * @return Job|null
279
     */
280 6
    public function getJob($workerName = null, $methodName = null, $prioritize = true, $runId = null)
281
    {
282 6
        $uniqid = uniqid(gethostname().'-'.getmypid(), true);
283 6
        $hash = hash('sha256', $uniqid);
0 ignored issues
show
Unused Code introduced by
$hash 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...
284
285
        /** @var EntityManager $objectManager */
286 6
        $objectManager = $this->getObjectManager();
287
288 6
        $objectManager->beginTransaction();
289
290
        /** @var EntityRepository $repository */
291 6
        $repository = $this->getRepository();
292 6
        $qb = $repository->createQueryBuilder('j');
293 6
        $dateTime = new \DateTime();
294
        $qb
295 6
            ->select('j')
296 6
            ->where('j.status = :status')->setParameter(':status', BaseJob::STATUS_NEW)
297 6
            ->andWhere('j.locked is NULL')
298 6
            ->andWhere($qb->expr()->orX(
299 6
                $qb->expr()->isNull('j.whenAt'),
300 6
                        $qb->expr()->lte('j.whenAt', ':whenAt')
301
            ))
302 6
            ->andWhere($qb->expr()->orX(
303 6
                $qb->expr()->isNull('j.expiresAt'),
304 6
                        $qb->expr()->gt('j.expiresAt', ':expiresAt')
305
            ))
306 6
            ->setParameter(':whenAt', $dateTime)
307 6
            ->setParameter(':expiresAt', $dateTime);
308
309 6
        $this->addWorkerNameCriterion($qb, $workerName, $methodName);
310
311 6
        if ($prioritize) {
312 6
            $qb->add('orderBy', 'j.priority DESC, j.whenAt ASC');
0 ignored issues
show
Documentation introduced by
'j.priority DESC, j.whenAt ASC' is of type string, but the function expects a object<Doctrine\ORM\Query\Expr\Base>.

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...
313
        } else {
314
            $qb->orderBy('j.whenAt', 'ASC');
315
        }
316 6
        $qb->setMaxResults(1);
317
318
        /** @var QueryBuilder $qb */
319 6
        $query = $qb->getQuery();
320 6
        $query->setLockMode(LockMode::PESSIMISTIC_WRITE);
321 6
        $jobs = $query->getResult();
322
323 6
        if ($jobs) {
324
            /** @var Job $job */
325 5
            $job = $jobs[0];
326 5
            $job->setLocked(true);
327 5
            $job->setLockedAt(new \DateTime());
328 5
            $job->setStatus(BaseJob::STATUS_RUNNING);
329 5
            $job->setRunId($runId);
330 5
            $objectManager->commit();
331 5
            $objectManager->flush();
332 5
            return $job;
333
        }
334
335 3
        $objectManager->rollback();
336
337 3
        return null;
338
    }
339
340
    /**
341
     * Tries to update the nearest job as a batch.
342
     *
343
     * @param \Dtc\QueueBundle\Model\Job $job
344
     *
345
     * @return mixed|null
346
     */
347 1
    public function updateNearestBatch(\Dtc\QueueBundle\Model\Job $job)
348
    {
349 1
        $oldJob = null;
350
        do {
351
            try {
352
                /** @var EntityManager $entityManager */
353 1
                $entityManager = $this->getObjectManager();
354 1
                $entityManager->beginTransaction();
355
356
                /** @var QueryBuilder $queryBuilder */
357 1
                $queryBuilder = $this->getRepository()->createQueryBuilder('j');
358 1
                $queryBuilder->select()
359 1
                    ->where('j.crcHash = :crcHash')
360 1
                    ->andWhere('j.status = :status')
361 1
                    ->setParameter(':status', BaseJob::STATUS_NEW)
362 1
                    ->setParameter(':crcHash', $job->getCrcHash())
363 1
                    ->orderBy('j.whenAt', 'ASC')
364 1
                    ->setMaxResults(1);
365 1
                $oldJob = $queryBuilder->getQuery()->getSingleResult();
366
367 1
                if (!$oldJob) {
368
                    return null;
369
                }
370
371 1
                $oldJob->setPriority(max($job->getPriority(), $oldJob->getPriority()));
372 1
                $oldJob->setWhenAt(min($job->getWhenAt(), $oldJob->getWhenAt()));
373
374 1
                $entityManager->persist($oldJob);
375 1
                $entityManager->commit();
376 1
                $this->flush();
377
            } catch (\Exception $exception) {
378
                $entityManager->rollback();
379
            }
380 1
        } while (null === $oldJob);
381
382 1
        return $oldJob;
383
    }
384
}
385