Completed
Pull Request — master (#12)
by
unknown
01:38
created

XmlSchemaDateHandler::deserializeDate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.0466

Importance

Changes 0
Metric Value
cc 4
nc 3
nop 3
dl 0
loc 12
ccs 6
cts 7
cp 0.8571
crap 4.0466
rs 9.8666
c 0
b 0
f 0
1
<?php
2
namespace GoetasWebservices\Xsd\XsdToPhpRuntime\Jms\Handler;
3
4
use JMS\Serializer\Context;
5
use JMS\Serializer\GraphNavigator;
6
use JMS\Serializer\Handler\SubscribingHandlerInterface;
7
use JMS\Serializer\XmlDeserializationVisitor;
8
use JMS\Serializer\XmlSerializationVisitor;
9
use RuntimeException;
10
11
class XmlSchemaDateHandler implements SubscribingHandlerInterface
12
{
13
14
    protected $defaultTimezone;
15
16
    public static function getSubscribingMethods()
17
    {
18
        return array(
19
            array(
20
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
21
                'format' => 'xml',
22
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\Date',
23
                'method' => 'deserializeDate'
24
            ),
25
            array(
26
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
27
                'format' => 'xml',
28
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\Date',
29
                'method' => 'serializeDate'
30
            ),
31
            array(
32
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
33
                'format' => 'xml',
34
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\DateTime',
35
                'method' => 'deserializeDateTime'
36
            ),
37
            array(
38
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
39
                'format' => 'xml',
40
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\DateTime',
41
                'method' => 'serializeDateTime'
42
            ),
43
            array(
44
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
45
                'format' => 'xml',
46
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\Time',
47
                'method' => 'deserializeTime'
48
            ),
49
            array(
50
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
51
                'format' => 'xml',
52
                'type' => 'GoetasWebservices\Xsd\XsdToPhp\XMLSchema\Time',
53
                'method' => 'serializeTime'
54
            ),
55
            array(
56
                'type' => 'DateInterval',
57
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
58
                'format' => 'xml',
59
                'method' => 'deserializeDateIntervalXml',
60
            ),
61
            array(
62
                'type' => 'DateInterval',
63
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
64
                'format' => 'xml',
65
                'method' => 'serializeDateInterval',
66
            ),
67
        );
68
    }
69
70 17
    public function __construct($defaultTimezone = 'UTC')
71
    {
72 17
        $this->defaultTimezone = new \DateTimeZone($defaultTimezone);
73
74 17
    }
75
76
    public function deserializeDateIntervalXml(XmlDeserializationVisitor $visitor, $data, array $type){
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
77
        $attributes = $data->attributes('xsi', true);
78
        if (isset($attributes['nil'][0]) && (string) $attributes['nil'][0] === 'true') {
79
            return null;
80
        }
81
82
        //Accept negative intervals like -PT1M23S.  Safe to assume that "-" doesn't exist elsewhere in a valid interval spec.
83
        $interval = str_replace('-', '', (string)$data, $count);
84
        $dateInterval = new \DateInterval($interval);
85
86
        //Invert if a negative sign was found
87
        $dateInterval->invert = !!$count;
0 ignored issues
show
Documentation Bug introduced by
The property $invert was declared of type integer, but !!$count is of type boolean. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
88
89
        return $dateInterval;
90
    }
91
92
    public function serializeDateInterval(XmlSerializationVisitor $visitor, \DateInterval $interval, array $type, Context $context)
93
    {
94
        $date = array_filter(array(
95
            'Y' => $interval->y,
96
            'M' => $interval->m,
97
            'D' => $interval->d
98
        ));
99
100
        // Reading all non-zero time parts.
101
        $time = array_filter(array(
102
            'H' => $interval->h,
103
            'M' => $interval->i,
104
            'S' => $interval->s
105
        ));
106
107
        $specString = 'P';
108
109
        // Adding each part to the spec-string.
110
        foreach ($date as $key => $value) {
111
            $specString .= $value . $key;
112
        }
113
        if (count($time) > 0) {
114
            $specString .= 'T';
115
            foreach ($time as $key => $value) {
116
                $specString .= $value . $key;
117
            }
118
        }
119
120
        return $visitor->visitSimpleString($specString, $type, $context);
0 ignored issues
show
Unused Code introduced by
The call to XmlSerializationVisitor::visitSimpleString() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
121
    }
122
123 5
    public function serializeDate(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
124
    {
125 5
        $v = $date->format('Y-m-d');
126
127 5
        return $visitor->visitSimpleString($v, $type, $context);
0 ignored issues
show
Unused Code introduced by
The call to XmlSerializationVisitor::visitSimpleString() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
128
    }
129
130 5
    public function deserializeDate(XmlDeserializationVisitor $visitor, $data, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
131
    {
132 5
        $attributes = $data->attributes('xsi', true);
133 5
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
134
            return null;
135
        }
136 5
        if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})(Z|([+-]\d{2}:\d{2}))?$/', $data)) {
137 1
            throw new RuntimeException(sprintf('Invalid date "%s", expected valid XML Schema date string.', $data));
138
        }
139
140 4
        return $this->parseDateTime($data, $type);
141
    }
142
143 7
    public function serializeDateTime(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
144
    {
145
146 7
        $v = $date->format(\DateTime::W3C);
147
148 7
        return $visitor->visitSimpleString($v, $type, $context);
0 ignored issues
show
Unused Code introduced by
The call to XmlSerializationVisitor::visitSimpleString() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
149
    }
150
151 View Code Duplication
    public function deserializeDateTime(XmlDeserializationVisitor $visitor, $data, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
152
    {
153
        $attributes = $data->attributes('xsi', true);
154
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
155
            return null;
156
        }
157
158
        return $this->parseDateTime($data, $type);
159
160
    }
161
162
    public function serializeTime(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
163
    {
164
        $v = $date->format('H:i:s');
165
        if ($date->getTimezone()->getOffset($date) !== $this->defaultTimezone->getOffset($date)) {
166
            $v .= $date->format('P');
167
        }
168
        return $visitor->visitSimpleString($v, $type, $context);
0 ignored issues
show
Unused Code introduced by
The call to XmlSerializationVisitor::visitSimpleString() has too many arguments starting with $context.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
169
    }
170
171 View Code Duplication
    public function deserializeTime(XmlDeserializationVisitor $visitor, $data, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
172
    {
173
        $attributes = $data->attributes('xsi', true);
174
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
175
            return null;
176
        }
177
178
        $data = (string)$data;
179
180
        return new \DateTime($data, $this->defaultTimezone);
181
    }
182
183 4
    private function parseDateTime($data, array $type)
184
    {
185 4
        $timezone = isset($type['params'][1]) ? new \DateTimeZone($type['params'][1]) : $this->defaultTimezone;
186 4
        $datetime = new \DateTime((string)$data, $timezone);
187 4
        if (false === $datetime) {
188
            throw new RuntimeException(sprintf('Invalid datetime "%s", expected valid XML Schema dateTime string.', $data));
189
        }
190
191 4
        return $datetime;
192
    }
193
}
194
195