1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ecodev\Felix\DBAL\Types; |
6
|
|
|
|
7
|
|
|
use BackedEnum; |
8
|
|
|
use Doctrine\DBAL\Platforms\AbstractPlatform; |
9
|
|
|
use Doctrine\DBAL\Types\Type; |
10
|
|
|
use Exception; |
11
|
|
|
use InvalidArgumentException; |
12
|
|
|
use ReflectionClass; |
13
|
|
|
|
14
|
|
|
abstract class EnumType extends Type |
15
|
|
|
{ |
16
|
3 |
|
final public function getQuotedPossibleValues(): string |
17
|
|
|
{ |
18
|
3 |
|
return implode(', ', array_map(fn (string $str) => "'" . $str . "'", $this->getPossibleValues())); |
19
|
|
|
} |
20
|
|
|
|
21
|
2 |
|
public function getSqlDeclaration(array $column, AbstractPlatform $platform): string |
22
|
|
|
{ |
23
|
2 |
|
$sql = 'ENUM(' . $this->getQuotedPossibleValues() . ')'; |
24
|
|
|
|
25
|
2 |
|
return $sql; |
26
|
|
|
} |
27
|
|
|
|
28
|
3 |
|
public function convertToPHPValue(mixed $value, AbstractPlatform $platform): null|string|BackedEnum |
29
|
|
|
{ |
30
|
3 |
|
if ($value === null || '' === $value) { |
31
|
1 |
|
return null; |
32
|
|
|
} |
33
|
|
|
|
34
|
3 |
|
if (!in_array($value, $this->getPossibleValues(), true)) { |
35
|
2 |
|
throw new InvalidArgumentException("Invalid '" . $value . "' value fetched from database for enum " . $this->getName()); |
36
|
|
|
} |
37
|
|
|
|
38
|
1 |
|
return (string) $value; |
39
|
|
|
} |
40
|
|
|
|
41
|
3 |
|
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string |
42
|
|
|
{ |
43
|
3 |
|
if ($value === null || '' === $value) { |
44
|
1 |
|
return null; |
45
|
|
|
} |
46
|
|
|
|
47
|
2 |
|
if (!in_array($value, $this->getPossibleValues(), true)) { |
48
|
2 |
|
throw new InvalidArgumentException("Invalid '" . $value . "' value to be stored in database for enum " . $this->getName()); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return (string) $value; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Return all possibles values as an array of string. |
56
|
|
|
* |
57
|
|
|
* @return string[] |
58
|
|
|
*/ |
59
|
|
|
abstract protected function getPossibleValues(): array; |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Returns the type name based on actual class name. |
63
|
|
|
*/ |
64
|
9 |
|
public function getName(): string |
65
|
|
|
{ |
66
|
9 |
|
$class = new ReflectionClass($this); |
67
|
9 |
|
$shortClassName = $class->getShortName(); |
68
|
9 |
|
$typeName = preg_replace('/Type$/', '', $shortClassName); |
69
|
|
|
|
70
|
9 |
|
if ($typeName === null) { |
71
|
|
|
throw new Exception('Could not extract enum name from class name'); |
72
|
|
|
} |
73
|
|
|
|
74
|
9 |
|
return $typeName; |
75
|
|
|
} |
76
|
|
|
|
77
|
2 |
|
public function getMappedDatabaseTypes(AbstractPlatform $platform): array |
78
|
|
|
{ |
79
|
2 |
|
return ['enum']; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|