DateIntervalType.php 1.97 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Types;

5
use DateInterval;
6
use Doctrine\DBAL\Platforms\AbstractPlatform;
7
use Throwable;
8

9
use function substr;
10

11
/**
12
 * Type that maps interval string to a PHP DateInterval Object.
13
 */
14
class DateIntervalType extends Type
15
{
16
    public const FORMAT = '%RP%YY%MM%DDT%HH%IM%SS';
17

18 19 20 21 22
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
23
        return Types::DATEINTERVAL;
24 25 26 27 28 29 30
    }

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
31
        $fieldDeclaration['length'] = 255;
32

33 34 35 36 37 38 39 40
        return $platform->getVarcharTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
41
        if ($value === null) {
42 43 44
            return null;
        }

45
        if ($value instanceof DateInterval) {
46
            return $value->format(self::FORMAT);
47 48
        }

49
        throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateInterval']);
50 51 52 53 54 55 56
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
57
        if ($value === null || $value instanceof DateInterval) {
58 59 60
            return $value;
        }

61 62 63 64 65 66 67
        $negative = false;

        if (isset($value[0]) && ($value[0] === '+' || $value[0] === '-')) {
            $negative = $value[0] === '-';
            $value    = substr($value, 1);
        }

68
        try {
69
            $interval = new DateInterval($value);
70

71
            if ($negative) {
72 73 74 75
                $interval->invert = 1;
            }

            return $interval;
76
        } catch (Throwable $exception) {
77
            throw ConversionException::conversionFailedFormat($value, $this->getName(), self::FORMAT, $exception);
78 79
        }
    }
80

81 82 83 84 85 86 87
    /**
     * {@inheritdoc}
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
88
}