DateTimeTzType.php 2.38 KB
Newer Older
1 2
<?php

Michael Moravec's avatar
Michael Moravec committed
3 4
declare(strict_types=1);

5 6
namespace Doctrine\DBAL\Types;

7 8
use DateTime;
use DateTimeInterface;
9
use Doctrine\DBAL\Platforms\AbstractPlatform;
10 11
use Doctrine\DBAL\Types\Exception\InvalidFormat;
use Doctrine\DBAL\Types\Exception\InvalidType;
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

/**
 * DateTime type saving additional timezone information.
 *
 * Caution: Databases are not necessarily experts at storing timezone related
 * data of dates. First, of all the supported vendors only PostgreSQL and Oracle
 * support storing Timezone data. But those two don't save the actual timezone
 * attached to a DateTime instance (for example "Europe/Berlin" or "America/Montreal")
 * but the current offset of them related to UTC. That means depending on daylight saving times
 * or not you may get different offsets.
 *
 * This datatype makes only sense to use, if your application works with an offset, not
 * with an actual timezone that uses transitions. Otherwise your DateTime instance
 * attached with a timezone such as Europe/Berlin gets saved into the database with
 * the offset and re-created from persistence with only the offset, not the original timezone
 * attached.
 */
29
class DateTimeTzType extends Type implements PhpDateTimeMappingType
30
{
31
    public function getName() : string
32
    {
33
        return Types::DATETIMETZ_MUTABLE;
34
    }
35

Benjamin Morel's avatar
Benjamin Morel committed
36 37 38
    /**
     * {@inheritdoc}
     */
39
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform) : string
40 41 42 43
    {
        return $platform->getDateTimeTzTypeDeclarationSQL($fieldDeclaration);
    }

Benjamin Morel's avatar
Benjamin Morel committed
44 45 46
    /**
     * {@inheritdoc}
     */
47 48
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
49
        if ($value === null) {
50 51 52
            return $value;
        }

53
        if ($value instanceof DateTimeInterface) {
54
            return $value->format($platform->getDateTimeTzFormatString());
55
        }
56

57
        throw InvalidType::new($value, $this->getName(), ['null', 'DateTime']);
58 59
    }

Benjamin Morel's avatar
Benjamin Morel committed
60 61 62
    /**
     * {@inheritdoc}
     */
63 64
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
65
        if ($value === null || $value instanceof DateTimeInterface) {
66
            return $value;
67 68
        }

69
        $val = DateTime::createFromFormat($platform->getDateTimeTzFormatString(), $value);
70
        if ($val === false) {
71
            throw InvalidFormat::new($value, $this->getName(), $platform->getDateTimeTzFormatString());
72
        }
Benjamin Morel's avatar
Benjamin Morel committed
73

74
        return $val;
75
    }
76
}