Passed
Push — master ( 68bc04...2d5d0a )
by Adrien
02:23
created

EnumType::getSqlDeclaration()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

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