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

ChronosDateTimeType::convertToDatabaseValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 14
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 2
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