DateIntervalType.php 1.96 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
use function substr;
9

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

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

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

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

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

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

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

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

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

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

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

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

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

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