Completed
Pull Request — master (#228)
by
unknown
01:16
created

Period::years()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Spatie\Analytics;
4
5
use DateTime;
6
use Carbon\Carbon;
7
use Spatie\Analytics\Exceptions\InvalidPeriod;
8
9
class Period
10
{
11
    /** @var \DateTime */
12
    public $startDate;
13
14
    /** @var \DateTime */
15
    public $endDate;
16
17
    public static function create(DateTime $startDate, $endDate): Period
18
    {
19
        return new static($startDate, $endDate);
20
    }
21
22
    public static function days(int $numberOfDays): Period
23
    {
24
        $endDate = Carbon::today();
25
26
        $startDate = Carbon::today()->subDays($numberOfDays)->startOfDay();
27
28
        return new static($startDate, $endDate);
29
    }
30
31
    public static function months(int $numberOfMonths): Period
32
    {
33
        $endDate = Carbon::today();
34
35
        $startDate = Carbon::today()->subMonths($numberOfMonths)->startOfMonth();
36
37
        return new static($startDate, $endDate);
38
    }
39
40
    public static function years(int $numberOfYears): Period
41
    {
42
        $endDate = Carbon::today();
43
44
        $startDate = Carbon::today()->subYears($numberOfYears)->startOfYear();
45
46
        return new static($startDate, $endDate);
47
    }
48
49
    public function __construct(DateTime $startDate, DateTime $endDate)
50
    {
51
        if ($startDate > $endDate) {
52
            throw InvalidPeriod::startDateCannotBeAfterEndDate($startDate, $endDate);
53
        }
54
55
        $this->startDate = $startDate;
56
57
        $this->endDate = $endDate;
58
    }
59
}
60