-
Notifications
You must be signed in to change notification settings - Fork 1
/
Period.php
51 lines (41 loc) · 855 Bytes
/
Period.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
namespace App\Models;
class Period
{
protected $month;
protected $year;
public static function fromString($period): self
{
$period = explode('-', $period);
return new self($period[0], $period[1]);
}
public static function fromDateTime(\DateTimeInterface $date): self
{
return new self($date->format('Y'), $date->format('n'));
}
public function __construct(int $year, int $month)
{
if (1 > $month || $month > 12)
{
throw new \OutOfRangeException('A month is between 1 and 12');
}
$this->year = $year;
$this->month = $month;
}
public function getMonth(): int
{
return $this->month;
}
public function getYear(): int
{
return $this->year;
}
public function format(): string
{
return sprintf('%04d-%02d', $this->year, $this->month);
}
public function __toString()
{
return $this->format();
}
}