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

ChronosDateTimeType::convertToPHPValue()   A

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