-
-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathCastToDateTimeImmutable.php
More file actions
49 lines (38 loc) · 1.3 KB
/
CastToDateTimeImmutable.php
File metadata and controls
49 lines (38 loc) · 1.3 KB
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
<?php
declare(strict_types=1);
namespace EventSauce\ObjectHydrator\PropertyCasters;
use Attribute;
use DateTimeImmutable;
use DateTimeInterface;
use DateTimeZone;
use EventSauce\ObjectHydrator\ObjectMapper;
use EventSauce\ObjectHydrator\PropertyCaster;
use EventSauce\ObjectHydrator\PropertySerializer;
use function assert;
use function is_int;
#[Attribute(Attribute::TARGET_PARAMETER | Attribute::IS_REPEATABLE)]
final class CastToDateTimeImmutable implements PropertyCaster, PropertySerializer
{
public function __construct(private ?string $format = null, private ?string $timeZone = null)
{
}
public function cast(mixed $value, ObjectMapper $hydrator): mixed
{
if($value === null){
return null;
}
$timeZone = $this->timeZone ? new DateTimeZone($this->timeZone) : $this->timeZone;
if ($this->format !== null) {
return DateTimeImmutable::createFromFormat($this->format, $value, $timeZone);
}
if (is_int($value)) {
$value = "@$value";
}
return new DateTimeImmutable($value, $timeZone);
}
public function serialize(mixed $value, ObjectMapper $hydrator): mixed
{
assert($value instanceof DateTimeInterface);
return $value->format($this->format ?: 'Y-m-d H:i:s.uO');
}
}