1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Speicher210\BusinessHours\Day\Time; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Builder for Time. |
7
|
|
|
*/ |
8
|
|
|
class TimeBuilder |
9
|
|
|
{ |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Create a new Time from an array. |
13
|
|
|
* |
14
|
|
|
* @param array $data The data. |
15
|
|
|
* @return Time |
16
|
|
|
*/ |
17
|
|
|
public static function fromArray(array $data) |
18
|
|
|
{ |
19
|
|
|
if (!isset($data['hours'])) { |
20
|
|
|
throw new \InvalidArgumentException('Array is not valid.'); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
return new Time( |
24
|
|
|
$data['hours'], |
25
|
|
|
isset($data['minutes']) ? $data['minutes'] : 0, |
26
|
|
|
isset($data['seconds']) ? $data['seconds'] : 0 |
27
|
|
|
); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Create a new time from a string. |
32
|
|
|
* |
33
|
|
|
* @param string $time The time as a string. |
34
|
|
|
* @return Time |
35
|
|
|
* @throws \InvalidArgumentException If the passed time is invalid. |
36
|
|
|
*/ |
37
|
|
|
public static function fromString($time) |
38
|
|
|
{ |
39
|
|
|
if (empty($time)) { |
40
|
|
|
throw new \InvalidArgumentException('Invalid time "".'); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
try { |
44
|
|
|
$date = new \DateTime($time); |
45
|
|
|
} catch (\Exception $e) { |
46
|
|
|
throw new \InvalidArgumentException(sprintf('Invalid time "%s".', $time), 0, $e); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$return = static::fromDate($date); |
50
|
|
|
if (strpos($time, '24') === 0) { |
51
|
|
|
$return->setHours(24); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $return; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Create a new time from a date. |
59
|
|
|
* |
60
|
|
|
* @param \DateTime $date The date. |
61
|
|
|
* @return Time |
62
|
|
|
*/ |
63
|
|
|
public static function fromDate(\DateTime $date) |
64
|
|
|
{ |
65
|
|
|
return new Time($date->format('H'), $date->format('i'), $date->format('s')); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Create a new time from seconds. |
70
|
|
|
* |
71
|
|
|
* @param integer $seconds The seconds. |
72
|
|
|
* @return Time |
73
|
|
|
*/ |
74
|
|
|
public static function fromSeconds($seconds) |
75
|
|
|
{ |
76
|
|
|
$seconds = (int)$seconds; |
77
|
|
|
|
78
|
|
|
if ($seconds < 0 || $seconds > 86400) { |
79
|
|
|
throw new \InvalidArgumentException(sprintf('Invalid time "%s".', $seconds)); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$data = array( |
83
|
|
|
'hours' => $seconds / 3600, |
84
|
|
|
'minutes' => $seconds / 60 % 60, |
85
|
|
|
'seconds' => $seconds % 60 |
86
|
|
|
); |
87
|
|
|
|
88
|
|
|
return self::fromArray($data); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|