-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDate.php
73 lines (62 loc) · 1.99 KB
/
Date.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
namespace ICanBoogie\HTTP\Headers;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
/**
* Representation of a 'Date' header field.
*
* @property-read bool $is_empty
* Whether the value of the {@see Date} is empty.
* @property-read int|null $timestamp
* The Unix timestamp in seconds, or null if {@see Date} is empty.
*
* @link https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
*/
readonly class Date
{
public static function from(
DateTimeInterface|int|string|null $source
): self {
$timezone = null;
if ($source === null) {
return new self();
} elseif ($source instanceof DateTimeInterface) {
$timezone = $source->getTimezone();
$source = $source->format('Y-m-d\TH:i:s.u');
} elseif (is_int($source)) {
$timezone = 'UTC';
$source = "@{$source}";
}
if (is_string($timezone)) {
$timezone = new DateTimeZone($timezone);
}
$datetime = new DateTimeImmutable($source, $timezone);
return new self($datetime);
}
private function __construct(
public ?DateTimeInterface $delegate = null
) {
}
/**
* Formats the instance according to the RFC 1123.
*/
public function __toString(): string
{
return $this->is_empty
? ''
: str_replace('+0000', 'GMT', $this->delegate->format(DateTimeInterface::RFC1123));
}
/**
* The timestamp of a {@see \DateTime} or {@see DateTimeImmutable} created with "0000-00-00".
*/
private const EMPTY_TIMESTAMP = -62169984000;
public function __get($property)
{
return match ($property) {
'is_empty' => $this->delegate === null || $this->timestamp == self::EMPTY_TIMESTAMP,
'timestamp' => $this->delegate?->getTimestamp(),
default => throw new \BadMethodCallException('Undefined property: ' . get_class($this) . '::' . $property),
};
}
}