1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace Sunfox\DateUtils; |
4
|
|
|
|
5
|
|
|
use DateTime as NativeDateTime; |
6
|
|
|
use InvalidArgumentException; |
7
|
|
|
|
8
|
|
|
final class Time implements ITime |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var int |
12
|
|
|
*/ |
13
|
|
|
private $seconds = 0; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @throws InvalidArgumentException |
17
|
|
|
*/ |
18
|
|
|
public function __construct(string $time) |
19
|
|
|
{ |
20
|
|
|
$this->seconds = $this->parseLetterExpression($time) ?: $this->parseTimeExpression($time); |
21
|
|
|
if (!$this->seconds) { |
22
|
|
|
throw new InvalidArgumentException('Cannot parse time value'); |
23
|
|
|
} |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function getSeconds(): int |
27
|
|
|
{ |
28
|
|
|
return $this->seconds; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function getMinutes(int $rounding = self::DEFAULT_ROUNDING): float |
32
|
|
|
{ |
33
|
|
|
return round($this->seconds / 60, $rounding); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function getHours(int $rounding = self::DEFAULT_ROUNDING): float |
37
|
|
|
{ |
38
|
|
|
return round($this->seconds / 60 / 60, $rounding); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function getTime(string $format = self::DEFAULT_FORMAT): string |
42
|
|
|
{ |
43
|
|
|
return (new NativeDateTime("@$this->seconds"))->format($format); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
private function parseLetterExpression(string $time): int |
47
|
|
|
{ |
48
|
|
|
if (preg_match( |
49
|
|
|
'/^(?:(?<h>\d+(?:[.,]\d+)?)(?:h|$))?(?:(?<m>\d+(?:[.,]\d+)?)(?:m|$))?(?:(?<s>\d+(?:[.,]\d+)?)(?:s|$))?$/i', |
50
|
|
|
trim($time), |
51
|
|
|
$m |
52
|
|
|
)) { |
53
|
|
|
return (int) ( |
54
|
|
|
(!empty($m['h']) ? str_replace(',', '.', $m['h']) * 60 * 60 : 0) + |
55
|
|
|
(!empty($m['m']) ? str_replace(',', '.', $m['m']) * 60 : 0) + |
56
|
|
|
(!empty($m['s']) ? str_replace(',', '.', $m['s']) : 0) |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return 0; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function parseTimeExpression(string $time): int |
64
|
|
|
{ |
65
|
|
|
if (preg_match('/^(\d+):(\d+)(?::(\d+))?$/', trim($time), $m)) { |
66
|
|
|
return (int) ( |
67
|
|
|
($m[1] * 60 * 60) + ($m[2] * 60) + (!empty($m[3]) ? $m[3] : 0) |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return 0; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|