VarDateTimeImmutableType.php 1.43 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Types;

5
use DateTimeImmutable;
6
use Doctrine\DBAL\Platforms\AbstractPlatform;
7

8
use function date_create_immutable;
9 10 11 12 13 14 15 16 17 18 19

/**
 * Immutable type of {@see VarDateTimeType}.
 */
class VarDateTimeImmutableType extends VarDateTimeType
{
    /**
     * {@inheritdoc}
     */
    public function getName()
    {
20
        return Types::DATETIME_IMMUTABLE;
21 22 23 24 25 26 27
    }

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

32
        if ($value instanceof DateTimeImmutable) {
33 34 35 36 37 38
            return $value->format($platform->getDateTimeFormatString());
        }

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

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

        $dateTime = date_create_immutable($value);

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

        return $dateTime;
    }

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