DatetimeConverter::convert()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 31
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 6
eloc 22
nc 6
nop 2
1
<?php
2
3
namespace Spiral\Statistics;
4
5
class DatetimeConverter
6
{
7
    /**
8
     * @param \DateTimeInterface $datetime
9
     * @param string|null        $interval
10
     * @return \DateTimeImmutable
11
     */
12
    public function convert(
13
        \DateTimeInterface $datetime,
14
        string $interval = null
15
    ): \DateTimeImmutable
16
    {
17
        $datetime = $this->immutable($datetime);
18
19
        switch ($interval) {
20
            case 'day':
21
                return $datetime->setTime(0, 0, 0);
22
23
            case 'week':
24
                $weekSub = $datetime->format('w') ? $datetime->format('w') - 1 : 6;
25
26
                return $datetime
27
                    ->sub(new \DateInterval('P' . $weekSub . 'D'))
28
                    ->setTime(0, 0, 0);
29
30
            case 'month':
31
                return $datetime
32
                    ->setDate($datetime->format('Y'), $datetime->format('m'), 1)
33
                    ->setTime(0, 0, 0);
34
35
            case 'year':
36
                return $datetime
37
                    ->setDate($datetime->format('Y'), 1, 1)
38
                    ->setTime(0, 0, 0);
39
        }
40
41
        return $datetime;
42
    }
43
44
    /**
45
     * @param \DateTimeInterface $datetime
46
     * @return \DateTimeImmutable
47
     */
48
    public function immutable(\DateTimeInterface $datetime): \DateTimeImmutable
49
    {
50
        if ($datetime instanceof \DateTime) {
51
            return \DateTimeImmutable::createFromMutable($datetime);
52
        }
53
54
        return $datetime;
55
    }
56
}