Completed
Pull Request — master (#456)
by Alejandro
14:16
created

ChronosDateTimeType   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 15
dl 0
loc 39
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertToPHPValue() 0 8 2
A getName() 0 3 1
A convertToDatabaseValue() 0 14 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Common\Doctrine\Type;
5
6
use Cake\Chronos\Chronos;
7
use DateTimeInterface;
8
use Doctrine\DBAL\Platforms\AbstractPlatform;
9
use Doctrine\DBAL\Types\ConversionException;
10
use Doctrine\DBAL\Types\DateTimeImmutableType;
11
12
class ChronosDateTimeType extends DateTimeImmutableType
13
{
14
    public const CHRONOS_DATETIME = 'chronos_datetime';
15
16
    public function getName(): string
17
    {
18
        return self::CHRONOS_DATETIME;
19
    }
20
21
    /**
22
     * @throws ConversionException
23
     */
24
    public function convertToPHPValue($value, AbstractPlatform $platform): ?Chronos
25
    {
26
        if ($value === null) {
27
            return null;
28
        }
29
30
        $dateTime = parent::convertToPHPValue($value, $platform);
31
        return Chronos::instance($dateTime);
32
    }
33
34
    /**
35
     * @throws ConversionException
36
     */
37
    public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
38
    {
39
        if (null === $value) {
40
            return $value;
41
        }
42
43
        if ($value instanceof DateTimeInterface) {
44
            return $value->format($platform->getDateTimeFormatString());
45
        }
46
47
        throw ConversionException::conversionFailedInvalidType(
48
            $value,
49
            $this->getName(),
50
            ['null', DateTimeInterface::class]
51
        );
52
    }
53
}
54