DateTimeType   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 4
dl 0
loc 45
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A valueOf() 0 8 3
A __invoke() 0 12 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