Completed
Pull Request — master (#18)
by Samuel
03:55
created

RecurrenceProvider::create()   B

Complexity

Conditions 4
Paths 6

Size

Total Lines 29
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 14
nc 6
nop 1
1
<?php
2
3
namespace Recurrence\Rrule;
4
5
use Recurrence\Model\Exception\InvalidRecurrenceException;
6
use Recurrence\Model\Exception\InvalidRruleExpressionException;
7
use Recurrence\Model\Recurrence;
8
use Recurrence\Model\Exception\InvalidRruleException;
9
use Recurrence\Validator\RecurrenceValidator;
10
11
/**
12
 * Class RecurrenceProvider
13
 * @package Recurrence\Rrule
14
 */
15
class RecurrenceProvider
16
{
17
18
    /**
19
     * Map extractor/transformer names with Recurrence attributes
20
     * @var array
21
     */
22
    private $options = [
23
        'Count'            => 'count',
24
        'Interval'         => 'interval',
25
        'Freq'             => 'frequency',
26
        'DtStartTimezoned' => 'periodStartAt',
27
        'DtStart'          => 'periodStartAt',
28
        'UntilTimezoned'   => 'periodEndAt',
29
        'Until'            => 'periodEndAt',
30
    ];
31
32
    /**
33
     * @param string $rRule
34
     * @return Recurrence
35
     * @throws InvalidRruleException
36
     */
37
    public function create($rRule)
38
    {
39
        $recurrence = new Recurrence();
40
41
        // Process all options supported
42
        foreach ($this->options as $option => $attribute) {
43
            // Create extractor
44
            $className = 'Recurrence\Rrule\Extractor\\'.$option.'Extractor';
45
            $extractor = new $className();
46
47
            if ($values = $extractor->extract($rRule)) {
48
49
                // Create corresponding transformer
50
                $className = 'Recurrence\Rrule\Transformer\\'.$option.'Transformer';
51
                $transformer = new $className();
52
53
                // Set Recurrence attribute
54
                $recurrence = $this->setAttribute($recurrence, $attribute, $transformer->transform($values));
55
            }
56
        }
57
58
        try {
59
            RecurrenceValidator::validate($recurrence);
60
        } catch (InvalidRecurrenceException $e)  {
61
            throw new InvalidRruleExpressionException($e->getMessage());
62
        }
63
64
        return $recurrence;
65
    }
66
67
    /**
68
     * @param Recurrence $recurrence
69
     * @param string     $attribute
70
     * @param mixed      $value
71
     * @return Recurrence
72
     */
73
    private function setAttribute(Recurrence $recurrence, $attribute, $value)
74
    {
75
        $method = sprintf('set%s', ucfirst($attribute));
76
77
        if ($value && method_exists($recurrence, $method)) {
78
            $recurrence->$method($value);
79
        }
80
81
        return $recurrence;
82
    }
83
}
84