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

ExcludeDaysOfWeekConstraint   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 46
c 0
b 0
f 0
wmc 8
lcom 1
cbo 0
ccs 13
cts 13
cp 1
rs 10

2 Methods

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