1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\queue\sync;
use Yii;
use yii\base\Application;
use yii\base\InvalidArgumentException;
use yii\queue\Queue as BaseQueue;
/**
* Sync Queue.
*
* @author Roman Zhuravlev <zhuravljov@gmail.com>
*/
class Queue extends BaseQueue
{
/**
* @var bool
*/
public $handle = false;
/**
* @var array of payloads
*/
private $payloads = [];
/**
* @var int last pushed ID
*/
private $pushedId = 0;
/**
* @var int started ID
*/
private $startedId = 0;
/**
* @var int last finished ID
*/
private $finishedId = 0;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->handle) {
Yii::$app->on(Application::EVENT_AFTER_REQUEST, function () {
ob_start();
$this->run();
ob_end_clean();
});
}
}
/**
* Runs all jobs from queue.
*/
public function run()
{
while (($payload = array_shift($this->payloads)) !== null) {
list($ttr, $message) = $payload;
$this->startedId = $this->finishedId + 1;
$this->handleMessage($this->startedId, $message, $ttr, 1);
$this->finishedId = $this->startedId;
$this->startedId = 0;
}
}
/**
* @inheritdoc
*/
protected function pushMessage($message, $ttr, $delay, $priority)
{
array_push($this->payloads, [$ttr, $message]);
return ++$this->pushedId;
}
/**
* @inheritdoc
*/
public function status($id)
{
if (!is_int($id) || $id <= 0 || $id > $this->pushedId) {
throw new InvalidArgumentException("Unknown messages ID: $id.");
}
if ($id <= $this->finishedId) {
return self::STATUS_DONE;
}
if ($id === $this->startedId) {
return self::STATUS_RESERVED;
}
return self::STATUS_WAITING;
}
}