Test Failed
Pull Request — master (#16)
by Samuel
05:20
created

DtStartTransformer::transform()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
ccs 3
cts 3
cp 1
rs 6.7272
cc 7
eloc 16
nc 13
nop 1
crap 7
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 1
            'date_format' => 'Ymd\THisZ',
20
            'timezone'    => 'UTC',
21 1
        ],
22 1
        [
23 1
            'pattern'     => '[0-9]{8}T[0-9]{6}',
24
            'date_format' => 'Ymd\THis',
25
            'timezone'    => null,
26
        ],
27 1
        [
28 1
            'pattern'     => '[0-9]{8}',
29
            'date_format' => 'Ymd',
30
            'timezone'    => null,
31 1
        ],
32 1
    ];
33
34
    /**
35 1
     * @param string $rRule
36 1
     * @return \DateTime
37
     */
38
    public function transform($rRule)
39
    {
40 1
        $date = null;
41 1
42
        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
            } catch (\Exception $e) {
46
                throw new \InvalidArgumentException(sprintf('Invalid RRULE [%s] option : [%s] with timezone [%s]', $this::RRULE_PARAMETER, $matches[2], $matches[1]));
47
            }
48
        }
49
50
        // Process each supported date patterns and try to create \Datetime
51
        foreach ($this->datePatterns as $datePattern) {
52
            if (preg_match(sprintf('/%s=(%s)/', $this::RRULE_PARAMETER, $datePattern['pattern']), $rRule, $matches)) {
53
                $date = \DateTime::createFromFormat(
54
                    $datePattern['date_format'],
55
                    $matches[1],
56
                    (($datePattern['timezone']) ? new \DateTimeZone($datePattern['timezone']) : new \DateTimeZone(date_default_timezone_get()))
57
                );
58
59
                break;
60
            }
61
        }
62
63
        $this->throwExceptionOnInvalidParameter($rRule, $this::RRULE_PARAMETER);
64
65
        return ($date) ? $date : null;
66
    }
67
}
68