Completed
Push — fm-support ( 0de470...22a3ee )
by Konstantinos
04:53
created

DatetimeWithTimezoneTransformer::createTimeDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2.003

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
ccs 10
cts 11
cp 0.9091
rs 9.4285
cc 2
eloc 12
nc 2
nop 2
crap 2.003
1
<?php
2
3
namespace BZIon\Form\Transformer;
4
5
use Symfony\Component\Form\DataTransformerInterface;
6
7
class DatetimeWithTimezoneTransformer implements DataTransformerInterface
8
{
9
    /**
10
     * Take a TimeDate object (with a timezone) and put its value on the time
11
     * and timezone fields, so the user can see it
12
     *
13
     * @param  \TimeDate $time
14
     * @return array
15
     */
16 1
    public function transform($time)
17
    {
18 1
        if ($time === null) {
19
            return null;
20
        }
21
22
        return array(
23 1
            'time'     => $this->createTimeDate($time),
24 1
            'timezone' => $time->timezone->getName()
25
        );
26
    }
27
28
    /**
29
     * Take the timestamp from the time field and the timezone that the user
30
     * provided and combine them into a single timezoned TimeDate
31
     *
32
     * @param  array     $data
33
     * @return \TimeDate
34
     */
35 1
    public function reverseTransform($data)
36
    {
37 1
        return $this->createTimeDate($data['time'], $data['timezone']);
38
    }
39
40
    /**
41
     * Create a TimeDate object from another one, ignoring its timezone
42
     *
43
     * @param  \TimeDate   $from     The original timestamp
44
     * @param  string|null $timezone The timezone to add to the object (defaults
45
     *                               to the PHP's default)
46
     * @return \TimeDate
47
     */
48 1
    private function createTimeDate($from, $timezone = null)
49
    {
50 1
        if ($from === null) {
51
            return null;
52
        }
53
54
        // Make sure it's a TimeDate instance
55 1
        $time = \TimeDate::from($from);
56
57 1
        return \TimeDate::create(
58 1
            $time->year,
59 1
            $time->month,
60 1
            $time->day,
61 1
            $time->hour,
62 1
            $time->minute,
63 1
            $time->second,
64
            $timezone
65
        );
66
    }
67
}
68