Passed
Pull Request — master (#456)
by Alejandro
08:02
created

ChronosDateTimeType::convertToDatabaseValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 14
rs 10
c 0
b 0
f 0
ccs 9
cts 9
cp 1
cc 3
nc 3
nop 2
crap 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 2
    public function getName(): string
17
    {
18 2
        return self::CHRONOS_DATETIME;
19
    }
20
21
    /**
22
     * @throws ConversionException
23
     */
24 3
    public function convertToPHPValue($value, AbstractPlatform $platform): ?Chronos
25
    {
26 3
        if ($value === null) {
27 1
            return null;
28
        }
29
30 2
        $dateTime = parent::convertToPHPValue($value, $platform);
31 2
        return Chronos::instance($dateTime);
32
    }
33
34
    /**
35
     * @throws ConversionException
36
     */
37 5
    public function convertToDatabaseValue($value, AbstractPlatform $platform): ?string
38
    {
39 5
        if (null === $value) {
40 1
            return $value;
41
        }
42
43 4
        if ($value instanceof DateTimeInterface) {
44 3
            return $value->format($platform->getDateTimeFormatString());
45
        }
46
47 1
        throw ConversionException::conversionFailedInvalidType(
48 1
            $value,
49 1
            $this->getName(),
50 1
            ['null', DateTimeInterface::class]
51
        );
52
    }
53
}
54