Passed
Pull Request — master (#16)
by Samuel
01:51
created

DtStartTransformer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 61
ccs 17
cts 17
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C transform() 0 31 8
1
<?php
2
3
namespace Recurrence\RruleTransformer;
4
5
/**
6
 * Class DtStartTransformer
7
 * @package Recurrence\RruleTransformer
8
 */
9
class DtStartTransformer extends AbstractRruleTransformer implements TransformerInterface
10
{
11
    const RRULE_PARAMETER = 'DTSTART';
12
13
    /**
14
     * @var array
15
     */
16
    private $datePatterns = [
17
        [
18
            'pattern'     => '[0-9]{8}T[0-9]{6}Z',
19
            'date_format' => 'Ymd\THisZ',
20
            'timezone'    => 'UTC',
21
        ],
22
        [
23
            'pattern'     => '[0-9]{8}T[0-9]{6}',
24
            'date_format' => 'Ymd\THis',
25
            'timezone'    => null,
26
        ],
27
        [
28
            'pattern'     => '[0-9]{8}',
29
            'date_format' => 'Ymd',
30
            'timezone'    => null,
31
        ],
32
    ];
33
34
    /**
35
     * @param string $rRule
36
     * @return \DateTime
37
     */
38
    public function transform($rRule)
39
    {
40 1
        $date = null;
41
42 1
        if (preg_match('/'.$this::RRULE_PARAMETER.';TZID=([a-zA-Z_-]+[\/[a-zA-Z_+\-0-9]+]?):([0-9]{8}T[0-9]{6})/', $rRule, $matches)) {
43
            try {
44 1
                $date = \DateTime::createFromFormat('Ymd\THis', $matches[2], new \DateTimeZone($matches[1]));
45
46 1
                return ($date) ? $date : null;
47 1
            } catch (\Exception $e) {
48 1
                throw new \InvalidArgumentException(sprintf('Invalid RRULE [%s] option : [%s] with timezone [%s]', $this::RRULE_PARAMETER, $matches[2], $matches[1]));
49
            }
50
        }
51
52
        // Process each supported date patterns and try to create \Datetime
53 1
        foreach ($this->datePatterns as $datePattern) {
54 1
            if (preg_match(sprintf('/%s=(%s)/', $this::RRULE_PARAMETER, $datePattern['pattern']), $rRule, $matches)) {
55 1
                $date = \DateTime::createFromFormat(
56 1
                    $datePattern['date_format'],
57 1
                    $matches[1],
58 1
                    (($datePattern['timezone']) ? new \DateTimeZone($datePattern['timezone']) : new \DateTimeZone(date_default_timezone_get()))
59 1
                );
60
61 1
                return ($date) ? $date : null;
62
            }
63 1
        }
64
65 1
        $this->throwExceptionOnInvalidParameter($rRule, $this::RRULE_PARAMETER);
66
67 1
        return null;
68
    }
69
}
70