CarbonType::convertToPHPValue()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 2
nop 2
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Xgc\CarbonBundle\Doctrine\DBAL\Type;
5
6
use Carbon\Carbon;
7
use DateTime;
8
use Doctrine\DBAL\DBALException;
9
use Doctrine\DBAL\Platforms\AbstractPlatform;
10
use Doctrine\DBAL\Types\ConversionException;
11
use Doctrine\DBAL\Types\Type;
12
use InvalidArgumentException;
13
14
/**
15
 * Class CarbonType
16
 * @package Xgc\XgcCarbonBundle\Type
17
 */
18
class CarbonType extends Type
19
{
20
21
    /**
22
     * @return string
23
     */
24 2
    public function getName(): string
25
    {
26 2
        return 'carbon';
27
    }
28
29
    /**
30
     * @param array            $fieldDeclaration
31
     * @param AbstractPlatform $platform
32
     *
33
     * @return string
34
     *
35
     * @throws DBALException
36
     */
37 1
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform): string
38
    {
39 1
        return $platform->getDateTimeTypeDeclarationSQL($fieldDeclaration);
40
    }
41
42
    /**
43
     * @param null|Carbon|mixed $value
44
     * @param AbstractPlatform  $platform
45
     *
46
     * @return mixed|string
47
     *
48
     * @throws ConversionException
49
     */
50 3
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
51
    {
52 3
        if ($value === null) {
53 1
            return $value;
54
        }
55
56 2
        if ($value instanceof Carbon) {
57 1
            return $value->format($platform->getDateTimeFormatString());
58
        }
59
60 1
        throw ConversionException::conversionFailedInvalidType($value, $this->getName(), ['null', 'Carbon']);
61
    }
62
63
    /**
64
     * @param mixed|string     $value
65
     * @param AbstractPlatform $platform
66
     *
67
     * @return bool|DateTime|false|mixed
68
     *
69
     * @throws ConversionException
70
     */
71 3
    public function convertToPHPValue($value, AbstractPlatform $platform)
72
    {
73 3
        if ($value === null || $value instanceof Carbon) {
74 1
            return $value;
75
        }
76
77
        try {
78 2
            $carbon = Carbon::createFromFormat($platform->getDateTimeFormatString(), $value);
79 1
        } catch (InvalidArgumentException $e) {
80 1
            throw ConversionException::conversionFailedFormat(
81 1
                $value,
82 1
                $this->getName(),
83 1
                $platform->getDateTimeFormatString(),
84 1
                $e
85
            );
86
        }
87
88 1
        return $carbon;
89
    }
90
}
91