Passed
Branch factorize (ea9e2e)
by Samuel
05:13
created

DatetimeProvider::provide()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 33
ccs 16
cts 16
cp 1
rs 8.5806
cc 4
eloc 17
nc 8
nop 1
crap 4
1
<?php
2
3
namespace Recurrence;
4
5
use Recurrence\Model\Recurrence;
6
use Recurrence\Validator\RecurrenceValidator;
7
8
/**
9
 * Class DatetimeProvider
10
 * @package Recurrence
11
 */
12
class DatetimeProvider
13
{
14
    /**
15
     * @param Recurrence $recurrence
16
     * @return array<\DateTime>
17
     */
18
    public function provide(Recurrence $recurrence)
19
    {
20 1
        RecurrenceValidator::validate($recurrence);
21
22 1
        $interval = $recurrence->getFrequency()->convertToDateIntervalFormat();
23
24
        // Transform interval in Datetime interval expression
25 1
        if ($recurrence->getInterval() !== 1) {
26 1
            $interval = str_replace('1', $recurrence->getInterval(), $interval);
27
        }
28
29 1
        $dateInterval = new \DateInterval($interval);
30
31
        // Estimate end date in case of count option
32 1
        $periodEndAt = $recurrence->getPeriodEndAt();
33 1
        if ($recurrence->hasCount()) {
34 1
            $periodEndAt = clone $recurrence->getPeriodStartAt();
35 1
            $periodEndAt->modify(str_replace('1', ($recurrence->getCount()*$recurrence->getInterval()), $recurrence->getFrequency()->convertToDateTimeFormat()));
36
        }
37
38 1
        $recurrences = iterator_to_array(new \DatePeriod(
39 1
            $recurrence->getPeriodStartAt(),
40 1
            $dateInterval,
41 1
            $periodEndAt
42
        ));
43
44
        // When having count option, return only amount of recurrences requested
45 1
        if ($recurrence->hasCount()) {
46 1
            return array_slice($recurrences, 0, $recurrence->getCount());
47
        }
48
49 1
        return $recurrences;
50
    }
51
}
52