ChronosDateTimeType::convertToPHPValue()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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