Passed
Push — master ( ed2711...5bfb66 )
by Samuel
02:22
created

DatetimeProvider   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 21
c 1
b 0
f 0
dl 0
loc 56
ccs 20
cts 20
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B provide() 0 31 7
A applyConstraints() 0 12 3
1
<?php
2
3
namespace Recurrence;
4
5
use Recurrence\Constraint\DatetimeConstraint\DatetimeConstraintInterface;
6
use Recurrence\Model\Recurrence;
7
use Recurrence\Provider\DatetimeProviderFactory;
8
use Recurrence\Validator\RecurrenceValidator;
9
10
/**
11
 * Class DatetimeProvider
12
 * @package Recurrence
13
 */
14
class DatetimeProvider
15
{
16
    /**
17
     * @param Recurrence $recurrence
18
     * @return array<\DateTime>
19
     */
20
    public function provide(Recurrence $recurrence)
21
    {
22 1
        RecurrenceValidator::validate($recurrence);
23
24 1
        $provider = DatetimeProviderFactory::create($recurrence);
25
26 1
        $datetimes = $provider->provide($recurrence);
27
28 1
        if (!$recurrence->hasDatetimeConstraint()) {
29 1
            return $datetimes;
30
        }
31
32 1
        $filteredDatetimes = [];
33
34 1
        $previousDatetime = null;
35 1
        foreach ($datetimes as $key => $datetime) {
36 1
            $filteredDatetime = $this->applyConstraints($recurrence, $datetime);
37
38
            // Check that datetime do not pass recurrence end period
39 1
            if ($recurrence->hasPeriodEndAt() && $datetime > $recurrence->getPeriodEndAt()) {
40 1
                break;
41
            }
42
43
            // Avoid duplicate datetime due to constraint updates
44 1
            if (empty($filteredDatetimes) || $previousDatetime != $filteredDatetime) {
45 1
                $filteredDatetimes[] = $filteredDatetime;
46 1
                $previousDatetime    = $filteredDatetime;
47
            }
48
        }
49
50 1
        return $filteredDatetimes;
51
    }
52
53
    /**
54
     * @param Recurrence $recurrence
55
     * @param \Datetime  $datetime
56
     * @return \Datetime
57
     */
58
    private function applyConstraints($recurrence, $datetime)
59
    {
60 1
        $filteredDatetime = $datetime;
61
62
        // Apply each constraint on current datetime
63 1
        foreach ($recurrence->getConstraints() as $constraint) {
64 1
            if ($constraint instanceof DatetimeConstraintInterface) {
65 1
                $filteredDatetime = $constraint->apply($recurrence, $datetime);
66
            }
67
        }
68
69 1
        return $filteredDatetime;
70
    }
71
}
72