Completed
Push — master ( 9a2ca3...ae9d99 )
by Alejandro
10s
created

ChronosDateTimeType::convertToDatabaseValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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