Completed
Pull Request — master (#16)
by Samuel
04:38
created

DtStartTransformer::createDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 2
cts 2
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 3
crap 2
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
        if (preg_match('/'.$this::RRULE_PARAMETER.';TZID=([a-zA-Z_-]+[\/[a-zA-Z_+\-0-9]+]?):([0-9]{8}T[0-9]{6})/', $rRule, $matches)) {
41
            try {
42 1
                return $this->createDate('Ymd\THis', $matches[2], new \DateTimeZone($matches[1]));
43 1
            } catch (\Exception $e) {
44 1
                throw new \InvalidArgumentException(sprintf('Invalid RRULE [%s] option : [%s] with timezone [%s]', $this::RRULE_PARAMETER, $matches[2], $matches[1]));
45
            }
46
        }
47
48
        // Process each supported date patterns and try to create \Datetime
49 1
        foreach ($this->datePatterns as $datePattern) {
50 1
            if (preg_match(sprintf('/%s=(%s)/', $this::RRULE_PARAMETER, $datePattern['pattern']), $rRule, $matches)) {
51 1
                return $this->createDate(
52 1
                    $datePattern['date_format'],
53 1
                    $matches[1],
54 1
                    (($datePattern['timezone']) ? new \DateTimeZone($datePattern['timezone']) : new \DateTimeZone(date_default_timezone_get()))
55 1
                );
56
            }
57 1
        }
58
59 1
        $this->throwExceptionOnInvalidParameter($rRule, $this::RRULE_PARAMETER);
60
61 1
        return null;
62
    }
63
64
    /**
65
     * @param string        $format
66
     * @param string        $time
67
     * @param \DateTimeZone $timezone
68
     * @return \DateTime|null
69
     */
70
    private function createDate($format, $time, \DateTimeZone $timezone)
71
    {
72 1
        $date = \DateTime::createFromFormat($format, $time, $timezone);
73
74 1
        return ($date) ? $date : null;
75
    }
76
}
77