Passed
Pull Request — master (#456)
by Alejandro
06:37 queued 01:57
created

ChronosDateTimeType   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 15
dl 0
loc 39
rs 10
c 0
b 0
f 0
ccs 16
cts 16
cp 1

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 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