-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDateTimeTransformerAttribute.php
More file actions
54 lines (43 loc) · 1.25 KB
/
DateTimeTransformerAttribute.php
File metadata and controls
54 lines (43 loc) · 1.25 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
50
51
52
53
54
<?php
declare(strict_types=1);
namespace Picamator\TransferObject\Transfer\Attribute\Transformer;
use Attribute;
use DateTimeInterface;
/**
* @api
*/
#[Attribute(Attribute::TARGET_CLASS_CONSTANT)]
final readonly class DateTimeTransformerAttribute implements TransformerAttributeInterface
{
use InvalidTypeAssertTrait;
private const string DATE_TIME_FORMAT = DateTimeInterface::ATOM;
/**
* @param class-string<\DateTime|\DateTimeImmutable> $typeName
*/
public function __construct(private string $typeName)
{
}
public function fromArray(mixed $data): DateTimeInterface
{
$type = \gettype($data);
if ($type === 'string') {
/** @var string $data */
return new $this->typeName($data);
}
if ($type === 'integer' || $type === 'double') {
/** @var int|float $data */
return $this->typeName::createFromTimestamp($data);
}
if ($type === 'object' && $data instanceof DateTimeInterface) {
return $data;
}
$this->throwInvalidType($data);
}
/**
* @param DateTimeInterface $data
*/
public function toArray(mixed $data): string
{
return $data->format(self::DATE_TIME_FORMAT);
}
}