Completed
Pull Request — master (#944)
by Asmir
02:43
created

XmlDriver::loadMetadataFromFile()   F

Complexity

Conditions 89
Paths > 20000

Size

Total Lines 329
Code Lines 186

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 139
CRAP Score 193.5132

Importance

Changes 0
Metric Value
cc 89
eloc 186
nc 158226
nop 2
dl 0
loc 329
ccs 139
cts 182
cp 0.7637
crap 193.5132
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * Copyright 2016 Johannes M. Schmitt <[email protected]>
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
21
namespace JMS\Serializer\Metadata\Driver;
22
23
use JMS\Serializer\Annotation\ExclusionPolicy;
24
use JMS\Serializer\Exception\RuntimeException;
25
use JMS\Serializer\Exception\XmlErrorException;
26
use JMS\Serializer\Metadata\ClassMetadata;
27
use JMS\Serializer\Metadata\ExpressionPropertyMetadata;
28
use JMS\Serializer\Metadata\PropertyMetadata;
29
use JMS\Serializer\Metadata\VirtualPropertyMetadata;
30
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
31
use JMS\Serializer\Type\Parser;
32
use JMS\Serializer\Type\ParserInterface;
33
use Metadata\Driver\AbstractFileDriver;
34
use Metadata\Driver\FileLocatorInterface;
35
use Metadata\MethodMetadata;
36
37
class XmlDriver extends AbstractFileDriver
38
{
39
    private $typeParser;
40
    /**
41
     * @var PropertyNamingStrategyInterface
42
     */
43
    private $namingStrategy;
44
45 29
    public function __construct(FileLocatorInterface $locator, PropertyNamingStrategyInterface $namingStrategy, ParserInterface $typeParser = null)
46
    {
47 29
        parent::__construct($locator);
48 29
        $this->typeParser = $typeParser ?? new Parser();
49 29
        $this->namingStrategy = $namingStrategy;
50 29
    }
51
52 29
    protected function loadMetadataFromFile(\ReflectionClass $class, $path)
53
    {
54 29
        $previous = libxml_use_internal_errors(true);
55 29
        libxml_clear_errors();
56
57 29
        $elem = simplexml_load_file($path);
58 29
        libxml_use_internal_errors($previous);
59
60 29
        if (false === $elem) {
61 1
            throw new XmlErrorException(libxml_get_last_error());
62
        }
63
64 28
        $metadata = new ClassMetadata($name = $class->name);
65 28
        if (!$elems = $elem->xpath("./class[@name = '" . $name . "']")) {
66
            throw new RuntimeException(sprintf('Could not find class %s inside XML element.', $name));
67
        }
68 28
        $elem = reset($elems);
69
70 28
        $metadata->fileResources[] = $path;
71 28
        $metadata->fileResources[] = $class->getFileName();
72 28
        $exclusionPolicy = strtoupper((string)$elem->attributes()->{'exclusion-policy'}) ?: 'NONE';
73 28
        $excludeAll = null !== ($exclude = $elem->attributes()->exclude) ? 'true' === strtolower((string)$exclude) : false;
74 28
        $classAccessType = (string)($elem->attributes()->{'access-type'} ?: PropertyMetadata::ACCESS_TYPE_PROPERTY);
75
76 28
        $propertiesMetadata = [];
77 28
        $propertiesNodes = [];
78
79 28
        if (null !== $accessorOrder = $elem->attributes()->{'accessor-order'}) {
80
            $metadata->setAccessorOrder((string)$accessorOrder, preg_split('/\s*,\s*/', (string)$elem->attributes()->{'custom-accessor-order'}));
0 ignored issues
show
Bug introduced by
It seems like preg_split('/\s*,\s*/', ...custom-accessor-order') can also be of type false; however, parameter $customOrder of JMS\Serializer\Metadata\...ata::setAccessorOrder() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

80
            $metadata->setAccessorOrder((string)$accessorOrder, /** @scrutinizer ignore-type */ preg_split('/\s*,\s*/', (string)$elem->attributes()->{'custom-accessor-order'}));
Loading history...
81
        }
82
83 28
        if (null !== $xmlRootName = $elem->attributes()->{'xml-root-name'}) {
84 7
            $metadata->xmlRootName = (string)$xmlRootName;
85
        }
86
87 28
        if (null !== $xmlRootNamespace = $elem->attributes()->{'xml-root-namespace'}) {
88 1
            $metadata->xmlRootNamespace = (string)$xmlRootNamespace;
89
        }
90
91 28
        $readOnlyClass = 'true' === strtolower((string)$elem->attributes()->{'read-only'});
92
93 28
        $discriminatorFieldName = (string)$elem->attributes()->{'discriminator-field-name'};
94 28
        $discriminatorMap = [];
95 28
        foreach ($elem->xpath('./discriminator-class') as $entry) {
96 5
            if (!isset($entry->attributes()->value)) {
97
                throw new RuntimeException('Each discriminator-class element must have a "value" attribute.');
98
            }
99
100 5
            $discriminatorMap[(string)$entry->attributes()->value] = (string)$entry;
101
        }
102
103 28
        if ('true' === (string)$elem->attributes()->{'discriminator-disabled'}) {
104
            $metadata->discriminatorDisabled = true;
105 28
        } elseif (!empty($discriminatorFieldName) || !empty($discriminatorMap)) {
106
107 5
            $discriminatorGroups = [];
108 5
            foreach ($elem->xpath('./discriminator-groups/group') as $entry) {
109 1
                $discriminatorGroups[] = (string)$entry;
110
            }
111 5
            $metadata->setDiscriminator($discriminatorFieldName, $discriminatorMap, $discriminatorGroups);
112
        }
113
114 28
        foreach ($elem->xpath('./xml-namespace') as $xmlNamespace) {
115 3
            if (!isset($xmlNamespace->attributes()->uri)) {
116
                throw new RuntimeException('The prefix attribute must be set for all xml-namespace elements.');
117
            }
118
119 3
            if (isset($xmlNamespace->attributes()->prefix)) {
120 3
                $prefix = (string)$xmlNamespace->attributes()->prefix;
121
            } else {
122 2
                $prefix = null;
123
            }
124
125 3
            $metadata->registerNamespace((string)$xmlNamespace->attributes()->uri, $prefix);
126
        }
127
128 28
        foreach ($elem->xpath('./xml-discriminator') as $xmlDiscriminator) {
129 3
            if (isset($xmlDiscriminator->attributes()->attribute)) {
130 2
                $metadata->xmlDiscriminatorAttribute = (string)$xmlDiscriminator->attributes()->attribute === 'true';
131
            }
132 3
            if (isset($xmlDiscriminator->attributes()->cdata)) {
133 1
                $metadata->xmlDiscriminatorCData = (string)$xmlDiscriminator->attributes()->cdata === 'true';
134
            }
135 3
            if (isset($xmlDiscriminator->attributes()->namespace)) {
136 3
                $metadata->xmlDiscriminatorNamespace = (string)$xmlDiscriminator->attributes()->namespace;
137
            }
138
        }
139
140 28
        foreach ($elem->xpath('./virtual-property') as $method) {
141
142 7
            if (isset($method->attributes()->expression)) {
143 2
                $virtualPropertyMetadata = new ExpressionPropertyMetadata($name, (string)$method->attributes()->name, (string)$method->attributes()->expression);
144
            } else {
145 6
                if (!isset($method->attributes()->method)) {
146
                    throw new RuntimeException('The method attribute must be set for all virtual-property elements.');
147
                }
148 6
                $virtualPropertyMetadata = new VirtualPropertyMetadata($name, (string)$method->attributes()->method);
149
            }
150
151 7
            $propertiesMetadata[] = $virtualPropertyMetadata;
152 7
            $propertiesNodes[] = $method;
153
        }
154
155 28
        if (!$excludeAll) {
156
157 28
            foreach ($class->getProperties() as $property) {
158 23
                if ($property->class !== $name || (isset($property->info) && $property->info['class'] !== $name)) {
0 ignored issues
show
Bug introduced by
The property info does not seem to exist on ReflectionProperty.
Loading history...
159 2
                    continue;
160
                }
161
162 22
                $propertiesMetadata[] = new PropertyMetadata($name, $pName = $property->getName());
163 22
                $pElems = $elem->xpath("./property[@name = '" . $pName . "']");
164
165 22
                $propertiesNodes[] = $pElems ? reset($pElems) : null;
166
            }
167
168 28
            foreach ($propertiesMetadata as $propertyKey => $pMetadata) {
169
170 24
                $isExclude = false;
171 24
                $isExpose = $pMetadata instanceof VirtualPropertyMetadata
172 24
                    || $pMetadata instanceof ExpressionPropertyMetadata;
173
174 24
                $pElem = $propertiesNodes[$propertyKey];
175 24
                if (!empty($pElem)) {
176
177 24
                    if (null !== $exclude = $pElem->attributes()->exclude) {
178 2
                        $isExclude = 'true' === strtolower((string)$exclude);
179
                    }
180
181 24
                    if ($isExclude) {
182 2
                        continue;
183
                    }
184
185 22
                    if (null !== $expose = $pElem->attributes()->expose) {
186 2
                        $isExpose = 'true' === strtolower((string)$expose);
187
                    }
188
189 22
                    if (null !== $excludeIf = $pElem->attributes()->{'exclude-if'}) {
190 1
                        $pMetadata->excludeIf = (string)$excludeIf;
191
                    }
192
193 22
                    if (null !== $skip = $pElem->attributes()->{'skip-when-empty'}) {
194 1
                        $pMetadata->skipWhenEmpty = 'true' === strtolower((string)$skip);
195
                    }
196
197 22
                    if (null !== $excludeIf = $pElem->attributes()->{'expose-if'}) {
198 1
                        $pMetadata->excludeIf = "!(" . (string)$excludeIf . ")";
199 1
                        $isExpose = true;
200
                    }
201
202 22
                    if (null !== $version = $pElem->attributes()->{'since-version'}) {
203
                        $pMetadata->sinceVersion = (string)$version;
204
                    }
205
206 22
                    if (null !== $version = $pElem->attributes()->{'until-version'}) {
207
                        $pMetadata->untilVersion = (string)$version;
208
                    }
209
210 22
                    if (null !== $serializedName = $pElem->attributes()->{'serialized-name'}) {
211 6
                        $pMetadata->serializedName = (string)$serializedName;
212
                    }
213
214 22
                    if (null !== $type = $pElem->attributes()->type) {
215 15
                        $pMetadata->setType($this->typeParser->parse((string)$type));
216 10
                    } elseif (isset($pElem->type)) {
217 2
                        $pMetadata->setType($this->typeParser->parse((string)$pElem->type));
218
                    }
219
220 22
                    if (null !== $groups = $pElem->attributes()->groups) {
221 2
                        $pMetadata->groups = preg_split('/\s*,\s*/', trim((string)$groups));
222 21
                    } elseif (isset($pElem->groups)) {
223 1
                        $pMetadata->groups = (array)$pElem->groups->value;
224
                    }
225
226 22
                    if (isset($pElem->{'xml-list'})) {
227
228 2
                        $pMetadata->xmlCollection = true;
229
230 2
                        $colConfig = $pElem->{'xml-list'};
231 2
                        if (isset($colConfig->attributes()->inline)) {
232 1
                            $pMetadata->xmlCollectionInline = 'true' === (string)$colConfig->attributes()->inline;
233
                        }
234
235 2
                        if (isset($colConfig->attributes()->{'entry-name'})) {
236 1
                            $pMetadata->xmlEntryName = (string)$colConfig->attributes()->{'entry-name'};
237
                        }
238
239 2
                        if (isset($colConfig->attributes()->{'skip-when-empty'})) {
240 1
                            $pMetadata->xmlCollectionSkipWhenEmpty = 'true' === (string)$colConfig->attributes()->{'skip-when-empty'};
241
                        } else {
242 1
                            $pMetadata->xmlCollectionSkipWhenEmpty = true;
243
                        }
244
245 2
                        if (isset($colConfig->attributes()->namespace)) {
246
                            $pMetadata->xmlEntryNamespace = (string)$colConfig->attributes()->namespace;
247
                        }
248
                    }
249
250 22
                    if (isset($pElem->{'xml-map'})) {
251
                        $pMetadata->xmlCollection = true;
252
253
                        $colConfig = $pElem->{'xml-map'};
254
                        if (isset($colConfig->attributes()->inline)) {
255
                            $pMetadata->xmlCollectionInline = 'true' === (string)$colConfig->attributes()->inline;
256
                        }
257
258
                        if (isset($colConfig->attributes()->{'entry-name'})) {
259
                            $pMetadata->xmlEntryName = (string)$colConfig->attributes()->{'entry-name'};
260
                        }
261
262
                        if (isset($colConfig->attributes()->namespace)) {
263
                            $pMetadata->xmlEntryNamespace = (string)$colConfig->attributes()->namespace;
264
                        }
265
266
                        if (isset($colConfig->attributes()->{'key-attribute-name'})) {
267
                            $pMetadata->xmlKeyAttribute = (string)$colConfig->attributes()->{'key-attribute-name'};
268
                        }
269
                    }
270
271 22
                    if (isset($pElem->{'xml-element'})) {
272 4
                        $colConfig = $pElem->{'xml-element'};
273 4
                        if (isset($colConfig->attributes()->cdata)) {
274 2
                            $pMetadata->xmlElementCData = 'true' === (string)$colConfig->attributes()->cdata;
275
                        }
276
277 4
                        if (isset($colConfig->attributes()->namespace)) {
278 3
                            $pMetadata->xmlNamespace = (string)$colConfig->attributes()->namespace;
279
                        }
280
                    }
281
282 22
                    if (isset($pElem->attributes()->{'xml-attribute'})) {
283 4
                        $pMetadata->xmlAttribute = 'true' === (string)$pElem->attributes()->{'xml-attribute'};
284
                    }
285
286 22
                    if (isset($pElem->attributes()->{'xml-attribute-map'})) {
287
                        $pMetadata->xmlAttributeMap = 'true' === (string)$pElem->attributes()->{'xml-attribute-map'};
288
                    }
289
290 22
                    if (isset($pElem->attributes()->{'xml-value'})) {
291 2
                        $pMetadata->xmlValue = 'true' === (string)$pElem->attributes()->{'xml-value'};
292
                    }
293
294 22
                    if (isset($pElem->attributes()->{'xml-key-value-pairs'})) {
295 1
                        $pMetadata->xmlKeyValuePairs = 'true' === (string)$pElem->attributes()->{'xml-key-value-pairs'};
296
                    }
297
298 22
                    if (isset($pElem->attributes()->{'max-depth'})) {
299 1
                        $pMetadata->maxDepth = (int)$pElem->attributes()->{'max-depth'};
300
                    }
301
302
                    //we need read-only before setter and getter set, because that method depends on flag being set
303 22
                    if (null !== $readOnly = $pElem->attributes()->{'read-only'}) {
304 1
                        $pMetadata->readOnly = 'true' === strtolower((string)$readOnly);
305
                    } else {
306 21
                        $pMetadata->readOnly = $pMetadata->readOnly || $readOnlyClass;
307
                    }
308
309 22
                    $getter = $pElem->attributes()->{'accessor-getter'};
310 22
                    $setter = $pElem->attributes()->{'accessor-setter'};
311 22
                    $pMetadata->setAccessor(
312 22
                        (string)($pElem->attributes()->{'access-type'} ?: $classAccessType),
313 22
                        $getter ? (string)$getter : null,
314 22
                        $setter ? (string)$setter : null
315
                    );
316
317 22
                    if (null !== $inline = $pElem->attributes()->inline) {
318
                        $pMetadata->inline = 'true' === strtolower((string)$inline);
319
                    }
320
                }
321
322 24
                if ($pMetadata->inline && PropertyMetadata::isCollectionList($pMetadata->type)) {
323
                    $metadata->isList = true;
324
                }
325
326 24
                if (!$pMetadata->serializedName) {
327 24
                    $pMetadata->serializedName = $this->namingStrategy->translateName($pMetadata);
328
                }
329
330 24
                if (!empty($pElem) && null !== $name = $pElem->attributes()->name) {
331 19
                    $pMetadata->name = (string)$name;
332
                }
333
334 24
                if ((ExclusionPolicy::NONE === (string)$exclusionPolicy && !$isExclude)
335 24
                    || (ExclusionPolicy::ALL === (string)$exclusionPolicy && $isExpose)
336
                ) {
337
338
339 24
                    $metadata->addPropertyMetadata($pMetadata);
340
                }
341
            }
342
        }
343
344 28
        foreach ($elem->xpath('./callback-method') as $method) {
345
            if (!isset($method->attributes()->type)) {
346
                throw new RuntimeException('The type attribute must be set for all callback-method elements.');
347
            }
348
            if (!isset($method->attributes()->name)) {
349
                throw new RuntimeException('The name attribute must be set for all callback-method elements.');
350
            }
351
352
            switch ((string)$method->attributes()->type) {
353
                case 'pre-serialize':
354
                    $metadata->addPreSerializeMethod(new MethodMetadata($name, (string)$method->attributes()->name));
355
                    break;
356
357
                case 'post-serialize':
358
                    $metadata->addPostSerializeMethod(new MethodMetadata($name, (string)$method->attributes()->name));
359
                    break;
360
361
                case 'post-deserialize':
362
                    $metadata->addPostDeserializeMethod(new MethodMetadata($name, (string)$method->attributes()->name));
363
                    break;
364
365
                case 'handler':
366
                    if (!isset($method->attributes()->format)) {
367
                        throw new RuntimeException('The format attribute must be set for "handler" callback methods.');
368
                    }
369
                    if (!isset($method->attributes()->direction)) {
370
                        throw new RuntimeException('The direction attribute must be set for "handler" callback methods.');
371
                    }
372
373
                    break;
374
375
                default:
376
                    throw new RuntimeException(sprintf('The type "%s" is not supported.', $method->attributes()->name));
377
            }
378
        }
379
380 28
        return $metadata;
381
    }
382
383 28
    protected function getExtension()
384
    {
385 28
        return 'xml';
386
    }
387
}
388