DatetimeComparison::getDatetimeFromFormat()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 4.0058

Importance

Changes 0
Metric Value
dl 0
loc 31
ccs 13
cts 14
cp 0.9286
rs 9.424
c 0
b 0
f 0
cc 4
nc 6
nop 1
crap 4.0058
1
<?php
2
3
namespace PhpAbac\Comparison;
4
5
class DatetimeComparison extends AbstractComparison
6
{
7 1
    public function isBetween(\DateTime $start, \DateTime $end, \DateTime $datetime): bool
8
    {
9 1
        return $start <= $datetime && $end >= $datetime;
10
    }
11
12 4
    public function isMoreRecentThan(string $format, \DateTime $datetime): bool
13
    {
14 4
        return $this->getDatetimeFromFormat($format) <= $datetime;
15
    }
16
17 1
    public function isLessRecentThan(string $format, \DateTime $datetime): bool
18
    {
19 1
        return $this->getDatetimeFromFormat($format) >= $datetime;
20
    }
21
22 5
    public function getDatetimeFromFormat(string $format): \DateTime
23
    {
24
        $formats = [
25 5
            'Y' => 31104000,
26
            'M' => 2592000,
27
            'D' => 86400,
28
            'H' => 3600,
29
            'm' => 60,
30
            's' => 1,
31
        ];
32 5
        $operator = $format{0};
33 5
        $format = substr($format, 1);
34 5
        $time = 0;
35
36 5
        foreach ($formats as $scale => $seconds) {
37 5
            $data = explode($scale, $format);
38
39 5
            if (strlen($format) === strlen($data[0])) {
40 5
                continue;
41
            }
42 5
            $time += $data[0] * $seconds;
43
            // Remaining format string
44 5
            $format = $data[1];
45
        }
46
47
        return
48 5
            ($operator === '+')
49
            ? (new \DateTime())->setTimestamp((time() + $time))
50 5
            : (new \DateTime())->setTimestamp((time() - $time))
51
        ;
52
    }
53
}
54