Completed
Push — utc-datetime-storing ( 42f778 )
by Kamil
29:36
created

UTCDateTimeType::convertToDatabaseValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Sylius\Bundle\ResourceBundle\Doctrine\DBAL\Type;
6
7
use Doctrine\DBAL\Platforms\AbstractPlatform;
8
use Doctrine\DBAL\Types\ConversionException;
9
use Doctrine\DBAL\Types\DateTimeType;
10
11
final class UTCDateTimeType extends DateTimeType
12
{
13
    /**
14
     * @var \DateTimeZone
15
     */
16
    private static $utc;
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
22
    {
23
        if ($value instanceof \DateTimeInterface) {
24
            $value = $value->setTimezone($this->getUTC());
25
        }
26
27
        return parent::convertToDatabaseValue($value, $platform);
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function convertToPHPValue($value, AbstractPlatform $platform): ?\DateTimeInterface
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
34
    {
35
        if (null === $value || $value instanceof \DateTimeInterface) {
36
            return $value;
37
        }
38
39
        $converted = \DateTime::createFromFormat($platform->getDateTimeFormatString(), $value, $this->getUTC());
40
41
        if (!$converted) {
42
            throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeFormatString());
43
        }
44
45
        return $converted;
46
    }
47
48
    private function getUTC(): \DateTimeZone
49
    {
50
        if (!self::$utc) {
51
            self::$utc = new \DateTimeZone('UTC');
52
        }
53
54
        return self::$utc;
55
    }
56
}
57