DateTimeType.php 1.63 KB
Newer Older
1 2
<?php

3 4
namespace Doctrine\DBAL\Types;

5 6
use DateTime;
use DateTimeInterface;
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
use function date_create;
9

10
/**
11
 * Type that maps an SQL DATETIME/TIMESTAMP to a PHP DateTime object.
12
 */
13
class DateTimeType extends Type implements PhpDateTimeMappingType
14
{
Benjamin Morel's avatar
Benjamin Morel committed
15 16 17
    /**
     * {@inheritdoc}
     */
18 19
    public function getName()
    {
20
        return Types::DATETIME_MUTABLE;
21 22
    }

Benjamin Morel's avatar
Benjamin Morel committed
23 24 25
    /**
     * {@inheritdoc}
     */
26
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
27
    {
28
        return $platform->getDateTimeTypeDeclarationSQL($fieldDeclaration);
29 30
    }

Benjamin Morel's avatar
Benjamin Morel committed
31 32 33
    /**
     * {@inheritdoc}
     */
34
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
35
    {
36
        if ($value === null) {
37 38 39
            return $value;
        }

40
        if ($value instanceof DateTimeInterface) {
41
            return $value->format($platform->getDateTimeFormatString());
42 43
        }

44
        throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'DateTime']);
45
    }
46

Benjamin Morel's avatar
Benjamin Morel committed
47 48 49
    /**
     * {@inheritdoc}
     */
50
    public function convertToPHPValue($value, AbstractPlatform $platform)
51
    {
52
        if ($value === null || $value instanceof DateTimeInterface) {
53
            return $value;
54 55
        }

56
        $val = DateTime::createFromFormat($platform->getDateTimeFormatString(), $value);
57

58
        if ($val === false) {
59 60 61
            $val = date_create($value);
        }

62
        if ($val === false) {
63
            throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString());
64
        }
Benjamin Morel's avatar
Benjamin Morel committed
65

66
        return $val;
67
    }
68
}