1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Webfactor\Laravel\OpeningHours\Entities; |
4
|
|
|
|
5
|
|
|
use DateTime; |
6
|
|
|
use DateTimeInterface; |
7
|
|
|
use Webfactor\Laravel\OpeningHours\Exceptions\InvalidTimeString; |
8
|
|
|
|
9
|
|
|
class Time |
10
|
|
|
{ |
11
|
|
|
/** @var int */ |
12
|
|
|
protected $hours; |
13
|
|
|
|
14
|
|
|
/** @var int */ |
15
|
|
|
protected $minutes; |
16
|
|
|
|
17
|
41 |
|
protected function __construct(int $hours, int $minutes) |
18
|
|
|
{ |
19
|
41 |
|
$this->hours = $hours; |
20
|
41 |
|
$this->minutes = $minutes; |
21
|
41 |
|
} |
22
|
|
|
|
23
|
42 |
|
public static function fromString(string $string): self |
24
|
|
|
{ |
25
|
42 |
|
if (! preg_match('/^([0-1][0-9])|(2[0-4]):[0-5][0-9]$/', $string)) { |
26
|
1 |
|
throw InvalidTimeString::forString($string); |
27
|
|
|
} |
28
|
|
|
|
29
|
41 |
|
list($hours, $minutes) = explode(':', $string); |
30
|
|
|
|
31
|
41 |
|
return new self($hours, $minutes); |
32
|
|
|
} |
33
|
|
|
|
34
|
11 |
|
public static function fromDateTime(DateTimeInterface $dateTime): self |
35
|
|
|
{ |
36
|
11 |
|
return self::fromString($dateTime->format('H:i')); |
37
|
|
|
} |
38
|
|
|
|
39
|
21 |
|
public function isSame(Time $time): bool |
40
|
|
|
{ |
41
|
21 |
|
return (string) $this === (string) $time; |
42
|
|
|
} |
43
|
|
|
|
44
|
20 |
|
public function isAfter(Time $time): bool |
45
|
|
|
{ |
46
|
20 |
|
if ($this->isSame($time)) { |
47
|
1 |
|
return false; |
48
|
|
|
} |
49
|
|
|
|
50
|
20 |
|
if ($this->hours > $time->hours) { |
51
|
20 |
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
15 |
|
return $this->hours === $time->hours && $this->minutes >= $time->minutes; |
55
|
|
|
} |
56
|
|
|
|
57
|
18 |
|
public function isBefore(Time $time): bool |
58
|
|
|
{ |
59
|
18 |
|
if ($this->isSame($time)) { |
60
|
4 |
|
return false; |
61
|
|
|
} |
62
|
|
|
|
63
|
18 |
|
return ! $this->isAfter($time); |
64
|
|
|
} |
65
|
|
|
|
66
|
17 |
|
public function isSameOrAfter(Time $time): bool |
67
|
|
|
{ |
68
|
17 |
|
return $this->isSame($time) || $this->isAfter($time); |
69
|
|
|
} |
70
|
|
|
|
71
|
32 |
|
public function toDateTime(): DateTime |
72
|
|
|
{ |
73
|
32 |
|
return (new DateTime('1970-01-01 00:00:00'))->setTime($this->hours, $this->minutes); |
74
|
|
|
} |
75
|
|
|
|
76
|
32 |
|
public function format(string $format = 'H:i'): string |
77
|
|
|
{ |
78
|
32 |
|
return $this->toDateTime()->format($format); |
79
|
|
|
} |
80
|
|
|
|
81
|
25 |
|
public function __toString(): string |
82
|
|
|
{ |
83
|
25 |
|
return $this->format(); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|