Job::afterRun()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
ccs 0
cts 4
cp 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
namespace App\Queue;
3
4
use yii\base\Component;
5
use yii\queue\JobInterface;
6
use yii\queue\Queue;
7
8
abstract class Job extends Component implements JobInterface
9
{
10
    /**
11
     * @var Queue $queue queue instace.
12
     */
13
    private $queue;
14
15
    /**
16
     * Gets queue instance
17
     *
18
     * @return Queue $queue queue instance.
19
     */
20
    protected function getQueue(): Queue
21
    {
22
        return $this->queue;
23
    }
24
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function execute($queue)
29
    {
30
        $this->queue = $queue;
31
32
        if (!$this->beforeRun()) {
33
            throw new JobPreventedException();
34
        }
35
36
        $result = $this->run();
37
        $this->afterRun($result);
38
    }
39
40
    /**
41
     * Invoke before running job.
42
     *
43
     * @return bool whether the job is valid.
44
     */
45
    protected function beforeRun(): bool
46
    {
47
        $event = new JobEvent();
48
        $this->trigger(JobEvent::BEFORE_RUN, $event);
49
        return $event->isValid;
50
    }
51
52
    /**
53
     * Invoke after finishing job.
54
     */
55
    protected function afterRun($result)
56
    {
57
        $event = new JobEvent([
58
            'result' => $result
59
        ]);
60
        $this->trigger(JobEvent::AFTER_RUN, $event);
61
    }
62
63
    /**
64
     * Run job.
65
     *
66
     * @return mixed job result.
67
     */
68
    abstract protected function run();
69
}
70