Passed
Pull Request — master (#71)
by Axel
09:04
created

SchemaReader::loadElement()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 5
Bugs 1 Features 1
Metric Value
eloc 5
c 5
b 1
f 1
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GoetasWebservices\XML\XSDReader;
6
7
use Closure;
8
use DOMDocument;
9
use DOMElement;
10
use DOMNode;
11
use GoetasWebservices\XML\XSDReader\Documentation\DocumentationReader;
12
use GoetasWebservices\XML\XSDReader\Documentation\StandardDocumentationReader;
13
use GoetasWebservices\XML\XSDReader\Exception\IOException;
14
use GoetasWebservices\XML\XSDReader\Exception\TypeException;
15
use GoetasWebservices\XML\XSDReader\Schema\Attribute\Attribute;
16
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeContainer;
17
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeDef;
18
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeItem;
19
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeSingle;
20
use GoetasWebservices\XML\XSDReader\Schema\Attribute\Group as AttributeGroup;
21
use GoetasWebservices\XML\XSDReader\Schema\Element\AbstractElementSingle;
22
use GoetasWebservices\XML\XSDReader\Schema\Element\Choice;
23
use GoetasWebservices\XML\XSDReader\Schema\Element\Element;
24
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementContainer;
25
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementDef;
26
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementRef;
27
use GoetasWebservices\XML\XSDReader\Schema\Element\Group;
28
use GoetasWebservices\XML\XSDReader\Schema\Element\GroupRef;
29
use GoetasWebservices\XML\XSDReader\Schema\Element\InterfaceSetDefault;
30
use GoetasWebservices\XML\XSDReader\Schema\Element\InterfaceSetFixed;
31
use GoetasWebservices\XML\XSDReader\Schema\Element\InterfaceSetMinMax;
32
use GoetasWebservices\XML\XSDReader\Schema\Exception\TypeNotFoundException;
33
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Base;
34
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Extension;
35
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Restriction;
36
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\RestrictionType;
37
use GoetasWebservices\XML\XSDReader\Schema\Item;
38
use GoetasWebservices\XML\XSDReader\Schema\Schema;
39
use GoetasWebservices\XML\XSDReader\Schema\SchemaItem;
40
use GoetasWebservices\XML\XSDReader\Schema\Type\BaseComplexType;
41
use GoetasWebservices\XML\XSDReader\Schema\Type\ComplexType;
42
use GoetasWebservices\XML\XSDReader\Schema\Type\ComplexTypeSimpleContent;
43
use GoetasWebservices\XML\XSDReader\Schema\Type\SimpleType;
44
use GoetasWebservices\XML\XSDReader\Schema\Type\Type;
45
use GoetasWebservices\XML\XSDReader\Utils\UrlUtils;
46
47
class SchemaReader
48
{
49
    public const XSD_NS = 'http://www.w3.org/2001/XMLSchema';
50
51
    public const XML_NS = 'http://www.w3.org/XML/1998/namespace';
52
53
    private DocumentationReader $documentationReader;
54
55
    /**
56
     * @var Schema[]
57
     */
58
    private array $loadedFiles = [];
59
60
    /**
61
     * @var Schema[][]
62
     */
63
    private array $loadedSchemas = [];
64
65
    /**
66
     * @var string[]
67
     */
68
    protected array $knownLocationSchemas = [
69
        'http://www.w3.org/2001/xml.xsd' => (
70
            __DIR__ . '/Resources/xml.xsd'
71
        ),
72
        'http://www.w3.org/2001/XMLSchema.xsd' => (
73
            __DIR__ . '/Resources/XMLSchema.xsd'
74
        ),
75
        'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' => (
76
            __DIR__ . '/Resources/oasis-200401-wss-wssecurity-secext-1.0.xsd'
77
        ),
78
        'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' => (
79
            __DIR__.'/Resources/oasis-200401-wss-wssecurity-utility-1.0.xsd'
80
        ),
81
        'https://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd' => (
82
            __DIR__.'/Resources/xmldsig-core-schema.xsd'
83
        ),
84
        'http://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd' => (
85
            __DIR__.'/Resources/xmldsig-core-schema.xsd'
86
        ),
87
    ];
88
89
    /**
90
     * @var string[]
91
     */
92
    protected array $knownNamespaceSchemaLocations = [
93
        'http://www.w3.org/2000/09/xmldsig#' => (
94
            __DIR__ . '/Resources/xmldsig-core-schema.xsd'
95
        ),
96
    ];
97
98
    /**
99
     * @var string[]
100 2
     */
101
    protected static array $globalSchemaInfo = [
102 2
        self::XML_NS => 'http://www.w3.org/2001/xml.xsd',
103
        self::XSD_NS => 'http://www.w3.org/2001/XMLSchema.xsd',
104 2
    ];
105 1
106
    private function extractErrorMessage(): \Exception
107 2
    {
108 2
        $errors = [];
109
110 2
        foreach (libxml_get_errors() as $error) {
111
            $errors[] = sprintf("Error[%s] code %s: %s in '%s' at position %s:%s", $error->level, $error->code, trim($error->message), $error->file, $error->line, $error->column);
112
        }
113 85
        $e = new \Exception(implode('; ', $errors));
114
        libxml_use_internal_errors(false);
115 85
116 85
        return $e;
117
    }
118 85
119 85
    public function __construct(DocumentationReader $documentationReader = null)
120
    {
121
        if (null === $documentationReader) {
122
            $documentationReader = new StandardDocumentationReader();
123
        }
124
        $this->documentationReader = $documentationReader;
125
    }
126
127 1
    /**
128
     * Override remote location with a local file.
129 1
     *
130 1
     * @param string $remote remote schema URL
131
     * @param string $local  local file path
132
     */
133
    public function addKnownSchemaLocation(string $remote, string $local): void
134
    {
135
        $this->knownLocationSchemas[$remote] = $local;
136
    }
137
138
    /**
139 1
     * Specify schema location by namespace.
140
     * This can be used for schemas which import namespaces but do not specify schemaLocation attributes.
141 1
     *
142 1
     * @param string $namespace namespace
143
     * @param string $location  schema URL
144 74
     */
145
    public function addKnownNamespaceSchemaLocation(string $namespace, string $location): void
146
    {
147
        $this->knownNamespaceSchemaLocations[$namespace] = $location;
148 74
    }
149 74
150 74
    private function loadAttributeGroup(
151
        Schema $schema,
152
        DOMElement $node
153 74
    ): Closure {
154 74
        $attGroup = new AttributeGroup($schema, $node->getAttribute('name'));
155
        $attGroup->setDoc($this->getDocumentation($node));
156
        $schema->addAttributeGroup($attGroup);
157
158
        return function () use ($schema, $node, $attGroup): void {
159 74
            SchemaReader::againstDOMNodeList(
160 74
                $node,
161
                function (
162 74
                    DOMElement $node,
163 74
                    DOMElement $childNode
164 74
                ) use (
165 74
                    $schema,
166 74
                    $attGroup
167 74
                ): void {
168
                    switch ($childNode->localName) {
169 74
                        case 'attribute':
170 74
                            $attribute = $this->getAttributeFromAttributeOrRef(
171 74
                                $childNode,
172 1
                                $schema,
173 1
                                $node
174 1
                            );
175 1
                            $attGroup->addAttribute($attribute);
176 1
                            break;
177
                        case 'attributeGroup':
178 1
                            $this->findSomethingLikeAttributeGroup(
179
                                $schema,
180 74
                                $node,
181
                                $childNode,
182 74
                                $attGroup
183
                            );
184
                            break;
185 74
                    }
186
                }
187
            );
188
        };
189
    }
190 74
191 74
    private function getAttributeFromAttributeOrRef(
192
        DOMElement $childNode,
193
        Schema $schema,
194
        DOMElement $node
195
    ): AttributeItem {
196 74
        if ($childNode->hasAttribute('ref')) {
197
            $attribute = $this->findAttributeItem($schema, $node, $childNode->getAttribute('ref'));
198
        } else {
199 74
            /**
200
             * @var Attribute
201
             */
202 74
            $attribute = $this->loadAttribute($schema, $childNode);
203
        }
204
205
        return $attribute;
206 74
    }
207 74
208 74
    private function loadAttribute(Schema $schema, DOMElement $node): Attribute
209
    {
210 74
        $attribute = new Attribute($schema, $node->getAttribute('name'));
211 1
        $attribute->setDoc($this->getDocumentation($node));
212
        $this->fillItem($attribute, $node);
213 74
        $this->fillAttribute($attribute, $node);
214 1
215
        return $attribute;
216 74
    }
217 74
218
    private function fillAttribute(AttributeSingle $attribute, DOMElement $node): void
219
    {
220 74
        if ($node->hasAttribute('fixed')) {
221
            $attribute->setFixed($node->getAttribute('fixed'));
0 ignored issues
show
Bug introduced by
The method setFixed() does not exist on GoetasWebservices\XML\XS...tribute\AttributeSingle. Since it exists in all sub-types, consider adding an abstract or default implementation to GoetasWebservices\XML\XS...tribute\AttributeSingle. ( Ignorable by Annotation )

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

221
            $attribute->/** @scrutinizer ignore-call */ 
222
                        setFixed($node->getAttribute('fixed'));
Loading history...
222
        }
223 74
        if ($node->hasAttribute('default')) {
224
            $attribute->setDefault($node->getAttribute('default'));
0 ignored issues
show
Bug introduced by
The method setDefault() does not exist on GoetasWebservices\XML\XS...tribute\AttributeSingle. Since it exists in all sub-types, consider adding an abstract or default implementation to GoetasWebservices\XML\XS...tribute\AttributeSingle. ( Ignorable by Annotation )

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

224
            $attribute->/** @scrutinizer ignore-call */ 
225
                        setDefault($node->getAttribute('default'));
Loading history...
225
        }
226
        if ($node->hasAttribute('nillable')) {
227
            $attribute->setNil('true' === $node->getAttribute('nillable'));
228 74
        }
229 74
        if ($node->hasAttribute('form')) {
230 74
            $attribute->setQualified('qualified' === $node->getAttribute('form'));
231 74
        }
232
        if ($node->hasAttribute('use')) {
233 74
            $attribute->setUse($node->getAttribute('use'));
234 74
        }
235 74
    }
236
237
    private function loadAttributeOrElementDef(
238
        Schema $schema,
239 74
        DOMElement $node,
240 74
        bool $isAttribute
241
    ): Closure {
242
        $name = $node->getAttribute('name');
243 74
        if ($isAttribute) {
244
            $attribute = new AttributeDef($schema, $name);
245 74
            $attribute->setDoc($this->getDocumentation($node));
246
            $this->fillAttribute($attribute, $node);
247
            $schema->addAttribute($attribute);
248 74
        } else {
249
            $attribute = new ElementDef($schema, $name);
250 74
            $attribute->setDoc($this->getDocumentation($node));
251
            $this->fillElement($attribute, $node);
252
            $schema->addElement($attribute);
253
        }
254
255
        return function () use ($attribute, $node): void {
256 74
            $this->fillItem($attribute, $node);
257
        };
258 74
    }
259 74
260
    private function loadElementDef(Schema $schema, DOMElement $node): Closure
261 74
    {
262 74
        return $this->loadAttributeOrElementDef($schema, $node, false);
263
    }
264
265
    private function loadAttributeDef(Schema $schema, DOMElement $node): Closure
266
    {
267 74
        return $this->loadAttributeOrElementDef($schema, $node, true);
268 74
    }
269
270 74
    private function getDocumentation(DOMElement $node): string
271
    {
272 74
        return $this->documentationReader->get($node);
273 74
    }
274 74
275 74
    /**
276 74
     * @return Closure[]
277 74
     */
278 74
    private function schemaNode(Schema $schema, DOMElement $node, Schema $parent = null): array
279 74
    {
280 74
        $this->setSchemaThingsFromNode($schema, $node, $parent);
281 74
        $functions = [];
282 74
283 74
        self::againstDOMNodeList(
284 74
            $node,
285 74
            function (DOMElement $node, DOMElement $childNode) use ($schema, &$functions): void {
286 74
                $callback = null;
287 74
288 74
                switch ($childNode->localName) {
289 74
                    case 'attributeGroup':
290 74
                        $callback = $this->loadAttributeGroup($schema, $childNode);
291 74
                        break;
292 74
                    case 'include':
293 74
                    case 'import':
294 74
                        $callback = $this->loadImport($schema, $childNode);
295
                        break;
296
                    case 'element':
297 74
                        $callback = $this->loadElementDef($schema, $childNode);
298 74
                        break;
299
                    case 'attribute':
300 74
                        $callback = $this->loadAttributeDef($schema, $childNode);
301
                        break;
302
                    case 'group':
303 74
                        $callback = $this->loadGroup($schema, $childNode);
304
                        break;
305
                    case 'choice':
306 74
                        $callback = $this->loadChoice($schema, $childNode);
307
                        break;
308 74
                    case 'complexType':
309 74
                        $callback = $this->loadComplexType($schema, $childNode);
310
                        break;
311 74
                    case 'simpleType':
312 74
                        $callback = $this->loadSimpleType($schema, $childNode);
313
                        break;
314 74
                }
315
316
                if ($callback instanceof Closure) {
317 74
                    $functions[] = $callback;
318
                }
319 74
            }
320 74
        );
321
322 74
        return $functions;
323
    }
324 74
325
    private function createGroupRef(Group $referenced, DOMElement $node): GroupRef
326 74
    {
327 74
        $ref = new GroupRef($referenced);
328 74
        $ref->setDoc($this->getDocumentation($node));
329 7
330
        self::maybeSetMax($ref, $node);
331
        self::maybeSetMin($ref, $node);
332 74
333
        return $ref;
334 74
    }
335
336 74
    private static function maybeSetMax(InterfaceSetMinMax $ref, DOMElement $node): void
337 1
    {
338
        if ($node->hasAttribute('maxOccurs')) {
339 74
            $ref->setMax('unbounded' === $node->getAttribute('maxOccurs') ? -1 : (int) $node->getAttribute('maxOccurs'));
340
        }
341 74
    }
342
343
    private static function maybeSetMin(InterfaceSetMinMax $ref, DOMElement $node): void
344
    {
345 74
        if ($node->hasAttribute('minOccurs')) {
346 74
            $ref->setMin((int) $node->getAttribute('minOccurs'));
347 74
            if (-1 !== $ref->getMax() && $ref->getMin() > $ref->getMax()) {
348
                $ref->setMax($ref->getMin());
349 74
            }
350 74
        }
351
    }
352
353 74
    private static function maybeSetFixed(InterfaceSetFixed $ref, DOMElement $node): void
354 74
    {
355
        if ($node->hasAttribute('fixed')) {
356 74
            $ref->setFixed($node->getAttribute('fixed'));
357 74
        }
358
    }
359 74
360 74
    private static function maybeSetDefault(InterfaceSetDefault $ref, DOMElement $node): void
361
    {
362
        if ($node->hasAttribute('default')) {
363
            $ref->setDefault($node->getAttribute('default'));
364
        }
365 74
    }
366 74
367 74
    private function loadSequence(ElementContainer $elementContainer, DOMElement $node, int $max = null, int $min = null): void
368
    {
369 74
        $max =
370 74
            (
371 74
                (is_int($max) && (bool) $max) ||
372 74
                'unbounded' === $node->getAttribute('maxOccurs') ||
373 74
                1 < $node->getAttribute('maxOccurs')
374 74
            )
375
                ? 2
376 74
                : null;
377
        $min =
378 74
            (
379
                null === $min &&
380 74
                !$node->hasAttribute('minOccurs')
381
            )
382
                ? null
383
                : (int) max((int) $min, $node->getAttribute('minOccurs'));
384
385
        self::againstDOMNodeList(
386
            $node,
387 74
            function (DOMElement $node, DOMElement $childNode) use ($elementContainer, $max, $min): void {
388 74
                $this->loadSequenceChildNode(
389 74
                    $elementContainer,
390 74
                    $node,
391 74
                    $childNode,
392 74
                    $max,
393 74
                    $min
394 74
                );
395 74
            }
396
        );
397 74
    }
398 74
399 74
    private function loadSequenceChildNode(
400 74
        ElementContainer $elementContainer,
401 74
        DOMElement $node,
402 74
        DOMElement $childNode,
403 74
        ?int $max,
404 74
        ?int $min = null
405
    ): void {
406 74
        switch ($childNode->localName) {
407 74
            case 'sequence':
408 74
            case 'all':
409 74
                $this->loadSequence(
410 74
                    $elementContainer,
411 74
                    $childNode,
412 74
                    $max,
413
                    $min
414 74
                );
415
                break;
416 74
            case 'choice':
417
                $this->loadChoiceWithChildren($elementContainer->getSchema(), $childNode, $elementContainer);
418 74
                break;
419
            case 'element':
420
                $this->loadSequenceChildNodeLoadElement(
421
                    $elementContainer,
422
                    $node,
423
                    $childNode,
424
                    $max,
425 74
                    $min
426 74
                );
427 74
                break;
428 74
            case 'group':
429
                $this->addGroupAsElement(
430 74
                    $elementContainer->getSchema(),
431 74
                    $node,
432
                    $childNode,
433 74
                    $elementContainer
434 74
                );
435
                break;
436 74
        }
437 74
    }
438
439
    private function loadSequenceChildNodeLoadElement(
440 74
        ElementContainer $elementContainer,
441
        DOMElement $node,
442
        DOMElement $childNode,
443 74
        ?int $max,
444 74
        ?int $min
445
    ): void {
446
        if ($childNode->hasAttribute('ref')) {
447 74
            $elementDef = $this->findElement($elementContainer->getSchema(), $node, $childNode->getAttribute('ref'));
448 74
            $element = new ElementRef($elementDef);
449 74
            $element->setDoc($this->getDocumentation($childNode));
450
            $this->fillElement($element, $childNode);
451
        } else {
452
            $element = $this->loadElement($elementContainer->getSchema(), $childNode);
453 74
        }
454 74
455
        if (null !== $min) {
456
            $element->setMin($min);
457 74
        }
458
459
        if (1 < $max) {
460
            /*
461
             * although one might think the typecast is not needed with $max being `? int $max` after passing > 1,
462
             * phpstan@a4f89fa still thinks it's possibly null.
463 74
             * see https://github.com/phpstan/phpstan/issues/577 for related issue
464
             */
465 74
            $element->setMax((int) $max);
466 74
        }
467
        $elementContainer->addElement($element);
468 74
    }
469
470
    private function addGroupAsElement(
471
        Schema $schema,
472
        DOMElement $node,
473
        DOMElement $childNode,
474 74
        ElementContainer $elementContainer
475 74
    ): void {
476 74
        $referencedGroup = $this->findGroup(
477 74
            $schema,
478
            $node,
479
            $childNode->getAttribute('ref')
480 74
        );
481 74
482 74
        $group = $this->createGroupRef($referencedGroup, $childNode);
483
        $elementContainer->addElement($group);
484 74
    }
485
486 74
    private function loadChoiceWithChildren(
487 74
        Schema $schema,
488 74
        DOMElement $node,
489
        ElementContainer $elementContainer
490 74
    ): void {
491 1
        $choice = $this->createChoice($schema, $node);
492
        $elementContainer->addElement($choice);
493 1
494 1
        self::againstDOMNodeList(
495
            $node,
496 1
            function (DOMElement $node, DOMElement $childNode) use ($choice): void {
497 1
                $this->loadSequenceChildNode(
498
                    $choice,
499
                    $node,
500
                    $childNode,
501 74
                    null,
502
                    null
503
                );
504 74
            }
505 74
        );
506
    }
507 74
508 74
    private function loadGroup(Schema $schema, DOMElement $node): Closure
509 74
    {
510 74
        $group = new Group($schema, $node->getAttribute('name'));
511 74
        $group->setDoc($this->getDocumentation($node));
512 74
        $groupOriginal = $group;
513
514 74
        if ($node->hasAttribute('maxOccurs') || $node->hasAttribute('minOccurs')) {
515
            $group = $this->createGroupRef($group, $node);
516 74
        }
517
518
        $schema->addGroup($group);
519 74
520
        return function () use ($groupOriginal, $node): void {
521
            static::againstDOMNodeList(
522
                $node,
523
                function (DOMelement $node, DOMElement $childNode) use ($groupOriginal): void {
524 74
                    switch ($childNode->localName) {
525
                        case 'sequence':
526 74
                        case 'all':
527 74
                            $this->loadSequence($groupOriginal, $childNode);
528
                            break;
529
                        case 'choice':
530
                            $this->loadChoiceWithChildren($groupOriginal->getSchema(), $childNode, $groupOriginal);
531
                    }
532 74
                }
533
            );
534 74
        };
535 1
    }
536
537 74
    private function loadChoice(Schema $schema, DOMElement $node): Closure
538 2
    {
539
        $choice = $this->createChoice($schema, $node);
540 74
541
        return function () use ($choice, $node): void {
542
            self::againstDOMNodeList(
543 74
                $node,
544
                function (DOMElement $node, DOMElement $childNode) use ($choice): void {
545 74
                    $this->loadSequenceChildNode(
546 74
                        $choice,
547 74
                        $node,
548
                        $childNode,
549
                        null,
550
                        null
551 74
                    );
552
                }
553 74
            );
554 74
        };
555
    }
556
557
    private function createChoice(Schema $schema, DOMElement $node): Choice
558
    {
559 74
        $choice = new Choice($schema, '');
560 74
        $choice->setDoc($this->getDocumentation($node));
561
        self::maybeSetMax($choice, $node);
562 74
        self::maybeSetMin($choice, $node);
563 74
564 74
        return $choice;
565 74
    }
566 74
567
    private function loadComplexType(Schema $schema, DOMElement $node, Closure $callback = null): Closure
568 74
    {
569
        /**
570
         * @var bool
571 74
         */
572 74
        $isSimple = false;
573
574 74
        self::againstDOMNodeList(
575
            $node,
576
            function (DOMElement $node, DOMElement $childNode) use (&$isSimple): void {
577 74
                if ($isSimple) {
578
                    return;
579
                }
580
                if ('simpleContent' === $childNode->localName) {
581
                    $isSimple = true;
582
                }
583 74
            }
584 74
        );
585 74
586 74
        $type = $isSimple ? new ComplexTypeSimpleContent($schema, $node->getAttribute('name')) : new ComplexType($schema, $node->getAttribute('name'));
587 74
588 74
        $type->setDoc($this->getDocumentation($node));
589 74
        if ($node->getAttribute('name')) {
590 74
            $schema->addType($type);
591
        }
592
593 74
        return function () use ($type, $node, $schema, $callback): void {
594 74
            $this->fillTypeNode($type, $node, true);
595 74
596 74
            self::againstDOMNodeList(
597 74
                $node,
598 74
                function (DOMElement $node, DOMElement $childNode) use ($schema, $type): void {
599 74
                    $this->loadComplexTypeFromChildNode($type, $node, $childNode, $schema);
600
                }
601 74
            );
602 74
603 2
            if ($callback instanceof Closure) {
604 2
                call_user_func($callback, $type);
605 2
            }
606 2
        };
607 2
    }
608
609 2
    private function loadComplexTypeFromChildNode(
610 74
        BaseComplexType $type,
611
        DOMElement $node,
612 1
        DOMElement $childNode,
613
        Schema $schema
614 1
    ): void {
615 1
        switch ($childNode->localName) {
616 1
            case 'sequence':
617 1
            case 'all':
618 1
                if ($type instanceof ElementContainer) {
619
                    $this->loadSequence($type, $childNode);
620
                }
621 1
                break;
622
            case 'choice':
623 74
                if ($type instanceof ComplexType) {
624
                    $this->loadChoiceWithChildren($schema, $childNode, $type);
625 74
                }
626
                break;
627 74
            case 'attribute':
628 74
                $this->addAttributeFromAttributeOrRef($type, $childNode, $schema, $node);
629 74
                break;
630 74
            case 'attributeGroup':
631
                $this->findSomethingLikeAttributeGroup($schema, $node, $childNode, $type);
632
                break;
633
            case 'group':
634 74
                if ($type instanceof ComplexType) {
635
                    $this->addGroupAsElement($schema, $node, $childNode, $type);
636 74
                }
637 74
                break;
638
        }
639 74
    }
640 74
641 74
    private function loadSimpleType(Schema $schema, DOMElement $node, Closure $callback = null): Closure
642 74
    {
643 74
        $type = new SimpleType($schema, $node->getAttribute('name'));
644 74
        $type->setDoc($this->getDocumentation($node));
645 74
        if ($node->getAttribute('name')) {
646
            $schema->addType($type);
647 74
        }
648
649
        return function () use ($type, $node, $callback): void {
650 74
            $this->fillTypeNode($type, $node, true);
651 74
652
            self::againstDOMNodeList(
653 74
                $node,
654
                function (DOMElement $node, DOMElement $childNode) use ($type): void {
655
                    switch ($childNode->localName) {
656 74
                        case 'union':
657
                            $this->loadUnion($type, $childNode);
658 74
                            break;
659
                        case 'list':
660
                            $this->loadList($type, $childNode);
661
                            break;
662 74
                    }
663 74
                }
664
            );
665 74
666 74
            if ($callback instanceof Closure) {
667
                call_user_func($callback, $type);
668
            }
669
        };
670
    }
671 74
672
    private function loadList(SimpleType $type, DOMElement $node): void
673 74
    {
674 74
        if ($node->hasAttribute('itemType')) {
675 74
            /**
676
             * @var SimpleType
677 74
             */
678 74
            $listType = $this->findSomeType($type, $node, 'itemType');
679
            $type->setList($listType);
680 74
        } else {
681
            self::againstDOMNodeList(
682
                $node,
683 74
                function (DOMElement $node, DOMElement $childNode) use ($type): void {
684
                    $this->loadTypeWithCallback(
685 74
                        $type->getSchema(),
686
                        $childNode,
687
                        function (SimpleType $list) use ($type): void {
688
                            $type->setList($list);
689
                        }
690 74
                    );
691 74
                }
692 74
            );
693 74
        }
694
    }
695
696
    private function findSomeType(
697 74
        SchemaItem $fromThis,
698
        DOMElement $node,
699
        string $attributeName
700
    ): SchemaItem {
701
        return $this->findSomeTypeFromAttribute(
702 74
            $fromThis,
703 74
            $node,
704 74
            $node->getAttribute($attributeName)
705 74
        );
706
    }
707
708 74
    private function findSomeTypeFromAttribute(
709
        SchemaItem $fromThis,
710
        DOMElement $node,
711 74
        string $attributeName
712
    ): SchemaItem {
713 74
        return $this->findType(
714 74
            $fromThis->getSchema(),
715 74
            $node,
716
            $attributeName
717
        );
718
    }
719 74
720 74
    private function loadUnion(SimpleType $type, DOMElement $node): void
721 74
    {
722 74
        if ($node->hasAttribute('memberTypes')) {
723
            $types = preg_split('/\s+/', $node->getAttribute('memberTypes'));
724 74
            foreach ($types as $typeName) {
725
                /**
726
                 * @var SimpleType
727 74
                 */
728 74
                $unionType = $this->findSomeTypeFromAttribute(
729
                    $type,
730
                    $node,
731
                    $typeName
732
                );
733 74
                $type->addUnion($unionType);
734
            }
735 74
        }
736 74
        self::againstDOMNodeList(
737 74
            $node,
738
            function (DOMElement $node, DOMElement $childNode) use ($type): void {
739 74
                $this->loadTypeWithCallback(
740 74
                    $type->getSchema(),
741
                    $childNode,
742 74
                    function (SimpleType $unType) use ($type): void {
743
                        $type->addUnion($unType);
744 74
                    }
745
                );
746 74
            }
747
        );
748 74
    }
749 74
750
    private function fillTypeNode(Type $type, DOMElement $node, bool $checkAbstract = false): void
751
    {
752 74
        if ($checkAbstract) {
753 74
            $type->setAbstract('true' === $node->getAttribute('abstract') || '1' === $node->getAttribute('abstract'));
754
        }
755 74
756 74
        self::againstDOMNodeList(
757 74
            $node,
758 74
            function (DOMElement $node, DOMElement $childNode) use ($type): void {
759 74
                switch ($childNode->localName) {
760 74
                    case 'restriction':
761 74
                        $this->loadRestriction($type, $childNode);
762
                        break;
763 74
                    case 'extension':
764 74
                        if ($type instanceof BaseComplexType) {
765 74
                            $this->loadExtension($type, $childNode);
766 74
                        }
767 74
                        break;
768
                    case 'simpleContent':
769 74
                    case 'complexContent':
770
                        $this->fillTypeNode($type, $childNode);
771 74
                        break;
772
                }
773 74
            }
774
        );
775 74
    }
776 74
777
    private function loadExtension(BaseComplexType $type, DOMElement $node): void
778 74
    {
779 74
        $extension = new Extension();
780 74
        $type->setExtension($extension);
781 74
782 74
        if ($node->hasAttribute('base')) {
783
            $this->findAndSetSomeBase($type, $extension, $node);
784
        }
785 74
        $this->loadExtensionChildNodes($type, $node);
786 74
    }
787
788 74
    private function findAndSetSomeBase(
789
        Type $type,
790
        Base $setBaseOnThis,
791
        DOMElement $node
792
    ): void {
793
        /**
794
         * @var Type
795
         */
796 74
        $parent = $this->findSomeType($type, $node, 'base');
797 74
        $setBaseOnThis->setBase($parent);
798 74
    }
799
800 74
    private function loadExtensionChildNodes(
801
        BaseComplexType $type,
802
        DOMElement $node
803
    ): void {
804 74
        self::againstDOMNodeList(
805 74
            $node,
806
            function (DOMElement $node, DOMElement $childNode) use ($type): void {
807
                switch ($childNode->localName) {
808
                    case 'sequence':
809
                    case 'choice':
810 74
                    case 'all':
811
                        if ($type instanceof ElementContainer) {
812 74
                            $this->loadSequence($type, $childNode);
813 74
                        }
814 74
                        break;
815 74
                }
816 74
                $this->loadChildAttributesAndAttributeGroups($type, $node, $childNode);
817 74
            }
818 74
        );
819 74
    }
820
821
    private function loadChildAttributesAndAttributeGroups(
822 74
        BaseComplexType $type,
823 74
        DOMElement $node,
824 74
        DOMElement $childNode
825 74
    ): void {
826 74
        switch ($childNode->localName) {
827 74
            case 'attribute':
828 74
                $this->addAttributeFromAttributeOrRef(
829
                    $type,
830 74
                    $childNode,
831 74
                    $type->getSchema(),
832 74
                    $node
833 74
                );
834 74
                break;
835 74
            case 'attributeGroup':
836 74
                $this->findSomethingLikeAttributeGroup(
837
                    $type->getSchema(),
838 74
                    $node,
839
                    $childNode,
840 74
                    $type
841
                );
842 74
                break;
843
        }
844 74
    }
845
846 74
    private function loadRestriction(Type $type, DOMElement $node): void
847 74
    {
848 74
        $restriction = new Restriction();
849 74
        $type->setRestriction($restriction);
850
        if ($node->hasAttribute('base')) {
851 74
            $this->findAndSetSomeBase($type, $restriction, $node);
852 74
        } else {
853
            self::againstDOMNodeList(
854
                $node,
855
                function (
856
                    DOMElement $node,
857 74
                    DOMElement $childNode
858 74
                ) use (
859
                    $type,
860 74
                    $restriction
861 74
                ): void {
862 74
                    $this->loadTypeWithCallback(
863
                        $type->getSchema(),
864 74
                        $childNode,
865 74
                        function (Type $restType) use ($restriction): void {
866
                            $restriction->setBase($restType);
867 74
                        }
868
                    );
869
                }
870 74
            );
871 74
        }
872
        $this->loadRestrictionChildNodes($type, $restriction, $node);
873
    }
874
875
    private function loadRestrictionChildNodes(
876 74
        Type $type,
877
        Restriction $restriction,
878
        DOMElement $node
879 74
    ): void {
880 74
        self::againstDOMNodeList(
881
            $node,
882 74
            function (
883
                DOMElement $node,
884
                DOMElement $childNode
885
            ) use (
886
                $type,
887
                $restriction
888
            ): void {
889
                if ($type instanceof BaseComplexType) {
890
                    $this->loadChildAttributesAndAttributeGroups($type, $node, $childNode);
891
                }
892
                if (null !== ($restrictionType = RestrictionType::tryFrom($childNode->localName))) {
893
                    $restriction->addCheck(
894
                        $restrictionType,
895 74
                        [
896
                            'value' => $childNode->getAttribute('value'),
897
                            'doc' => $this->getDocumentation($childNode),
898 74
                        ]
899 74
                    );
900
                }
901 74
            }
902 74
        );
903
    }
904
905
    /**
906 74
     * @return mixed[]
907
     */
908 74
    private static function splitParts(DOMElement $node, string $typeName): array
909
    {
910
        $prefix = null;
911
        $name = $typeName;
912
        if (str_contains($typeName, ':')) {
913 74
            [$prefix, $name] = explode(':', $typeName);
914
        }
915 74
916 74
        /**
917 74
         * @psalm-suppress PossiblyNullArgument
918 74
         */
919
        $namespace = $node->lookupNamespaceUri($prefix);
920
921
        return [
922
            $name,
923
            $namespace,
924 74
            $prefix,
925
        ];
926
    }
927 74
928 74
    private function findAttributeItem(Schema $schema, DOMElement $node, string $typeName): AttributeItem
929 74
    {
930
        [$name, $namespace] = static::splitParts($node, $typeName);
931
932
        /**
933 74
         * @var string|null $namespace
934
         */
935 74
        $namespace = $namespace ?: $schema->getTargetNamespace();
936
937
        try {
938
            /**
939
             * @var AttributeItem $out
940 74
             */
941
            $out = $schema->findAttribute((string) $name, $namespace);
942
943
            return $out;
944
        } catch (TypeNotFoundException $e) {
945
            throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", 'attribute', $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI), 0, $e);
946 74
        }
947
    }
948 74
949
    private function findAttributeGroup(Schema $schema, DOMElement $node, string $typeName): AttributeGroup
950
    {
951
        [$name, $namespace] = static::splitParts($node, $typeName);
952
953
        /**
954 74
         * @var string|null $namespace
955
         */
956 74
        $namespace = $namespace ?: $schema->getTargetNamespace();
957
958
        try {
959
            /**
960
             * @var AttributeGroup $out
961 74
             */
962
            $out = $schema->findAttributeGroup((string) $name, $namespace);
963
964
            return $out;
965
        } catch (TypeNotFoundException $e) {
966
            throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", 'attributegroup', $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI), 0, $e);
967 74
        }
968
    }
969 74
970
    private function findElement(Schema $schema, DOMElement $node, string $typeName): ElementDef
971
    {
972
        [$name, $namespace] = static::splitParts($node, $typeName);
973
974
        /**
975 74
         * @var string|null $namespace
976
         */
977 74
        $namespace = $namespace ?: $schema->getTargetNamespace();
978
979
        try {
980
            return $schema->findElement((string) $name, $namespace);
981
        } catch (TypeNotFoundException $e) {
982 74
            throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", 'element', $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI), 0, $e);
983
        }
984
    }
985 74
986
    private function findGroup(Schema $schema, DOMElement $node, string $typeName): Group
987
    {
988
        [$name, $namespace] = static::splitParts($node, $typeName);
989
990
        /**
991 74
         * @var string|null $namespace
992
         */
993 74
        $namespace = $namespace ?: $schema->getTargetNamespace();
994
995
        try {
996
            /**
997
             * @var Group $out
998 74
             */
999
            $out = $schema->findGroup((string) $name, $namespace);
1000
1001
            return $out;
1002
        } catch (TypeNotFoundException $e) {
1003
            throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", 'group', $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI), 0, $e);
1004 74
        }
1005
    }
1006 74
1007
    private function findType(Schema $schema, DOMElement $node, string $typeName): SchemaItem
1008
    {
1009
        [$name, $namespace] = static::splitParts($node, $typeName);
1010
1011
        /**
1012 74
         * @var string|null $namespace
1013
         */
1014 74
        $namespace = $namespace ?: $schema->getTargetNamespace();
1015
1016
        $tryFindType = static function (Schema $schema, string $name, ?string $namespace): ?SchemaItem {
1017
            try {
1018
                return $schema->findType($name, $namespace);
1019 74
            } catch (TypeNotFoundException $e) {
1020
                return null;
1021
            }
1022
        };
1023 74
1024 1
        $interestingSchemas = array_merge([$schema], $this->loadedSchemas[$namespace] ?? []);
1025 1
        foreach ($interestingSchemas as $interestingSchema) {
1026
            if ($result = $tryFindType($interestingSchema, $name, $namespace)) {
1027 74
                return $result;
1028
            }
1029 74
        }
1030 74
1031 74
        throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", 'type', $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI));
1032 74
    }
1033
1034
    private function fillItem(Item $element, DOMElement $node): void
1035
    {
1036
        /**
1037
         * @var bool
1038
         */
1039 74
        $skip = false;
1040
        self::againstDOMNodeList(
1041 74
            $node,
1042
            function (DOMElement $node, DOMElement $childNode) use ($element, &$skip): void {
1043
                if (
1044 74
                    !$skip &&
1045
                    in_array(
1046
                        $childNode->localName,
1047
                        [
1048
                            'complexType',
1049 74
                            'simpleType',
1050 74
                        ],
1051 74
                        true
1052
                    )
1053
                ) {
1054
                    $this->loadTypeWithCallback(
1055
                        $element->getSchema(),
1056 74
                        $childNode,
1057 74
                        function (Type $type) use ($element): void {
1058
                            $element->setType($type);
1059
                        }
1060 74
                    );
1061 74
                    $skip = true;
1062 74
                }
1063
            }
1064 74
        );
1065
        if ($skip) {
1066
            return;
1067 74
        }
1068
        $this->fillItemNonLocalType($element, $node);
1069
    }
1070 74
1071 74
    private function fillItemNonLocalType(Item $element, DOMElement $node): void
1072 74
    {
1073
        if ($node->getAttribute('type')) {
1074 74
            /**
1075 74
             * @var Type
1076
             */
1077 74
            $type = $this->findSomeType($element, $node, 'type');
1078
        } else {
1079 74
            /**
1080
             * @var Type
1081 74
             */
1082 74
            $type = $this->findSomeTypeFromAttribute(
1083
                $element,
1084 74
                $node,
1085 74
                ($node->lookupPrefix(self::XSD_NS).':anyType')
1086
            );
1087 74
        }
1088
1089 74
        $element->setType($type);
1090
    }
1091
1092
    private function loadImport(
1093 74
        Schema $schema,
1094
        DOMElement $node
1095
    ): Closure {
1096
        $namespace = $node->getAttribute('namespace');
1097
        $schemaLocation = $node->getAttribute('schemaLocation');
1098 74
        if (!$schemaLocation && isset($this->knownNamespaceSchemaLocations[$namespace])) {
1099 74
            $schemaLocation = $this->knownNamespaceSchemaLocations[$namespace];
1100 74
        }
1101 74
1102
        // postpone schema loading
1103
        if ($namespace && !$schemaLocation && !isset(self::$globalSchemaInfo[$namespace])) {
1104
            return function () use ($schema, $namespace): void {
1105 74
                if (!empty($this->loadedSchemas[$namespace])) {
1106 74
                    foreach ($this->loadedSchemas[$namespace] as $s) {
1107
                        $schema->addSchema($s, $namespace);
1108 74
                    }
1109
                }
1110
            };
1111
        }
1112 74
1113 74
        if ($namespace && !$schemaLocation && !empty($this->loadedSchemas[$namespace])) {
1114 74
            foreach ($this->loadedSchemas[$namespace] as $s) {
1115 1
                $schema->addSchema($s, $namespace);
1116
            }
1117
        }
1118
1119 74
        $base = urldecode($node->ownerDocument->documentURI);
0 ignored issues
show
Bug introduced by
It seems like $node->ownerDocument->documentURI can also be of type null; however, parameter $string of urldecode() does only seem to accept string, 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

1119
        $base = urldecode(/** @scrutinizer ignore-type */ $node->ownerDocument->documentURI);
Loading history...
1120
        $file = UrlUtils::resolveRelativeUrl($base, $schemaLocation);
1121 3
1122 3
        if (isset($this->loadedFiles[$file])) {
1123 3
            $schema->addSchema($this->loadedFiles[$file]);
1124
1125
            return function (): void {
1126 3
            };
1127 74
        }
1128 1
1129 1
        return $this->loadImportFresh($namespace, $schema, $file);
1130
    }
1131
1132
    private function createOrUseSchemaForNs(
1133 74
        Schema $schema,
1134 74
        string $namespace
1135
    ): Schema {
1136 74
        if (('' !== trim($namespace))) {
1137 74
            $newSchema = new Schema();
1138
            $newSchema->addSchema($this->getGlobalSchema());
1139
            $schema->addSchema($newSchema);
1140 74
        } else {
1141
            $newSchema = $schema;
1142
        }
1143 3
1144
        return $newSchema;
1145
    }
1146 3
1147
    private function loadImportFresh(
1148
        string $namespace,
1149
        Schema $schema,
1150 3
        string $file
1151 2
    ): Closure {
1152 2
        return function () use ($namespace, $schema, $file): void {
1153 2
            $dom = $this->getDOM(
1154
                $this->knownLocationSchemas[$file]
1155 1
                    ?? $file
1156
            );
1157
1158 3
            $schemaNew = $this->createOrUseSchemaForNs($schema, $namespace);
1159
1160
            $this->setLoadedFile($file, $schemaNew);
1161 3
1162
            $callbacks = $this->schemaNode($schemaNew, $dom->documentElement, $schema);
1163
1164
            foreach ($callbacks as $callback) {
1165
                $callback();
1166
            }
1167 3
        };
1168 3
    }
1169 3
1170
    /**
1171
     * @var Schema|null
1172 3
     */
1173
    protected $globalSchema;
1174 3
1175
    public function getGlobalSchema(): Schema
1176 3
    {
1177
        if (!($this->globalSchema instanceof Schema)) {
1178 3
            $callbacks = [];
1179 3
            $globalSchemas = [];
1180
            /**
1181 3
             * @var string $namespace
1182
             */
1183
            foreach (self::$globalSchemaInfo as $namespace => $uri) {
1184
                $this->setLoadedFile(
1185
                    $uri,
1186
                    $globalSchemas[$namespace] = $schema = new Schema()
1187
                );
1188
                $this->setLoadedSchema($namespace, $schema);
1189 74
                if ($namespace === self::XSD_NS) {
1190
                    $this->globalSchema = $schema;
1191 74
                }
1192 74
                $xml = $this->getDOM($this->knownLocationSchemas[$uri]);
1193 74
                $callbacks = array_merge($callbacks, $this->schemaNode($schema, $xml->documentElement));
1194
            }
1195
1196
            $globalSchemas[(string) static::XSD_NS]->addType(new SimpleType($globalSchemas[(string) static::XSD_NS], 'anySimpleType'));
1197 74
            $globalSchemas[(string) static::XSD_NS]->addType(new SimpleType($globalSchemas[(string) static::XSD_NS], 'anyType'));
1198 74
1199 74
            $globalSchemas[(string) static::XML_NS]->addSchema(
1200 74
                $globalSchemas[(string) static::XSD_NS],
1201
                (string) static::XSD_NS
1202 74
            );
1203 74
            $globalSchemas[(string) static::XSD_NS]->addSchema(
1204 74
                $globalSchemas[(string) static::XML_NS],
1205
                (string) static::XML_NS
1206 74
            );
1207 74
1208
            /**
1209
             * @var Closure $callback
1210 74
             */
1211 74
            foreach ($callbacks as $callback) {
1212
                $callback();
1213 74
            }
1214 74
        }
1215 74
1216
        if (!($this->globalSchema instanceof Schema)) {
1217 74
            throw new TypeException('Global schema not discovered');
1218 74
        }
1219 74
1220
        return $this->globalSchema;
1221
    }
1222
1223
    /**
1224
     * @param DOMNode[] $nodes
1225 74
     */
1226 74
    public function readNodes(array $nodes, string $file = null): Schema
1227
    {
1228
        $rootSchema = new Schema();
1229
        $rootSchema->addSchema($this->getGlobalSchema());
1230 74
1231
        if ($file !== null) {
1232
            $this->setLoadedFile($file, $rootSchema);
1233
        }
1234 74
1235
        $all = [];
1236
        foreach ($nodes as $k => $node) {
1237
            if (($node instanceof \DOMElement) && $node->namespaceURI === self::XSD_NS && $node->localName == 'schema') {
1238
                $holderSchema = new Schema();
1239
                $holderSchema->addSchema($this->getGlobalSchema());
1240 2
1241
                $this->setLoadedSchemaFromElement($node, $holderSchema);
1242 2
1243 2
                $rootSchema->addSchema($holderSchema);
1244
1245 2
                $callbacks = $this->schemaNode($holderSchema, $node);
1246 2
                $all = array_merge($callbacks, $all);
1247
            }
1248
        }
1249 2
1250 2
        foreach ($all as $callback) {
1251 2
            call_user_func($callback);
1252 2
        }
1253 2
1254
        return $rootSchema;
1255 2
    }
1256
1257 2
    public function readNode(DOMElement $node, string $file = null): Schema
1258
    {
1259 2
        $rootSchema = new Schema();
1260 2
        $rootSchema->addSchema($this->getGlobalSchema());
1261
1262
        if ($file !== null) {
1263
            $this->setLoadedFile($file, $rootSchema);
1264 2
        }
1265 2
1266
        $this->setLoadedSchemaFromElement($node, $rootSchema);
1267
1268 2
        $callbacks = $this->schemaNode($rootSchema, $node);
1269
1270
        foreach ($callbacks as $callback) {
1271 72
            call_user_func($callback);
1272
        }
1273 72
1274 72
        return $rootSchema;
1275
    }
1276 72
1277 71
    /**
1278
     * @throws IOException
1279
     */
1280 72
    public function readString(string $content, string $file = 'schema.xsd'): Schema
1281
    {
1282 72
        $xml = new DOMDocument('1.0', 'UTF-8');
1283
        libxml_use_internal_errors(true);
1284 72
        if (!@$xml->loadXML($content)) {
1285 66
            throw new IOException("Can't load the schema", 0, $this->extractErrorMessage());
1286
        }
1287
        libxml_use_internal_errors(false);
1288 72
        $xml->documentURI = $file;
1289
1290
        return $this->readNode($xml->documentElement, $file);
1291
    }
1292
1293
    /**
1294 68
     * @throws IOException
1295
     */
1296 68
    public function readFile(string $file): Schema
1297 68
    {
1298 68
        $xml = $this->getDOM($file);
1299 1
1300
        return $this->readNode($xml->documentElement, $file);
1301 67
    }
1302 67
1303
    /**
1304 67
     * @throws IOException
1305
     */
1306
    private function getDOM(string $file): DOMDocument
1307
    {
1308
        $xml = new DOMDocument('1.0', 'UTF-8');
1309
        libxml_use_internal_errors(true);
1310 5
        if (!@$xml->load($file)) {
1311
            libxml_use_internal_errors(false);
1312 5
            throw new IOException("Can't load the file '$file'", 0, $this->extractErrorMessage());
1313
        }
1314 4
        libxml_use_internal_errors(false);
1315
1316
        return $xml;
1317
    }
1318
1319
    private static function againstDOMNodeList(
1320 75
        DOMElement $node,
1321
        Closure $againstNodeList
1322 75
    ): void {
1323 75
        $limit = $node->childNodes->length;
1324 75
        for ($i = 0; $i < $limit; ++$i) {
1325 1
            /**
1326 1
             * @var DOMNode
1327
             */
1328 74
            $childNode = $node->childNodes->item($i);
1329
1330 74
            if ($childNode instanceof DOMElement) {
1331
                $againstNodeList($node, $childNode);
1332
            }
1333 74
        }
1334
    }
1335
1336
    private function loadTypeWithCallback(
1337 74
        Schema $schema,
1338 74
        DOMElement $childNode,
1339
        Closure $callback
1340
    ): void {
1341
        /**
1342 74
         * @var Closure|null $func
1343
         */
1344 74
        $func = null;
1345 74
1346 74
        switch ($childNode->localName) {
1347 74
            case 'complexType':
1348
                $func = $this->loadComplexType($schema, $childNode, $callback);
1349
                break;
1350
            case 'simpleType':
1351 74
                $func = $this->loadSimpleType($schema, $childNode, $callback);
1352
                break;
1353 74
        }
1354
1355
        if ($func instanceof Closure) {
1356
            call_user_func($func);
1357
        }
1358
    }
1359
1360
    private function loadElement(Schema $schema, DOMElement $node): Element
1361 74
    {
1362
        $element = new Element($schema, $node->getAttribute('name'));
1363 74
        $element->setDoc($this->getDocumentation($node));
1364 74
        $this->fillItem($element, $node);
1365 74
        $this->fillElement($element, $node);
1366 74
1367 74
        return $element;
1368 74
    }
1369 74
1370
    private function fillElement(AbstractElementSingle $element, DOMElement $node): void
1371
    {
1372 74
        self::maybeSetMax($element, $node);
1373 74
        self::maybeSetMin($element, $node);
1374
        self::maybeSetFixed($element, $node);
1375 74
        self::maybeSetDefault($element, $node);
1376
1377 74
        $xp = new \DOMXPath($node->ownerDocument);
0 ignored issues
show
Bug introduced by
It seems like $node->ownerDocument can also be of type null; however, parameter $document of DOMXPath::__construct() does only seem to accept DOMDocument, 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

1377
        $xp = new \DOMXPath(/** @scrutinizer ignore-type */ $node->ownerDocument);
Loading history...
1378
        $xp->registerNamespace('xs', self::XSD_NS);
1379
1380
        if ($xp->query('ancestor::xs:choice', $node)->length) {
1381 74
            $element->setMin(0);
1382 74
        }
1383
1384 74
        if ($node->hasAttribute('nillable')) {
1385
            $element->setNil('true' === $node->getAttribute('nillable'));
1386 74
        }
1387 74
        if ($node->hasAttribute('form')) {
1388 74
            $element->setQualified('qualified' === $node->getAttribute('form'));
1389
        }
1390 74
1391 74
        $parentNode = $node->parentNode;
1392
        if ('schema' !== $parentNode->localName || self::XSD_NS !== $parentNode->namespaceURI) {
1393 74
            $element->setLocal(true);
1394 74
        }
1395
    }
1396
1397 74
    private function addAttributeFromAttributeOrRef(
1398 4
        BaseComplexType $type,
1399
        DOMElement $childNode,
1400 74
        Schema $schema,
1401 5
        DOMElement $node
1402
    ): void {
1403
        $attribute = $this->getAttributeFromAttributeOrRef(
1404 74
            $childNode,
1405
            $schema,
1406 74
            $node
1407 74
        );
1408
1409
        $type->addAttribute($attribute);
1410 74
    }
1411
1412
    private function findSomethingLikeAttributeGroup(
1413 74
        Schema $schema,
1414
        DOMElement $node,
1415
        DOMElement $childNode,
1416
        AttributeContainer $addToThis
1417
    ): void {
1418
        $attribute = $this->findAttributeGroup($schema, $node, $childNode->getAttribute('ref'));
1419 74
        $addToThis->addAttribute($attribute);
1420 74
    }
1421 74
1422 74
    private function setLoadedFile(string $key, Schema $schema): void
1423
    {
1424
        $this->loadedFiles[$key] = $schema;
1425 74
    }
1426 74
1427
    private function setLoadedSchemaFromElement(DOMElement $node, Schema $schema): void
1428 74
    {
1429
        if ($node->hasAttribute('targetNamespace')) {
1430
            $this->setLoadedSchema($node->getAttribute('targetNamespace'), $schema);
1431
        }
1432
    }
1433
1434 74
    private function setLoadedSchema(string $namespace, Schema $schema): void
1435 74
    {
1436 74
        if (!isset($this->loadedSchemas[$namespace])) {
1437
            $this->loadedSchemas[$namespace] = [];
1438 74
        }
1439
        if (!in_array($schema, $this->loadedSchemas[$namespace], true)) {
1440 74
            $this->loadedSchemas[$namespace][] = $schema;
1441 74
        }
1442
    }
1443 74
1444
    private function setSchemaThingsFromNode(
1445 74
        Schema $schema,
1446 74
        DOMElement $node,
1447
        Schema $parent = null
1448 74
    ): void {
1449
        $schema->setDoc($this->getDocumentation($node));
1450 74
1451
        if ($node->hasAttribute('targetNamespace')) {
1452 74
            $schema->setTargetNamespace($node->getAttribute('targetNamespace'));
1453 74
        } elseif ($parent instanceof Schema) {
1454
            $schema->setTargetNamespace($parent->getTargetNamespace());
1455 74
        }
1456 74
        $schema->setElementsQualification($node->getAttribute('elementFormDefault') == 'qualified');
1457
        $schema->setAttributesQualification($node->getAttribute('attributeFormDefault') == 'qualified');
1458 74
        $schema->setDoc($this->getDocumentation($node));
1459
    }
1460
}
1461