DateImmutableType.php 1.52 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Types;

5
use DateTimeImmutable;
6 7 8 9 10 11 12 13 14 15 16 17
use Doctrine\DBAL\Platforms\AbstractPlatform;

/**
 * Immutable type of {@see DateType}.
 */
class DateImmutableType extends DateType
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
18
        return Types::DATE_IMMUTABLE;
19 20 21 22 23 24 25
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
26
        if ($value === null) {
27 28 29
            return $value;
        }

30
        if ($value instanceof DateTimeImmutable) {
31 32 33 34 35 36
            return $value->format($platform->getDateFormatString());
        }

        throw ConversionException::conversionFailedInvalidType(
            $value,
            $this->getName(),
37
            ['null', DateTimeImmutable::class]
38 39 40 41 42 43 44 45
        );
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
46
        if ($value === null || $value instanceof DateTimeImmutable) {
47 48 49
            return $value;
        }

50
        $dateTime = DateTimeImmutable::createFromFormat('!' . $platform->getDateFormatString(), $value);
51

52
        if ($dateTime === false) {
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
            throw ConversionException::conversionFailedFormat(
                $value,
                $this->getName(),
                $platform->getDateFormatString()
            );
        }

        return $dateTime;
    }

    /**
     * {@inheritdoc}
     */
    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}