DateTimeType::valueOf()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 4
nc 2
nop 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tdn\PhpTypes\Type;
6
7
use Tdn\PhpTypes\Exception\InvalidTransformationException;
8
use Tdn\PhpTypes\Exception\InvalidTypeCastException;
9
use Tdn\PhpTypes\Type\Traits\Boxable;
10
use Carbon\Carbon;
11
12
/**
13
 * Class DateTime.
14
 *
15
 * A DateTime is a TypeInterface implementation that wraps around a regular string value meant to represent a date.
16
 * This object extends Carbon, which extends PHP's own \DateTime.
17
 *
18
 * {@inheritdoc}
19
 */
20
class DateTimeType extends Carbon implements TypeInterface
21
{
22
    use Boxable;
23
24
    /**
25
     * @param string|null               $time
26
     * @param \DateTimezone|string|null $tz
27
     */
28 20
    public function __construct(string $time = null, $tz = null)
29
    {
30 20
        parent::__construct($time, $tz);
31 20
    }
32
33
    /**
34
     * {@inheritdoc}
35
     *
36
     * @return DateTimeType
37
     */
38 7
    public static function valueOf($mixed): DateTimeType
39
    {
40 7
        if ($mixed instanceof StringType || 'string' === $type = strtolower(gettype($mixed))) {
41 2
            return new static((string) $mixed);
42
        }
43
44 5
        throw new InvalidTransformationException($type, static::class);
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @return string|DateTimeType
51
     */
52 6
    public function __invoke(int $toType = null)
53
    {
54 6
        if ($toType === Type::STRING) {
55 1
            return $this->format('Y-m-d H:i:s');
56
        }
57
58 6
        if ($toType === null) {
59 2
            return $this;
60
        }
61
62 4
        throw new InvalidTypeCastException(static::class, $this->getTranslatedType($toType));
63
    }
64
}
65