Failed Conditions
Push — travis-db2 ( e87e37...2c4097 )
by Michael
03:43
created

DateIntervalType::getName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
1
<?php
2
3
namespace Doctrine\DBAL\Types;
4
5
use Doctrine\DBAL\Platforms\AbstractPlatform;
6
use function substr;
7
8
/**
9
 * Type that maps interval string to a PHP DateInterval Object.
10
 */
11
class DateIntervalType extends Type
12
{
13
    public const FORMAT = '%RP%YY%MM%DDT%HH%IM%SS';
14
15
    /**
16
     * {@inheritdoc}
17
     */
18
    public function getName()
19
    {
20
        return Type::DATEINTERVAL;
21
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
27
    {
28
        $fieldDeclaration['length'] = 255;
29
        $fieldDeclaration['fixed']  = true;
30
31
        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
38
    {
39
        if (null === $value) {
40
            return null;
41
        }
42
43
        if ($value instanceof \DateInterval) {
44
            return $value->format(self::FORMAT);
45
        }
46
47
        throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateInterval']);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function convertToPHPValue($value, AbstractPlatform $platform)
54
    {
55
        if ($value === null || $value instanceof \DateInterval) {
56
            return $value;
57
        }
58
59
        $negative = false;
60
61
        if (isset($value[0]) && ($value[0] === '+' || $value[0] === '-')) {
62
            $negative = $value[0] === '-';
63
            $value    = substr($value, 1);
64
        }
65
66
        try {
67
            $interval = new \DateInterval($value);
68
69
            if ($negative) {
70
                $interval->invert = 1;
71
            }
72
73
            return $interval;
74
        } catch (\Exception $exception) {
75
            throw ConversionException::conversionFailedFormat($value, $this->getName(), self::FORMAT, $exception);
76
        }
77
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function requiresSQLCommentHint(AbstractPlatform $platform)
83
    {
84
        return true;
85
    }
86
}
87