1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Traits\TimeStamp; |
4
|
|
|
|
5
|
|
|
use Doctrine\DBAL\Types\Type; |
6
|
|
|
use Doctrine\ORM\Events; |
7
|
|
|
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder; |
8
|
|
|
use Doctrine\ORM\Mapping\Builder\FieldBuilder; |
9
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Interfaces\TimeStamp\CreationTimestampFieldInterface; |
10
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\MappingHelper; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Trait TimestampFieldTrait |
14
|
|
|
* |
15
|
|
|
* An Immutable creation timestamp. It is null until it is saved (and reloaded) |
16
|
|
|
* |
17
|
|
|
* Notice the use of a lifecyle event to handle setting the pre persist creation timestamp |
18
|
|
|
* |
19
|
|
|
* @package EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Traits\DateTime |
20
|
|
|
*/ |
21
|
|
|
trait CreationTimestampFieldTrait |
22
|
|
|
{ |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var \DateTimeImmutable|null |
26
|
|
|
*/ |
27
|
|
|
private $creationTimestamp; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
31
|
|
|
* @param ClassMetadataBuilder $builder |
32
|
|
|
*/ |
33
|
2 |
|
public static function metaForCreationTimestamp(ClassMetadataBuilder $builder): void |
34
|
|
|
{ |
35
|
2 |
|
$builder->addLifecycleEvent('prePersistCreationTimestamp', Events::prePersist); |
36
|
2 |
|
$fieldBuilder = new FieldBuilder( |
37
|
2 |
|
$builder, |
38
|
|
|
[ |
39
|
2 |
|
'fieldName' => CreationTimestampFieldInterface::PROP_CREATION_TIMESTAMP, |
40
|
|
|
'type' => Type::DATETIME_IMMUTABLE, |
41
|
|
|
] |
42
|
|
|
); |
43
|
|
|
$fieldBuilder |
44
|
2 |
|
->columnName(MappingHelper::getColumnNameForField( |
45
|
2 |
|
CreationTimestampFieldInterface::PROP_CREATION_TIMESTAMP |
46
|
|
|
)) |
47
|
2 |
|
->nullable(false) |
48
|
2 |
|
->build(); |
49
|
2 |
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @throws \Exception |
53
|
|
|
*/ |
54
|
2 |
|
public function prePersistCreationTimestamp(): void |
55
|
|
|
{ |
56
|
2 |
|
if (null === $this->creationTimestamp) { |
57
|
2 |
|
$this->creationTimestamp = new \DateTimeImmutable(); |
58
|
|
|
} |
59
|
2 |
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return \DateTimeImmutable|null |
63
|
|
|
*/ |
64
|
2 |
|
public function getCreationTimestamp(): ?\DateTimeImmutable |
65
|
|
|
{ |
66
|
2 |
|
return $this->creationTimestamp; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|