Completed
Push — master ( b3a86f...d34cec )
by Maxime
02:08
created

GenderEnumType::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
nc 1
cc 1
eloc 2
nop 0
1
<?php
2
3
/*
4
 * This file is part of the "elao/enum" package.
5
 *
6
 * Copyright (C) 2016 Elao
7
 *
8
 * @author Elao <[email protected]>
9
 */
10
11
namespace Elao\Enum\Bridge\Doctrine\DBAL\Types;
12
13
use Doctrine\DBAL\Platforms\AbstractPlatform;
14
use Doctrine\DBAL\Types\Type;
15
use Elao\Enum\EnumInterface;
16
17
abstract class AbstractEnumType extends Type
18
{
19
    /**
20
     * The enum FQCN for which we should make the DBAL conversion.
21
     *
22
     * @return string
23
     */
24
    abstract protected function getEnumClass(): string;
25
26
    /**
27
     * What should be returned on null value from the database.
28
     *
29
     * @return mixed
30
     */
31
    protected function onNullFromDatabase()
32
    {
33
        return null;
34
    }
35
36
    /**
37
     * What should be returned on null value from PHP.
38
     *
39
     * @return mixed
40
     */
41
    protected function onNullFromPhp()
42
    {
43
        return null;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     *
49
     * @param EnumInterface $value
50
     */
51
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
52
    {
53
        if (null === $value) {
54
            return $this->onNullFromPhp();
55
        }
56
57
        return $value->getValue();
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function convertToPHPValue($value, AbstractPlatform $platform)
64
    {
65
        if (null === $value) {
66
            return $this->onNullFromDatabase();
67
        }
68
69
        /** @var string|EnumInterface $class */
70
        $class = $this->getEnumClass();
71
72
        return $class::create($this->cast($value));
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
79
    {
80
        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function getDefaultLength(AbstractPlatform $platform)
87
    {
88
        return $platform->getVarcharDefaultLength();
89
    }
90
91
    /**
92
     * {@inheritdoc}
93
     */
94
    public function requiresSQLCommentHint(AbstractPlatform $platform)
95
    {
96
        return true;
97
    }
98
99
    /**
100
     * Cast the value from database to proper enumeration internal type.
101
     *
102
     * @param mixed $value
103
     *
104
     * @return mixed
105
     */
106
    protected function cast($value)
107
    {
108
        return (string) $value;
109
    }
110
}
111