DatetimeConverter   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 0
cbo 0
dl 0
loc 52
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B convert() 0 31 6
A immutable() 0 8 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
}