Failed Conditions
Pull Request — master (#2763)
by Alexandre
04:52
created

DateIntervalType::convertToPHPValue()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

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