Passed
Pull Request — master (#23)
by Adrien
17:46 queued 04:32
created

EnumType::requiresSQLCommentHint()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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