|
1
|
|
|
<?php |
|
2
|
|
|
namespace Acelaya\Doctrine\Type; |
|
3
|
|
|
|
|
4
|
|
|
use Acelaya\Doctrine\Exception\InvalidArgumentException; |
|
5
|
|
|
use Doctrine\DBAL\Platforms\AbstractPlatform; |
|
6
|
|
|
use Doctrine\DBAL\Types\Type; |
|
7
|
|
|
use MyCLabs\Enum\Enum; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractPhpEnumType extends Type |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var string |
|
13
|
|
|
*/ |
|
14
|
|
|
protected $name; |
|
15
|
|
|
/** |
|
16
|
|
|
* @var string |
|
17
|
|
|
*/ |
|
18
|
|
|
protected $enumClass = Enum::class; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Gets the name of this type. |
|
22
|
|
|
* |
|
23
|
|
|
* @return string |
|
24
|
|
|
*/ |
|
25
|
1 |
|
public function getName() |
|
26
|
|
|
{ |
|
27
|
1 |
|
return $this->name ?: $this->enumClass; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Gets the SQL declaration snippet for a field of this type. |
|
32
|
|
|
* |
|
33
|
|
|
* @param array $fieldDeclaration The field declaration. |
|
34
|
|
|
* @param AbstractPlatform $platform The currently used database platform. |
|
35
|
|
|
* |
|
36
|
|
|
* @return string |
|
37
|
|
|
*/ |
|
38
|
1 |
|
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) |
|
39
|
|
|
{ |
|
40
|
1 |
|
return $platform->getVarcharTypeDeclarationSQL([]); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* @param string $value |
|
45
|
|
|
* @param AbstractPlatform $platform |
|
46
|
|
|
* @return mixed |
|
47
|
|
|
* @throws InvalidArgumentException |
|
48
|
|
|
*/ |
|
49
|
3 |
|
public function convertToPHPValue($value, AbstractPlatform $platform) |
|
50
|
|
|
{ |
|
51
|
3 |
|
if ($value === null) { |
|
52
|
1 |
|
return null; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
2 |
|
$isValid = call_user_func([$this->enumClass, 'isValid'], $value); |
|
56
|
2 |
|
if (! $isValid) { |
|
57
|
1 |
|
throw new InvalidArgumentException(sprintf( |
|
58
|
1 |
|
'The value "%s" is not valid for the enum "%s". Expected one of ["%s"]', |
|
59
|
1 |
|
$value, |
|
60
|
1 |
|
$this->enumClass, |
|
61
|
1 |
|
implode('", "', call_user_func([$this->enumClass, 'toArray'])) |
|
62
|
1 |
|
)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
1 |
|
return new $this->enumClass($value); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
1 |
|
public function convertToDatabaseValue($value, AbstractPlatform $platform) |
|
69
|
|
|
{ |
|
70
|
1 |
|
return $value === null ? null : (string) $value; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|