-
Notifications
You must be signed in to change notification settings - Fork 3
/
DoctrineUuidEntityId.php
67 lines (55 loc) · 1.51 KB
/
DoctrineUuidEntityId.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
<?php
declare(strict_types=1);
namespace DDDStarterPack\Aggregate\Infrastructure\Doctrine;
use DDDStarterPack\Aggregate\Domain\EntityId;
use DDDStarterPack\Aggregate\Domain\UuidEntityId;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\GuidType;
abstract class DoctrineUuidEntityId extends GuidType
{
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return $value instanceof UuidEntityId ? $value->value() : $value ?? null;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
$value = $this->prepareValue($value);
if (
is_null($value)
|| (!$this->isValidUuid($value) && !$this->isCustomValid())
) {
return $value;
}
$className = $this->getFQCN();
return $className::createFrom($value);
}
/**
* @param mixed $value
*
* @return null|string
*/
private function prepareValue(mixed $value): null|string
{
return match (true) {
is_object($value), is_null($value) => null,
default => (string) $value
};
}
/**
* @param string $value
*
* @return bool
*/
private function isValidUuid(string $value): bool
{
return UuidEntityId::isValidUuid($value);
}
protected function isCustomValid(): bool
{
return false;
}
/**
* @return class-string<EntityId>
*/
abstract protected function getFQCN(): string;
}