1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Scheduler; |
4
|
|
|
|
5
|
|
|
use Scheduler\Action\ActionIterator; |
6
|
|
|
use Scheduler\Job\JobInterface; |
7
|
|
|
use Scheduler\Job\JobIterator; |
8
|
|
|
use DateTimeInterface; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class Scheduler |
12
|
|
|
* @package Scheduler |
13
|
|
|
* @author Aleh Hutnikau, <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
class Scheduler implements SchedulerInterface |
16
|
|
|
{ |
17
|
|
|
/** |
18
|
|
|
* @var JobInterface[] |
19
|
|
|
*/ |
20
|
|
|
protected $jobs = []; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Scheduler constructor. |
24
|
|
|
* @param JobInterface[] $jobs |
25
|
|
|
*/ |
26
|
15 |
|
public function __construct(array $jobs = []) |
27
|
|
|
{ |
28
|
15 |
|
foreach ($jobs as $job) { |
29
|
12 |
|
$this->addJob($job); |
30
|
15 |
|
} |
31
|
15 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @inheritdoc |
35
|
|
|
*/ |
36
|
13 |
|
public function getIterator(DateTimeInterface $from, DateTimeInterface $to = null, $inc = true) |
37
|
|
|
{ |
38
|
13 |
|
$iterator = new \ArrayIterator(); |
39
|
13 |
|
if ($to === null) { |
40
|
2 |
|
$to = new \DateTime('now', $from->getTimezone()); |
41
|
2 |
|
} |
42
|
13 |
|
foreach ($this->jobs as $job) { |
43
|
13 |
|
$this->appendActions($iterator, $job, $from, $to, $inc); |
44
|
13 |
|
} |
45
|
13 |
|
$this->sortActions($iterator); |
46
|
13 |
|
return $iterator; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param JobInterface $job |
51
|
|
|
* @return mixed|void |
52
|
|
|
*/ |
53
|
13 |
|
public function addJob(JobInterface $job) |
54
|
|
|
{ |
55
|
13 |
|
$this->jobs[] = $job; |
56
|
13 |
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param \ArrayIterator $iterator - iterator to append actions |
60
|
|
|
* @param JobInterface $job |
61
|
|
|
* @param DateTimeInterface $from |
62
|
|
|
* @param DateTimeInterface $to |
63
|
|
|
* @param $inc |
64
|
|
|
*/ |
65
|
13 |
|
protected function appendActions(\ArrayIterator $iterator, JobInterface $job, DateTimeInterface $from, DateTimeInterface $to, $inc) |
66
|
|
|
{ |
67
|
13 |
|
$actionIterator = new ActionIterator($job, $from, $to, $inc); |
68
|
13 |
|
foreach ($actionIterator as $action) { |
69
|
12 |
|
$iterator->append($action); |
70
|
13 |
|
} |
71
|
13 |
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Sort actions by execution time |
75
|
|
|
* @param \ArrayIterator $iterator - iterator to append actions |
76
|
|
|
*/ |
77
|
|
|
protected function sortActions(\ArrayIterator $iterator) |
78
|
|
|
{ |
79
|
13 |
|
$iterator->uasort(function ($a, $b) { |
80
|
6 |
|
return $a->getTime()->getTimestamp() - $b->getTime()->getTimestamp(); |
81
|
13 |
|
}); |
82
|
13 |
|
} |
83
|
|
|
} |
84
|
|
|
|