1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BsbPostponableJobStrategy\Job; |
4
|
|
|
|
5
|
|
|
use SlmQueue\Exception\RuntimeException; |
6
|
|
|
use SlmQueue\Job\JobInterface; |
7
|
|
|
use Traversable; |
8
|
|
|
|
9
|
|
|
trait PostponableJobTrait |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @inheritdoc |
13
|
|
|
*/ |
14
|
10 |
|
public function postponeUntil($spec, $releaseDelay = null) |
15
|
|
|
{ |
16
|
10 |
|
$added = 0; |
17
|
|
|
|
18
|
10 |
|
if (is_integer($spec)) { |
19
|
7 |
|
$added += $this->addPostponeUntil($spec); |
20
|
7 |
|
} |
21
|
|
|
|
22
|
10 |
|
if ($spec instanceof JobInterface) { |
23
|
4 |
|
if (!$spec->getId()) { |
24
|
1 |
|
throw new RuntimeException( |
25
|
|
|
"JobInterface does not have an id. You should push it to a queue first." |
26
|
1 |
|
); |
27
|
|
|
} |
28
|
|
|
|
29
|
3 |
|
$added += $this->addPostponeUntil($spec->getId()); |
30
|
3 |
|
} |
31
|
|
|
|
32
|
9 |
|
if (is_array($spec) || $spec instanceof Traversable) { |
33
|
3 |
|
foreach ($spec as $value) { |
34
|
3 |
|
$added += $this->postponeUntil($value); |
35
|
3 |
|
} |
36
|
3 |
|
} |
37
|
|
|
|
38
|
9 |
|
if ((int) $releaseDelay) { |
39
|
3 |
|
$this->setMetadata('__postponeReleaseDelay', (int) $releaseDelay); |
40
|
3 |
|
} |
41
|
|
|
|
42
|
9 |
|
return $added; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param int $jobId An id of a job |
47
|
|
|
* @return int the number of the id's added |
48
|
|
|
*/ |
49
|
9 |
|
private function addPostponeUntil($jobId) |
50
|
|
|
{ |
51
|
9 |
|
$postpone = $this->getMetadata('__postponeUntil', []); |
52
|
9 |
|
$count = count($postpone); |
53
|
9 |
|
$postpone[] = (int) $jobId; |
54
|
9 |
|
$postpone = array_unique($postpone); |
55
|
|
|
|
56
|
9 |
|
$this->setMetadata('__postponeUntil', $postpone); |
57
|
|
|
|
58
|
9 |
|
return count($postpone) - $count; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Set metadata |
63
|
|
|
* |
64
|
|
|
* @param string|int|array|\Traversable $spec |
65
|
|
|
* @param mixed $value |
66
|
|
|
*/ |
67
|
|
|
abstract function setMetadata($spec, $value = null); |
|
|
|
|
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Get metadata |
71
|
|
|
* |
72
|
|
|
* @param null|string|int $key |
73
|
|
|
* @return mixed |
74
|
|
|
*/ |
75
|
|
|
abstract function getMetadata($key = null, $default = null); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
|
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.