-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCuckooClock.php
More file actions
90 lines (75 loc) · 1.93 KB
/
CuckooClock.php
File metadata and controls
90 lines (75 loc) · 1.93 KB
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
<?php
/**
* @copyright 2009-2020 Red Matter Ltd (UK)
*/
namespace RedMatter\Examples;
use DateTime;
use DateTimeZone;
use RedMatter\Chrono\Clock\CalendarClockInterface;
use RedMatter\Chrono\Duration\Seconds;
use RedMatter\Chrono\Time\CalendarTime;
/**
* Models a clock that
* - plays a music at the 0-th minute of every hour
* - Cuckoos N times at the 0th minute of the N-th hour
* - Cuckoos once every 15 minutes, except at the 0th minute
*/
class CuckooClock
{
/** @var CalendarClockInterface */
private $clock;
/** @var DateTimeZone */
private $timeZone;
public $cuckoo = 0;
public $music = 0;
public function __construct(CalendarClockInterface $clock, DateTimeZone $timeZone)
{
$this->clock = $clock;
$this->timeZone = $timeZone;
}
public function music()
{
$this->music++;
}
private function cuckoo()
{
$this->cuckoo++;
}
private function announceTime(CalendarTime $time)
{
list($hours, $minutes, $seconds) = array_map(
function ($v) {
return (int)ltrim($v, '0');
},
explode(' ', $time->format('h i s', $this->timeZone))
);
if ($seconds) {
return;
}
if ($minutes % 15) {
return;
}
// announce every 15 minutes except at 00 minutes
if ($minutes !== 0) {
$this->cuckoo();
return;
}
// announce the whole hour
$this->music();
while ($hours--) {
$this->cuckoo();
}
}
public function runUntil(DateTime $until)
{
$timeUntil = CalendarTime::fromDateTime($until);
while (true) {
$now = $this->clock->now();
if ($now->isAfter($timeUntil)) {
break;
}
$this->announceTime($now);
$this->clock->elapse(new Seconds(1.0));
}
}
}