Passed
Branch main (b6a268)
by Iain
04:11
created

UtcDateTimeTzType   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 54
rs 10
wmc 11

5 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToDatabaseValue() 0 7 2
A getUtc() 0 3 2
A convertToPHPValue() 0 17 4
A getTimezone() 0 7 2
A setTimeZone() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright Humbly Arrogant Ltd 2020-2022.
7
 *
8
 * Use of this software is governed by the Business Source License included in the LICENSE file and at https://getparthenon.com/docs/next/license.
9
 *
10
 * Change Date: TBD ( 3 years after 2.0.0 release )
11
 *
12
 * On the date above, in accordance with the Business Source License, use of this software will be governed by the open source license specified in the LICENSE file.
13
 */
14
15
namespace Parthenon\User\Dbal\Types;
16
17
use Doctrine\DBAL\Platforms\AbstractPlatform;
18
use Doctrine\DBAL\Types\ConversionException;
19
use Doctrine\DBAL\Types\DateTimeType;
20
21
/**
22
 * Copied from https://www.doctrine-project.org/projects/doctrine-orm/en/2.12/cookbook/working-with-datetime.html.
23
 */
24
class UtcDateTimeTzType extends DateTimeType
25
{
26
    private static $userTimezone;
27
28
    /**
29
     * @var \DateTimeZone
30
     */
31
    private static $utc;
32
33
    public static function setTimeZone(string $timezone)
34
    {
35
        self::$userTimezone = new \DateTimeZone($timezone);
36
    }
37
38
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
39
    {
40
        if ($value instanceof \DateTime) {
41
            $value->setTimezone(self::getUtc());
42
        }
43
44
        return parent::convertToDatabaseValue($value, $platform);
45
    }
46
47
    public function convertToPHPValue($value, AbstractPlatform $platform)
48
    {
49
        if (null === $value || $value instanceof \DateTime) {
50
            return $value;
51
        }
52
53
        $converted = \DateTime::createFromFormat(
54
            $platform->getDateTimeTzFormatString(),
55
            $value,
56
            self::getUtc(),
57
        );
58
        if (!$converted) {
0 ignored issues
show
introduced by
$converted is of type DateTime, thus it always evaluated to true.
Loading history...
59
            throw ConversionException::conversionFailedFormat($value, $this->getName(), $platform->getDateTimeTzFormatString());
60
        }
61
        $converted->setTimezone(self::getTimezone());
62
63
        return $converted;
64
    }
65
66
    private static function getTimezone(): \DateTimeZone
67
    {
68
        if (!isset(self::$userTimezone)) {
69
            return self::getUtc();
70
        }
71
72
        return self::$userTimezone;
73
    }
74
75
    private static function getUtc(): \DateTimeZone
76
    {
77
        return self::$utc ?: self::$utc = new \DateTimeZone('UTC');
78
    }
79
}
80