| 199 |
lars |
1 |
<?php namespace Clockwork\Request\Timeline;
|
|
|
2 |
|
|
|
3 |
// Data structure representing collection of time-based events
|
|
|
4 |
class Timeline
|
|
|
5 |
{
|
|
|
6 |
// Timeline events
|
|
|
7 |
public $events = [];
|
|
|
8 |
|
|
|
9 |
// Create a new timeline, optionally with existing events
|
|
|
10 |
public function __construct($events = [])
|
|
|
11 |
{
|
|
|
12 |
foreach ($events as $event) {
|
|
|
13 |
$this->create($event['description'], $event);
|
|
|
14 |
}
|
|
|
15 |
}
|
|
|
16 |
|
|
|
17 |
// Find or create a new event, takes description and optional data - name, start, end, duration, color, data
|
|
|
18 |
public function event($description, $data = [])
|
|
|
19 |
{
|
|
|
20 |
$name = isset($data['name']) ? $data['name'] : $description;
|
|
|
21 |
|
|
|
22 |
if ($event = $this->find($name)) return $event;
|
|
|
23 |
|
|
|
24 |
return $this->create($description, $data);
|
|
|
25 |
}
|
|
|
26 |
|
|
|
27 |
// Create a new event, takes description and optional data - name, start, end, duration, color, data
|
|
|
28 |
public function create($description, $data = [])
|
|
|
29 |
{
|
|
|
30 |
return $this->events[] = new Event($description, $data);
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
// Find event by name
|
|
|
34 |
public function find($name)
|
|
|
35 |
{
|
|
|
36 |
foreach ($this->events as $event) {
|
|
|
37 |
if ($event->name == $name) return $event;
|
|
|
38 |
}
|
|
|
39 |
}
|
|
|
40 |
|
|
|
41 |
// Merge another timeline instance into the current timeline
|
|
|
42 |
public function merge(Timeline $timeline)
|
|
|
43 |
{
|
|
|
44 |
$this->events = array_merge($this->events, $timeline->events);
|
|
|
45 |
|
|
|
46 |
return $this;
|
|
|
47 |
}
|
|
|
48 |
|
|
|
49 |
// Finalize timeline, ends all events, sorts them and returns as an array
|
|
|
50 |
public function finalize($start = null, $end = null)
|
|
|
51 |
{
|
|
|
52 |
foreach ($this->events as $event) {
|
|
|
53 |
$event->finalize($start, $end);
|
|
|
54 |
}
|
|
|
55 |
|
|
|
56 |
$this->sort();
|
|
|
57 |
|
|
|
58 |
return $this->toArray();
|
|
|
59 |
}
|
|
|
60 |
|
|
|
61 |
// Sort the timeline events by start time
|
|
|
62 |
public function sort()
|
|
|
63 |
{
|
|
|
64 |
usort($this->events, function ($a, $b) { return $a->start * 1000 - $b->start * 1000; });
|
|
|
65 |
}
|
|
|
66 |
|
|
|
67 |
// Return events as an array
|
|
|
68 |
public function toArray()
|
|
|
69 |
{
|
|
|
70 |
return array_map(function ($event) { return $event->toArray(); }, $this->events);
|
|
|
71 |
}
|
|
|
72 |
}
|