VersionDate::month()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\RfcLinc\Domain;
6
7
class VersionDate
8
{
9
    private $timestamp;
10
11
    /** @var string[] */
12
    private $ymd;
13
14 48
    public function __construct(int $year, int $month, int $day)
15
    {
16 48
        if (! $this->dateIsValid($year, $month, $day)) {
17 1
            throw new \InvalidArgumentException('The combination of year-month-day is not valid');
18
        }
19 47
        $this->ymd = [
20 47
            str_pad((string) $year, 4, '0', STR_PAD_LEFT),
21 47
            str_pad((string) $month, 2, '0', STR_PAD_LEFT),
22 47
            str_pad((string) $day, 2, '0', STR_PAD_LEFT),
23
        ];
24 47
        $this->timestamp = (int) strtotime($this->format() . 'T00:00:00+00:00');
25 47
    }
26
27
    /**
28
     * Create a VersionDate based only on the date part information given.
29
     * It will not consider any information about time or timezone.
30
     * You can use terms like 'today'.
31
     *
32
     * @param string $date
33
     * @return VersionDate
34
     */
35 19
    public static function createFromString(string $date): self
36
    {
37 19
        $dt = new \DateTime($date);
38 19
        return new self((int) $dt->format('Y'), (int) $dt->format('m'), (int) $dt->format('d'));
39
    }
40
41
    /**
42
     * Create a VersionDate based on the timestamp.
43
     * The timestamp is considered the seconds since 1970-01-01
44
     * Only the date part is taken, this function consider the timestamp as UTC
45
     *
46
     * @param int $timestamp
47
     * @return VersionDate
48
     */
49 11
    public static function createFromTimestamp(int $timestamp): self
50
    {
51 11
        return static::createFromString(gmdate('Y-m-d', $timestamp));
52
    }
53
54 48
    public static function dateIsValid(int $year, int $month, int $day)
55
    {
56 48
        return checkdate($month, $day, $year);
57
    }
58
59 47
    public function format(string $separator = '-'): string
60
    {
61 47
        return implode($separator, $this->ymd);
62
    }
63
64 23
    public function timestamp(): int
65
    {
66 23
        return $this->timestamp;
67
    }
68
69 3
    public function year(): int
70
    {
71 3
        return (int) $this->ymd[0];
72
    }
73
74 3
    public function month(): int
75
    {
76 3
        return (int) $this->ymd[1];
77
    }
78
79 3
    public function day(): int
80
    {
81 3
        return (int) $this->ymd[2];
82
    }
83
84 1
    public function compare(self $to): int
85
    {
86 1
        return $this->timestamp() <=> $to->timestamp();
87
    }
88
}
89