CarbonDateTime::fromString()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 12
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 1
crap 12
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\CarbonExtension\In;
11
12
use Carbon\Carbon;
13
use Railt\CarbonExtension\Exception\InvalidDateTimeFormat;
14
15
/**
16
 * Class CarbonDateTime
17
 */
18
class CarbonDateTime
19
{
20
    /**
21
     * @param string $value
22
     * @return \DateTimeInterface
23
     * @throws InvalidDateTimeFormat
24
     */
25
    public function fromString(string $value): \DateTimeInterface
26
    {
27
        try {
28
            if ((string)(int)$value === $value) {
29
                return Carbon::createFromTimestamp((int)$value);
30
            }
31
32
            return Carbon::parse($value);
33
        } catch (\Throwable $e) {
34
            $error = 'Unknown or unsupported input CarbonDateTime format "%s"';
35
            throw new InvalidDateTimeFormat(\sprintf($error, $value));
36
        }
37
    }
38
39
    /**
40
     * @param mixed $value
41
     * @return \DateTimeInterface|null
42
     * @throws InvalidDateTimeFormat
43
     * @throws \InvalidArgumentException
44
     */
45
    public function verify($value): ?\DateTimeInterface
46
    {
47
        if ($value === null) {
48
            return null;
49
        }
50
51
        if ($value instanceof \DateTimeInterface) {
52
            return $value;
53
        }
54
55
        $error = 'Input CarbonDateTime scalar should be compatible with String or Int scalar type';
56
        throw new InvalidDateTimeFormat($error);
57
    }
58
}
59