Completed
Push — master ( 8b40f4...1a4202 )
by Peter
13:15
created

BaseType::convertToDatabaseValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
/**
3
 * Pkvs package
4
 *
5
 * @package Pkvs
6
 * @author  Peter Gribanov <[email protected]>
7
 */
8
9
namespace GpsLab\Component\Interval\Persistence\Doctrine\DBAL\Types;
10
11
use Doctrine\DBAL\Platforms\AbstractPlatform;
12
use Doctrine\DBAL\Types\ConversionException;
13
use Doctrine\DBAL\Types\TextType;
14
use GpsLab\Component\Interval\Exception\InvalidIntervalFormatException;
15
use GpsLab\Component\Interval\IntervalInterface;
16
17
abstract class BaseType extends TextType
18
{
19
    /**
20
     * @param IntervalInterface|null $value
21
     * @param AbstractPlatform $platform
22
     *
23
     * @return null|string
24
     */
25
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
26
    {
27
        $class = $this->getIntervalClass();
28
29
        return $value instanceof $class ? (string)$value : null;
30
    }
31
32
    /**
33
     * @throws ConversionException
34
     *
35
     * @param mixed $value
36
     * @param AbstractPlatform $platform
37
     *
38
     * @return null|IntervalInterface
39
     */
40
    public function convertToPHPValue($value, AbstractPlatform $platform)
41
    {
42
        if ($value === null) {
43
            return null;
44
        }
45
46
        try {
47
            return call_user_func([$this->getIntervalClass(), 'fromString'], $value);
48
        } catch (InvalidIntervalFormatException $e) {
49
            throw ConversionException::conversionFailed($value, $this->getName());
50
        }
51
    }
52
53
    /**
54
     * @return string
55
     */
56
    public function getName()
57
    {
58
        return basename($this->getIntervalClass());
59
    }
60
61
    /**
62
     * @return string
63
     */
64
    abstract protected function getIntervalClass();
65
}
66