Completed
Pull Request — master (#18)
by Samuel
02:01
created

ExcludeDaysOfWeekConstraint::apply()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
crap 2
1
<?php
2
3
namespace Recurrence\Constraint;
4
5
use Recurrence\Model\Recurrence;
6
7
/**
8
 * Class ExcludeDaysOfWeekConstraint
9
 * @package Recurrence\Constraint
10
 */
11
class ExcludeDaysOfWeekConstraint implements RecurrenceConstraintInterface
12
{
13
14
    /**
15
     * @var array
16
     */
17
    private $excludedDays = [];
18
19
    /**
20
     * @param array $excludedDays
21
     */
22
    public function __construct(array $excludedDays = [])
23
    {
24 1
        $excludedDays = array_unique($excludedDays);
25
26 1
        sort($excludedDays);
27
28 1
        if (count($excludedDays) >= 7) {
29 1
            throw new \InvalidArgumentException('At least one day of the week must be allowed');
30
        }
31
32 1
        foreach ($excludedDays as $excludedDay) {
33 1
            $excludedDay = filter_var($excludedDay, FILTER_VALIDATE_INT);
34
35 1
            if (!$excludedDay || $excludedDay < 1 || $excludedDay > 7) {
36 1
                throw new \InvalidArgumentException('Exclude day must be an integer between 1 and 7');
37
            }
38
39 1
            $this->excludedDays[] = $excludedDay;
40
        }
41 1
    }
42
43
    /**
44
     * @param Recurrence $recurrence
45
     * @param \Datetime $datetime
46
     * @return \Datetime
47
     */
48
    public function apply(Recurrence $recurrence, \Datetime $datetime)
49
    {
50 1
        while (in_array((int) $datetime->format('N'), $this->excludedDays)) {
51 1
            $datetime->modify('+1 day');
52
        }
53
54 1
        return $datetime;
55
    }
56
}
57