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

9
use function date_create;
10

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

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

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

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

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

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

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

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

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

67
        return $val;
68
    }
69
}