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

XmlSchemaDateHandler::serializeDateInterval()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 6.9849

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 6
cts 14
cp 0.4286
rs 9.44
c 0
b 0
f 0
cc 4
nc 4
nop 4
crap 6.9849
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 17
                'format' => 'xml',
65
                'method' => 'serializeDateInterval',
66 17
            ),
67
        );
68 17
    }
69
70
    public function __construct($defaultTimezone = 'UTC')
71
    {
72
        $this->defaultTimezone = new \DateTimeZone($defaultTimezone);
73
74
    }
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 5
        if (isset($attributes['nil'][0]) && (string) $attributes['nil'][0] === 'true') {
79
            return null;
80
        }
81 5
82
        //Accept negative intervals like -PT1M23S.  Safe to assume that "-" doesn't exist elsewhere in a valid interval spec.
83 5
        $interval = str_replace('-', '', (string)$data, $count);
84
        $dateInterval = new \DateInterval($interval);
85
86 5
        //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 5
89 5
        return $dateInterval;
90
    }
91
92 5
    public function serializeDateInterval(XmlSerializationVisitor $visitor, \DateInterval $interval, array $type, Context $context)
93 1
    {
94
        $date = array_filter(array(
95
            'Y' => $interval->y,
96 4
            'M' => $interval->m,
97
            'D' => $interval->d
98
        ));
99 7
100
        // Reading all non-zero time parts.
101
        $time = array_filter(array(
102 7
            'H' => $interval->h,
103
            'M' => $interval->i,
104 7
            '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
    public function serializeDateIntercal(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
124
    {
125
126
        $v = $date->format('Y-m-d');
127
128
        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...
129
    }
130
131
    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...
132
    {
133
        $attributes = $data->attributes('xsi', true);
134
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
135
            return null;
136
        }
137
        if (!preg_match('/^(\d{4})-(\d{2})-(\d{2})(Z|([+-]\d{2}:\d{2}))?$/', $data)) {
138
            throw new RuntimeException(sprintf('Invalid date "%s", expected valid XML Schema date string.', $data));
139 4
        }
140
141 4
        return $this->parseDateTime($data, $type);
142 4
    }
143 4
144
    public function serializeDateTime(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
145
    {
146
147 4
        $v = $date->format(\DateTime::W3C);
148
149
        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...
150
    }
151
152 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...
153
    {
154
        $attributes = $data->attributes('xsi', true);
155
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
156
            return null;
157
        }
158
159
        return $this->parseDateTime($data, $type);
160
161
    }
162
163
    public function serializeTime(XmlSerializationVisitor $visitor, \DateTime $date, array $type, Context $context)
164
    {
165
        $v = $date->format('H:i:s');
166
        if ($date->getTimezone()->getOffset($date) !== $this->defaultTimezone->getOffset($date)) {
167
            $v .= $date->format('P');
168
        }
169
        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...
170
    }
171
172 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...
173
    {
174
        $attributes = $data->attributes('xsi', true);
175
        if (isset($attributes['nil'][0]) && (string)$attributes['nil'][0] === 'true') {
176
            return null;
177
        }
178
179
        $data = (string)$data;
180
181
        return new \DateTime($data, $this->defaultTimezone);
182
    }
183
184
    private function parseDateTime($data, array $type)
185
    {
186
        $timezone = isset($type['params'][1]) ? new \DateTimeZone($type['params'][1]) : $this->defaultTimezone;
187
        $datetime = new \DateTime((string)$data, $timezone);
188
        if (false === $datetime) {
189
            throw new RuntimeException(sprintf('Invalid datetime "%s", expected valid XML Schema dateTime string.', $data));
190
        }
191
192
        return $datetime;
193
    }
194
}
195
196