1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Hyde\Support\Models; |
6
|
|
|
|
7
|
|
|
use DateTime; |
8
|
|
|
use Stringable; |
9
|
|
|
use BadMethodCallException; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Parse a date string and create normalized formats. |
13
|
|
|
*/ |
14
|
|
|
class DateString implements Stringable |
15
|
|
|
{ |
16
|
|
|
/** Date format constants */ |
17
|
|
|
final public const DATETIME_FORMAT = 'c'; |
18
|
|
|
final public const SENTENCE_FORMAT = 'l M jS, Y, \a\t g:ia'; |
19
|
|
|
final public const SHORT_FORMAT = 'M jS, Y'; |
20
|
|
|
|
21
|
|
|
/** The original date string. */ |
22
|
|
|
public readonly string $string; |
23
|
|
|
|
24
|
|
|
/** The parsed date object. */ |
25
|
|
|
public readonly DateTime $dateTimeObject; |
26
|
|
|
|
27
|
|
|
/** The machine-readable datetime string. */ |
28
|
|
|
public readonly string $datetime; |
29
|
|
|
|
30
|
|
|
/** The human-readable sentence string. */ |
31
|
|
|
public readonly string $sentence; |
32
|
|
|
|
33
|
|
|
/** Shorter version of the sentence string. */ |
34
|
|
|
public readonly string $short; |
35
|
|
|
|
36
|
|
|
public function __construct(string $string) |
37
|
|
|
{ |
38
|
|
|
$this->string = $string; |
|
|
|
|
39
|
|
|
$this->dateTimeObject = new DateTime($this->string); |
|
|
|
|
40
|
|
|
|
41
|
|
|
$this->datetime = $this->dateTimeObject->format(self::DATETIME_FORMAT); |
|
|
|
|
42
|
|
|
$this->sentence = $this->dateTimeObject->format(self::SENTENCE_FORMAT); |
|
|
|
|
43
|
|
|
$this->short = $this->dateTimeObject->format(self::SHORT_FORMAT); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function __toString(): string |
47
|
|
|
{ |
48
|
|
|
return $this->short; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function __call(string $method, array $arguments): mixed |
52
|
|
|
{ |
53
|
|
|
if (method_exists($this->dateTimeObject, $method)) { |
54
|
|
|
return $this->dateTimeObject->$method(...$arguments); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
throw new BadMethodCallException("Method {$method} does not exist on the DateTime object."); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|