Test Failed
Push — static-analysis ( 74f346...4e0c1f )
by SignpostMarv
02:52
created

SchemaReader::loadImportFresh()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 4
nop 4
dl 0
loc 25
ccs 18
cts 18
cp 1
crap 5
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace GoetasWebservices\XML\XSDReader;
3
4
use Closure;
5
use DOMDocument;
6
use DOMElement;
7
use DOMNode;
8
use GoetasWebservices\XML\XSDReader\Exception\IOException;
9
use GoetasWebservices\XML\XSDReader\Exception\TypeException;
10
use GoetasWebservices\XML\XSDReader\Schema\Attribute\Attribute;
11
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeDef;
12
use GoetasWebservices\XML\XSDReader\Schema\Attribute\AttributeItem;
13
use GoetasWebservices\XML\XSDReader\Schema\Attribute\Group as AttributeGroup;
14
use GoetasWebservices\XML\XSDReader\Schema\Element\Element;
15
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementContainer;
16
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementDef;
17
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementItem;
18
use GoetasWebservices\XML\XSDReader\Schema\Element\ElementRef;
19
use GoetasWebservices\XML\XSDReader\Schema\Element\Group;
20
use GoetasWebservices\XML\XSDReader\Schema\Element\GroupRef;
21
use GoetasWebservices\XML\XSDReader\Schema\Element\InterfaceSetMinMax;
22
use GoetasWebservices\XML\XSDReader\Schema\Exception\TypeNotFoundException;
23
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Base;
24
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Extension;
25
use GoetasWebservices\XML\XSDReader\Schema\Inheritance\Restriction;
26
use GoetasWebservices\XML\XSDReader\Schema\Item;
27
use GoetasWebservices\XML\XSDReader\Schema\Schema;
28
use GoetasWebservices\XML\XSDReader\Schema\SchemaItem;
29
use GoetasWebservices\XML\XSDReader\Schema\Type\BaseComplexType;
30
use GoetasWebservices\XML\XSDReader\Schema\Type\ComplexType;
31
use GoetasWebservices\XML\XSDReader\Schema\Type\ComplexTypeSimpleContent;
32
use GoetasWebservices\XML\XSDReader\Schema\Type\SimpleType;
33
use GoetasWebservices\XML\XSDReader\Schema\Type\Type;
34
use GoetasWebservices\XML\XSDReader\Utils\UrlUtils;
35
use RuntimeException;
36
37
class SchemaReader
38
{
39
40
    const XSD_NS = "http://www.w3.org/2001/XMLSchema";
41
42
    const XML_NS = "http://www.w3.org/XML/1998/namespace";
43
44
    /**
45
    * @var string[]
46
    */
47
    private $knownLocationSchemas = [
48
        'http://www.w3.org/2001/xml.xsd' => (
49
            __DIR__ . '/Resources/xml.xsd'
50
        ),
51
        'http://www.w3.org/2001/XMLSchema.xsd' => (
52
            __DIR__ . '/Resources/XMLSchema.xsd'
53
        ),
54
        'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' => (
55
            __DIR__ . '/Resources/oasis-200401-wss-wssecurity-secext-1.0.xsd'
56
        ),
57
        'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' => (
58
            __DIR__ . '/Resources/oasis-200401-wss-wssecurity-utility-1.0.xsd'
59
        ),
60
        'https://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd' => (
61
            __DIR__ . '/Resources/xmldsig-core-schema.xsd'
62
        ),
63
        'http://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd' => (
64
            __DIR__ . '/Resources/xmldsig-core-schema.xsd'
65
        ),
66
    ];
67
68
    /**
69
    * @var string[]
70
    */
71
    private static $globalSchemaInfo = array(
72
        self::XML_NS => 'http://www.w3.org/2001/xml.xsd',
73
        self::XSD_NS => 'http://www.w3.org/2001/XMLSchema.xsd'
74
    );
75
76 162
    public function __construct()
77
    {
78 162
    }
79
80
    /**
81
    * @param string $remote
82
    * @param string $local
83
    */
84
    public function addKnownSchemaLocation($remote, $local)
85
    {
86
        $this->knownLocationSchemas[$remote] = $local;
87
    }
88
89
    /**
90
    * @return Closure
91
    */
92 135
    private function loadAttributeGroup(Schema $schema, DOMElement $node)
93 1
    {
94 135
        return AttributeGroup::loadAttributeGroup($this, $schema, $node);
95
    }
96
97
    /**
98
    * @param bool $attributeDef
99
    *
100
    * @return Closure
101
    */
102 135
    private function loadAttributeOrElementDef(
103
        Schema $schema,
104
        DOMElement $node,
105
        $attributeDef
106
    ) {
107 135
        $name = $node->getAttribute('name');
108 135
        if ($attributeDef) {
109 135
            $attribute = new AttributeDef($schema, $name);
110 135
            $schema->addAttribute($attribute);
111 45
        } else {
112 135
            $attribute = new ElementDef($schema, $name);
113 135
            $schema->addElement($attribute);
114
        }
115
116
117
        return function () use ($attribute, $node) {
118 135
            $this->fillItem($attribute, $node);
119 135
        };
120
    }
121
122
    /**
123
    * @return Closure
124
    */
125 135
    private function loadAttributeDef(Schema $schema, DOMElement $node)
126
    {
127 135
        return $this->loadAttributeOrElementDef($schema, $node, true);
128
    }
129
130
    /**
131
     * @param DOMElement $node
132
     * @return string
133
     */
134 135
    public static function getDocumentation(DOMElement $node)
135
    {
136 135
        $doc = '';
137 135
        foreach ($node->childNodes as $childNode) {
138 135
            if ($childNode->localName == "annotation") {
139 135
                $doc .= static::getDocumentation($childNode);
140 135
            } elseif ($childNode->localName == 'documentation') {
141 135
                $doc .= ($childNode->nodeValue);
142 45
            }
143 45
        }
144 135
        $doc = preg_replace('/[\t ]+/', ' ', $doc);
145 135
        return trim($doc);
146
    }
147
148 135
    private function setSchemaThingsFromNode(
149
        Schema $schema,
150
        DOMElement $node,
151
        Schema $parent = null
152
    ) {
153 135
        $schema->setDoc(static::getDocumentation($node));
154
155 135
        if ($node->hasAttribute("targetNamespace")) {
156 135
            $schema->setTargetNamespace($node->getAttribute("targetNamespace"));
157 45
        } elseif ($parent) {
158
            $schema->setTargetNamespace($parent->getTargetNamespace());
159
        }
160 135
        $schema->setElementsQualification($node->getAttribute("elementFormDefault") == "qualified");
161 135
        $schema->setAttributesQualification($node->getAttribute("attributeFormDefault") == "qualified");
162 135
        $schema->setDoc(static::getDocumentation($node));
163 135
    }
164
165
    /**
166
    * @param string $key
167
    *
168
    * @return Closure|null
169
    */
170 135
    public function maybeCallMethod(
171
        array $methods,
172
        $key,
173
        DOMNode $childNode,
174
        ...$args
175
    ) {
176 135
        if ($childNode instanceof DOMElement && isset($methods[$key])) {
177 135
            $method = $methods[$key];
178
179 135
            $append = $this->$method(...$args);
180
181 135
            if ($append instanceof Closure) {
182 135
                return $append;
183
            }
184 45
        }
185 135
    }
186
187
    /**
188
     *
189
     * @param Schema $schema
190
     * @param DOMElement $node
191
     * @param Schema $parent
192
     * @return Closure[]
193
     */
194 135
    private function schemaNode(Schema $schema, DOMElement $node, Schema $parent = null)
195
    {
196 135
        $this->setSchemaThingsFromNode($schema, $node, $parent);
197 135
        $functions = array();
198
199 90
        static $methods = [
200
            'include' => 'loadImport',
201
            'import' => 'loadImport',
202
            'element' => 'loadElementDef',
203
            'attribute' => 'loadAttributeDef',
204
            'attributeGroup' => 'loadAttributeGroup',
205
            'group' => 'loadGroup',
206
            'complexType' => 'loadComplexType',
207
            'simpleType' => 'loadSimpleType',
208 45
        ];
209
210 135
        foreach ($node->childNodes as $childNode) {
211 135
            $callback = $this->maybeCallMethod(
212 135
                $methods,
213 135
                (string) $childNode->localName,
214 135
                $childNode,
215 135
                $schema,
216 90
                $childNode
217 45
            );
218
219 135
            if ($callback instanceof Closure) {
220 135
                $functions[] = $callback;
221 45
            }
222 45
        }
223
224 135
        return $functions;
225
    }
226
227
    /**
228
    * @return InterfaceSetMinMax
229
    */
230 135
    public static function maybeSetMax(InterfaceSetMinMax $ref, DOMElement $node)
231
    {
232
        if (
233 135
            $node->hasAttribute("maxOccurs")
234 45
        ) {
235 135
            $ref->setMax($node->getAttribute("maxOccurs") == "unbounded" ? -1 : (int)$node->getAttribute("maxOccurs"));
236 45
        }
237
238 135
        return $ref;
239
    }
240
241
    /**
242
    * @return InterfaceSetMinMax
243
    */
244 135
    public static function maybeSetMin(InterfaceSetMinMax $ref, DOMElement $node)
245
    {
246 135
        if ($node->hasAttribute("minOccurs")) {
247 135
            $ref->setMin((int) $node->getAttribute("minOccurs"));
248 45
        }
249
250 135
        return $ref;
251
    }
252
253
    /**
254
    * @param int|null $max
255
    *
256
    * @return int|null
257
    */
258 135
    private static function loadSequenceNormaliseMax(DOMElement $node, $max)
259
    {
260
        return
261
        (
262 135
            (is_int($max) && (bool) $max) ||
263 135
            $node->getAttribute("maxOccurs") == "unbounded" ||
264 135
            $node->getAttribute("maxOccurs") > 1
265 45
        )
266 90
            ? 2
267 135
            : null;
268
    }
269
270
    /**
271
    * @param int|null $max
272
    */
273 135
    private function loadSequence(ElementContainer $elementContainer, DOMElement $node, $max = null)
274
    {
275 135
        $max = static::loadSequenceNormaliseMax($node, $max);
276
277 135
        foreach ($node->childNodes as $childNode) {
278 135
            if ($childNode instanceof DOMElement) {
279 135
                $this->loadSequenceChildNode(
280 135
                    $elementContainer,
281 135
                    $node,
282 135
                    $childNode,
283 90
                    $max
284 45
                );
285 45
            }
286 45
        }
287 135
    }
288
289
    /**
290
    * @param int|null $max
291
    */
292 135
    private function loadSequenceChildNode(
293
        ElementContainer $elementContainer,
294
        DOMElement $node,
295
        DOMElement $childNode,
296
        $max
297
    ) {
298
        $loadSeq = $this->makeLoadSequenceChildNodeLoadSequence(
299 135
            $elementContainer,
300 135
            $childNode,
301
            $max
302 135
        );
303 135
        $methods = [
304 135
            'choice' => $loadSeq,
305
            'sequence' => $loadSeq,
306 135
            'all' => $loadSeq,
307 135
            'element' => $this->makeLoadSequenceChildNodeLoadElement(
308 135
                $elementContainer,
309 135
                $node,
310
                $childNode,
311 135
                $max
312
            ),
313
            'group' => $this->makeLoadSequenceChildNodeLoadGroup(
314
                $elementContainer,
315 135
                $node,
316 135
                $childNode
317 135
            ),
318 90
        ];
319 45
320 45
        if (isset($methods[$childNode->localName])) {
321 135
            $method = $methods[$childNode->localName];
322 135
            $method();
323 135
        }
324 90
    }
325 45
326
    /**
327 135
    * @param int|null $max
328 135
    */
329 45
    private function makeLoadSequenceChildNodeLoadSequence(
330 135
        ElementContainer $elementContainer,
331 135
        DOMElement $childNode,
332
        $max
333 135
    ) : Closure {
334 135
        return function () use ($elementContainer, $childNode, $max) {
335 135
            $this->loadSequence($elementContainer, $childNode, $max);
336
        };
337 135
    }
338 135
339 135
    /**
340 135
    * @param int|null $max
341 90
    */
342 45
    private function makeLoadSequenceChildNodeLoadElement(
343 135
        ElementContainer $elementContainer,
344 45
        DOMElement $node,
345
        DOMElement $childNode,
346 135
        $max
347 135
    ) : Closure {
348 135
        return function () use (
349 45
                $elementContainer,
350 135
                $node,
351
                $childNode,
352 135
                $max
353
            ) {
354
                if ($childNode->hasAttribute("ref")) {
355
                    /**
356
                    * @var ElementDef $referencedElement
357
                    */
358
                    $referencedElement = $this->findSomething('findElement', $elementContainer->getSchema(), $node, $childNode->getAttribute("ref"));
359
                    $element = ElementRef::loadElementRef(
360
                        $referencedElement,
361 135
                        $childNode
362 135
                    );
363 135
                } else {
364 135
                    $element = Element::loadElement(
365 135
                        $this,
366 45
                        $elementContainer->getSchema(),
367
                        $childNode
368 135
                    );
369 135
                }
370 135
                if (is_int($max) && (bool) $max) {
371
                    $element->setMax($max);
372 135
                }
373
                $elementContainer->addElement($element);
374
        };
375
    }
376 135
377
    private function makeLoadSequenceChildNodeLoadGroup(
378
        ElementContainer $elementContainer,
379
        DOMElement $node,
380
        DOMElement $childNode
381
    ) : Closure {
382
        return function () use (
383
                $elementContainer,
384
                $node,
385
                $childNode
386
            ) {
387 135
                $this->addGroupAsElement(
388 135
                    $elementContainer->getSchema(),
389
                    $node,
390
                    $childNode,
391
                    $elementContainer
392
                );
393 135
        };
394
    }
395 135
396
    private function addGroupAsElement(
397
        Schema $schema,
398
        DOMElement $node,
399
        DOMElement $childNode,
400
        ElementContainer $elementContainer
401
    ) {
402
        /**
403 135
        * @var Group $referencedGroup
404
        */
405 135
        $referencedGroup = $this->findSomething(
406
            'findGroup',
407 135
            $schema,
408 135
            $node,
409 6
            $childNode->getAttribute("ref")
410 49
        );
411
412 45
        $group = GroupRef::loadGroupRef($referencedGroup, $childNode);
413
        $elementContainer->addElement($group);
414 135
    }
415
416 135
    private function maybeLoadSequenceFromElementContainer(
417 135
        BaseComplexType $type,
418 135
        DOMElement $childNode
419 45
    ) {
420
        if (! ($type instanceof ElementContainer)) {
421 135
            throw new RuntimeException(
422 135
                '$type passed to ' .
423 135
                __FUNCTION__ .
424
                'expected to be an instance of ' .
425
                ElementContainer::class .
426
                ' when child node localName is "group", ' .
427
                get_class($type) .
428 135
                ' given.'
429 135
            );
430
        }
431 135
        $this->loadSequence($type, $childNode);
432 135
    }
433 135
434 135
    /**
435 90
    * @return Closure
436 45
    */
437 135
    private function loadGroup(Schema $schema, DOMElement $node)
438 90
    {
439 45
        return Group::loadGroup($this, $schema, $node);
440
    }
441
442
    /**
443
    * @param Closure|null $callback
444
    *
445
    * @return Closure
446
    */
447 135
    private function loadComplexType(Schema $schema, DOMElement $node, $callback = null)
448
    {
449
        $isSimple = false;
450
451
        foreach ($node->childNodes as $childNode) {
452
            if ($childNode->localName === "simpleContent") {
453
                $isSimple = true;
454
                break;
455 135
            }
456 135
        }
457 135
458 135
        $type = $isSimple ? new ComplexTypeSimpleContent($schema, $node->getAttribute("name")) : new ComplexType($schema, $node->getAttribute("name"));
459
460 135
        $type->setDoc(static::getDocumentation($node));
461 135
        if ($node->getAttribute("name")) {
462 135
            $schema->addType($type);
463 135
        }
464 90
465 45
        return $this->makeCallbackCallback(
466 135
            $type,
467
            $node,
468
                function (
469
                    DOMElement $node,
470
                    DOMElement $childNode
471
                ) use(
472 135
                    $schema,
473
                    $type
474
                ) {
475
                    $this->loadComplexTypeFromChildNode(
476
                        $type,
477
                        $node,
478 135
                        $childNode,
479
                        $schema
480 135
                    );
481 135
                },
482 135
            $callback
483 135
        );
484 90
    }
485 45
486 45
    /**
487 45
    * @param Closure|null $callback
488
    *
489 135
    * @return Closure
490 135
    */
491 45
    private function makeCallbackCallback(
492 135
        Type $type,
493
        DOMElement $node,
494 135
        Closure $callbackCallback,
495
        $callback = null
496
    ) {
497
        return function (
498
        ) use (
499
            $type,
500
            $node,
501 135
            $callbackCallback,
502 135
            $callback
503 90
        ) {
504 45
            $this->runCallbackAgainstDOMNodeList(
505 135
                $type,
506
                $node,
507 135
                $callbackCallback,
508 135
                $callback
509 135
            );
510
        };
511 135
    }
512 135
513 135
    /**
514 135
    * @param Closure|null $callback
515
    */
516 135
    private function runCallbackAgainstDOMNodeList(
517 135
        Type $type,
518 135
        DOMElement $node,
519 135
        Closure $againstNodeList,
520 90
        $callback = null
521 45
    ) {
522
        $this->fillTypeNode($type, $node, true);
523 135
524 135
        foreach ($node->childNodes as $childNode) {
525
            if ($childNode instanceof DOMElement) {
526 6
                $againstNodeList(
527 6
                    $node,
528 6
                    $childNode
529 6
                );
530
            }
531 6
        }
532 6
533 6
        if ($callback) {
534 6
            call_user_func($callback, $type);
535 6
        }
536 4
    }
537 2
538 135
    private function loadComplexTypeFromChildNode(
539 45
        BaseComplexType $type,
540
        DOMElement $node,
541 90
        DOMElement $childNode,
542 45
        Schema $schema
543
    ) {
544 3
        $maybeLoadSeq = function () use ($type, $childNode) {
545 3
            $this->maybeLoadSequenceFromElementContainer(
546 3
                $type,
547 3
                $childNode
548
            );
549 3
        };
550 3
        $methods = [
551 3
            'sequence' => $maybeLoadSeq,
552 3
            'choice' => $maybeLoadSeq,
553 2
            'all' => $maybeLoadSeq,
554 1
            'attribute' => function () use (
555 3
                $childNode,
556 45
                $schema,
557
                $node,
558 135
                $type
559 135
            ) {
560 135
                $attribute = Attribute::getAttributeFromAttributeOrRef(
561 45
                    $this,
562 135
                    $childNode,
563
                    $schema,
564
                    $node
565
                );
566
567
                $type->addAttribute($attribute);
568
            },
569 135
            'attributeGroup' => function() use (
570
                $schema,
571 135
                $node,
572 135
                $childNode,
573 135
                $type
574 135
            ) {
575 45
                AttributeGroup::findSomethingLikeThis(
576
                    $this,
577 90
                    $schema,
578
                    $node,
579
                    $childNode,
580 45
                    $type
581
                );
582 135
            },
583 135
        ];
584 135
        if (
585
            $type instanceof ComplexType
586
        ) {
587
            $methods['group'] = function() use (
588
                $schema,
589 135
                $node,
590 135
                $childNode,
591
                $type
592 135
            ) {
593 135
                $this->addGroupAsElement(
594 135
                    $schema,
595 135
                    $node,
596 135
                    $childNode,
597 90
                    $type
598 45
                );
599 135
            };
600 90
        }
601 45
602
        if (isset($methods[$childNode->localName])) {
603
            $method = $methods[$childNode->localName];
604 135
            $method();
605
        }
606 135
    }
607
608
    /**
609
    * @param Closure|null $callback
610 135
    *
611 135
    * @return Closure
612 45
    */
613
    private function loadSimpleType(Schema $schema, DOMElement $node, $callback = null)
614 135
    {
615 135
        $type = new SimpleType($schema, $node->getAttribute("name"));
616
        $type->setDoc(static::getDocumentation($node));
617 135
        if ($node->getAttribute("name")) {
618 135
            $schema->addType($type);
619 135
        }
620 135
621 90
        static $methods = [
622 45
            'union' => 'loadUnion',
623
            'list' => 'loadList',
624 135
        ];
625
626
        return $this->makeCallbackCallback(
627
            $type,
628
            $node,
629
            function (
630
                DOMElement $node,
631 135
                DOMElement $childNode
632
            ) use (
633
                $methods,
634
                $type
635
            ) {
636 135
                $this->maybeCallMethod(
637 135
                    $methods,
638 135
                    $childNode->localName,
639 135
                    $childNode,
640 45
                    $type,
641
                    $childNode
642
                );
643
            },
644
            $callback
645
        );
646
    }
647
648 135
    private function loadList(SimpleType $type, DOMElement $node)
649
    {
650
        if ($node->hasAttribute("itemType")) {
651
            /**
652
            * @var SimpleType $listType
653
            */
654
            $listType = $this->findSomeType($type, $node, 'itemType');
655
            $type->setList($listType);
656 135
        } else {
657 135
            $addCallback = function (SimpleType $list) use ($type) {
658 135
                $type->setList($list);
659 135
            };
660 90
661 45
            Type::loadTypeWithCallbackOnChildNodes(
662
                $this,
663 135
                $type->getSchema(),
664
                $node,
665
                $addCallback
666 135
            );
667
        }
668 135
    }
669 135
670 135
    /**
671
    * @param string $attributeName
672
    *
673
    * @return SchemaItem
674 135
    */
675 135
    private function findSomeType(
676 135
        SchemaItem $fromThis,
677 90
        DOMElement $node,
678 45
        $attributeName
679 135
    ) {
680 45
        return $this->findSomeTypeFromAttribute(
681 45
            $fromThis,
682
            $node,
683 135
            $node->getAttribute($attributeName)
684 135
        );
685
    }
686 135
687 135
    /**
688 135
    * @param string $attributeName
689 135
    *
690 90
    * @return SchemaItem
691 45
    */
692 135
    private function findSomeTypeFromAttribute(
693
        SchemaItem $fromThis,
694
        DOMElement $node,
695
        $attributeName
696
    ) {
697 135
        /**
698
        * @var SchemaItem $out
699
        */
700 135
        $out = $this->findSomething(
701 135
            'findType',
702 45
            $fromThis->getSchema(),
703
            $node,
704 90
            $attributeName
705
        );
706
707
        return $out;
708
    }
709 45
710
    private function loadUnion(SimpleType $type, DOMElement $node)
711 135
    {
712 135
        if ($node->hasAttribute("memberTypes")) {
713 135
            $types = preg_split('/\s+/', $node->getAttribute("memberTypes"));
714 135
            foreach ($types as $typeName) {
715 135
                /**
716 135
                * @var SimpleType $unionType
717 90
                */
718 45
                $unionType = $this->findSomeTypeFromAttribute(
719 45
                    $type,
720 135
                    $node,
721
                    $typeName
722 135
                );
723
                $type->addUnion($unionType);
724 135
            }
725 135
        }
726
        $addCallback = function (SimpleType $unType) use ($type) {
727 135
            $type->addUnion($unType);
728 135
        };
729 135
730 135
        Type::loadTypeWithCallbackOnChildNodes(
731 90
            $this,
732 45
            $type->getSchema(),
733 45
            $node,
734
            $addCallback
735
        );
736 135
    }
737 135
738 90
    /**
739 45
    * @param bool $checkAbstract
740 135
    */
741
    private function fillTypeNode(Type $type, DOMElement $node, $checkAbstract = false)
742
    {
743 135
744 135
        if ($checkAbstract) {
745 135
            $type->setAbstract($node->getAttribute("abstract") === "true" || $node->getAttribute("abstract") === "1");
746
        }
747
748
        static $methods = [
749 135
            'restriction' => 'loadRestriction',
750 135
            'extension' => 'maybeLoadExtensionFromBaseComplexType',
751
            'simpleContent' => 'fillTypeNode',
752 135
            'complexContent' => 'fillTypeNode',
753 135
        ];
754 135
755 135
        foreach ($node->childNodes as $childNode) {
756 90
            $this->maybeCallMethod(
757 45
                $methods,
758 135
                (string) $childNode->localName,
759 135
                $childNode,
760
                $type,
761
                $childNode
762
            );
763 135
        }
764 135
    }
765
766 135
    private function loadExtension(BaseComplexType $type, DOMElement $node)
767 135
    {
768 135
        $extension = new Extension();
769 135
        $type->setExtension($extension);
770 135
771 90
        if ($node->hasAttribute("base")) {
772 45
            $this->findAndSetSomeBase(
773 135
                $type,
774 45
                $extension,
775
                $node
776 135
            );
777 135
        }
778 135
779 135
        $seqFromElement = function (DOMElement $childNode) use ($type) {
780 45
            $this->maybeLoadSequenceFromElementContainer(
781 45
                $type,
782 135
                $childNode
783
            );
784 135
        };
785
786
        $methods = [
787
            'sequence' => $seqFromElement,
788
            'choice' => $seqFromElement,
789
            'all' => $seqFromElement,
790
            'attribute' => function (
791
                DOMElement $childNode
792 135
            ) use (
793 135
                $node,
794 135
                $type
795
            ) {
796 135
                $attribute = Attribute::getAttributeFromAttributeOrRef(
797
                    $this,
798
                    $childNode,
799
                    $type->getSchema(),
800 135
                    $node
801
                );
802
                $type->addAttribute($attribute);
803
            },
804
            'attributeGroup' => function (
805
                DOMElement $childNode
806
            ) use (
807
                $node,
808
                $type
809
            ) {
810
                AttributeGroup::findSomethingLikeThis(
811
                    $this,
812
                    $type->getSchema(),
813 135
                    $node,
814 135
                    $childNode,
815
                    $type
816 135
                );
817
            },
818 135
        ];
819 135
820
        foreach ($node->childNodes as $childNode) {
821
            if (isset($methods[$childNode->localName])) {
822
                $method = $methods[$childNode->localName];
823
                $method($childNode);
824
            }
825
        }
826 135
    }
827
828 135
    public function findAndSetSomeBase(
829 135
        Type $type,
830 135
        Base $setBaseOnThis,
831 135
        DOMElement $node
832 45
    ) {
833
        /**
834 135
        * @var Type $parent
835
        */
836 135
        $parent = $this->findSomeType($type, $node, 'base');
837 135
        $setBaseOnThis->setBase($parent);
838 90
    }
839 45
840
    private function maybeLoadExtensionFromBaseComplexType(
841
        Type $type,
842
        DOMElement $childNode
843
    ) {
844
        if (! ($type instanceof BaseComplexType)) {
845
            throw new RuntimeException(
846
                'Argument 1 passed to ' .
847
                __METHOD__ .
848
                ' needs to be an instance of ' .
849
                BaseComplexType::class .
850
                ' when passed onto ' .
851 135
                static::class .
852
                '::loadExtension(), ' .
853 135
                get_class($type) .
854
                ' given.'
855 135
            );
856
        }
857
        $this->loadExtension($type, $childNode);
858 135
    }
859
860
    private function loadRestriction(Type $type, DOMElement $node)
861
    {
862
        Restriction::loadRestriction($this, $type, $node);
863
    }
864
865
    /**
866
    * @param string $typeName
867 135
    *
868
    * @return mixed[]
869 135
    */
870
    private static function splitParts(DOMElement $node, $typeName)
871
    {
872 135
        $prefix = null;
873
        $name = $typeName;
874 135
        if (strpos($typeName, ':') !== false) {
875
            list ($prefix, $name) = explode(':', $typeName);
876 135
        }
877 135
878
        $namespace = $node->lookupNamespaceUri($prefix ?: '');
879 135
        return array(
880 45
            $name,
881
            $namespace,
882 45
            $prefix
883 45
        );
884 135
    }
885 135
886 135
    /**
887 135
     *
888
     * @param string $finder
889 135
     * @param Schema $schema
890 135
     * @param DOMElement $node
891 45
     * @param string $typeName
892 135
     * @throws TypeException
893
     * @return ElementItem|Group|AttributeItem|AttributeGroup|Type
894 45
     */
895
    public function findSomething($finder, Schema $schema, DOMElement $node, $typeName)
896 135
    {
897 135
        list ($name, $namespace) = self::splitParts($node, $typeName);
898
899 135
        $namespace = $namespace ?: $schema->getTargetNamespace();
900
901 135
        try {
902
            return $schema->$finder($name, $namespace);
903
        } catch (TypeNotFoundException $e) {
904
            throw new TypeException(sprintf("Can't find %s named {%s}#%s, at line %d in %s ", strtolower(substr($finder, 4)), $namespace, $name, $node->getLineNo(), $node->ownerDocument->documentURI), 0, $e);
905 135
        }
906 45
    }
907
908
    /**
909
    * @return Closure
910 135
    */
911 135
    private function loadElementDef(Schema $schema, DOMElement $node)
912 135
    {
913 135
        return $this->loadAttributeOrElementDef($schema, $node, false);
914 45
    }
915
916
    public function fillItem(Item $element, DOMElement $node)
917 135
    {
918 135
        foreach ($node->childNodes as $childNode) {
919
            if (
920
                in_array(
921
                    $childNode->localName,
922
                    [
923 135
                        'complexType',
924
                        'simpleType',
925 135
                    ]
926 135
                )
927
            ) {
928 135
                Type::loadTypeWithCallback(
929
                    $this,
930
                    $element->getSchema(),
931
                    $childNode,
932 135
                    function (Type $type) use ($element) {
933 135
                        $element->setType($type);
934 135
                    }
935 45
                );
936 45
                return;
937 9
            }
938 9
        }
939 9
940 6
        $this->fillItemNonLocalType($element, $node);
941 3
    }
942 3
943 47
    private function fillItemNonLocalType(Item $element, DOMElement $node)
944 45
    {
945 135
        if ($node->getAttribute("type")) {
946
            /**
947
            * @var Type $type
948 135
            */
949
            $type = $this->findSomeType($element, $node, 'type');
950
        } else {
951 3
            /**
952
            * @var Type $type
953
            */
954
            $type = $this->findSomeTypeFromAttribute(
955
                $element,
956
                $node,
957
                ($node->lookupPrefix(self::XSD_NS) . ':anyType')
958
            );
959
        }
960 3
961
        $element->setType($type);
962
    }
963
964
    /**
965
    * @return Closure
966 3
    */
967 3
    private function loadImport(Schema $schema, DOMElement $node)
968 1
    {
969
        $base = urldecode($node->ownerDocument->documentURI);
970
        $file = UrlUtils::resolveRelativeUrl($base, $node->getAttribute("schemaLocation"));
971
972
        $namespace = $node->getAttribute("namespace");
973 3
974
        if (
975 3
            (
976
                isset(self::$globalSchemaInfo[$namespace]) &&
977 3
                Schema::hasLoadedFile(
978
                    $loadedFilesKey = self::$globalSchemaInfo[$namespace]
979
                )
980
            ) ||
981
            Schema::hasLoadedFile(
982 3
                $loadedFilesKey = $this->getNamespaceSpecificFileIndex(
983 3
                    $file,
984 3
                    $namespace
985 1
                )
986 3
            ) ||
987
            Schema::hasLoadedFile($loadedFilesKey = $file)
988
        ) {
989
            $schema->addSchema(Schema::getLoadedFile($loadedFilesKey));
990
991
            return function() {
992
            };
993
        }
994
995
        return $this->loadImportFresh($schema, $node, $file, $namespace);
996
    }
997
998 135
    /**
999
    * @param string $file
1000 135
    * @param string $namespace
1001 135
    *
1002 135
    * @return Closure
1003 135
    */
1004 135
    private function loadImportFresh(
1005 135
        Schema $schema,
1006 135
        DOMElement $node,
1007 45
        $file,
1008 135
        $namespace
1009 135
    ) {
1010 45
        if (! $namespace) {
1011 135
            $newSchema = Schema::setLoadedFile($file, $schema);
1012 135
        } else {
1013 45
            $newSchema = Schema::setLoadedFile($file, new Schema());
1014
            $newSchema->addSchema($this->getGlobalSchema());
1015 135
        }
1016 135
1017
        $xml = $this->getDOM(isset($this->knownLocationSchemas[$file]) ? $this->knownLocationSchemas[$file] : $file);
1018 135
1019 135
        $callbacks = $this->schemaNode($newSchema, $xml->documentElement, $schema);
1020
1021 135
        if ($namespace) {
1022 135
            $schema->addSchema($newSchema);
1023 45
        }
1024 45
1025
1026
        return function () use ($callbacks) {
1027
            foreach ($callbacks as $callback) {
1028
                $callback();
1029 135
            }
1030
        };
1031 135
    }
1032
1033
    /**
1034
    * @var Schema|null
1035
    */
1036
    private $globalSchema;
1037
1038
    /**
1039
     *
1040 135
     * @return Schema
1041
     */
1042 135
    public function getGlobalSchema()
1043 135
    {
1044
        if (!$this->globalSchema) {
1045 135
            $callbacks = array();
1046 135
            $globalSchemas = array();
1047
            foreach (self::$globalSchemaInfo as $namespace => $uri) {
1048 135
                Schema::setLoadedFile(
1049 117
                    $uri,
1050 45
                    $globalSchemas[$namespace] = $schema = new Schema()
1051
                );
1052 135
                if ($namespace === self::XSD_NS) {
1053
                    $this->globalSchema = $schema;
1054
                }
1055
                $xml = $this->getDOM($this->knownLocationSchemas[$uri]);
1056
                $callbacks = array_merge($callbacks, $this->schemaNode($schema, $xml->documentElement));
1057
            }
1058
1059
            $globalSchemas[self::XSD_NS]->addType(new SimpleType($globalSchemas[self::XSD_NS], "anySimpleType"));
1060
            $globalSchemas[self::XSD_NS]->addType(new SimpleType($globalSchemas[self::XSD_NS], "anyType"));
1061
1062
            $globalSchemas[self::XML_NS]->addSchema($globalSchemas[self::XSD_NS], self::XSD_NS);
1063
            $globalSchemas[self::XSD_NS]->addSchema($globalSchemas[self::XML_NS], self::XML_NS);
1064
1065
            foreach ($callbacks as $callback) {
1066 135
                $callback();
1067
            }
1068 135
        }
1069
1070
        /**
1071
        * @var Schema $out
1072
        */
1073
        $out = $this->globalSchema;
1074
1075
        return $out;
1076
    }
1077
1078
    /**
1079 132
     * @param DOMElement $node
1080
     * @param string  $file
1081 132
     *
1082 132
     * @return Schema
1083
     */
1084
    public function readNode(DOMElement $node, $file = 'schema.xsd')
1085 132
    {
1086
        $fileKey = $node->hasAttribute('targetNamespace') ? $this->getNamespaceSpecificFileIndex($file, $node->getAttribute('targetNamespace')) : $file;
1087 132
        Schema::setLoadedFile($fileKey, $rootSchema = new Schema());
1088
1089
        $rootSchema->addSchema($this->getGlobalSchema());
1090
        $callbacks = $this->schemaNode($rootSchema, $node);
1091
1092
        foreach ($callbacks as $callback) {
1093
            call_user_func($callback);
1094
        }
1095 3
1096
        return $rootSchema;
1097 3
    }
1098 3
1099
    /**
1100
     * It is possible that a single file contains multiple <xsd:schema/> nodes, for instance in a WSDL file.
1101
     *
1102
     * Each of these  <xsd:schema/> nodes typically target a specific namespace. Append the target namespace to the
1103
     * file to distinguish between multiple schemas in a single file.
1104
     *
1105
     * @param string $file
1106
     * @param string $targetNamespace
1107
     *
1108 135
     * @return string
1109
     */
1110 135
    private function getNamespaceSpecificFileIndex($file, $targetNamespace)
1111 135
    {
1112
        return $file . '#' . $targetNamespace;
1113
    }
1114 135
1115
    /**
1116
     * @param string $content
1117
     * @param string $file
1118
     *
1119
     * @return Schema
1120
     *
1121
     * @throws IOException
1122
     */
1123
    public function readString($content, $file = 'schema.xsd')
1124
    {
1125
        $xml = new DOMDocument('1.0', 'UTF-8');
1126
        if (!$xml->loadXML($content)) {
1127
            throw new IOException("Can't load the schema");
1128
        }
1129
        $xml->documentURI = $file;
1130
1131
        return $this->readNode($xml->documentElement, $file);
1132
    }
1133
1134
    /**
1135
     * @param string $file
1136
     *
1137
     * @return Schema
1138
     */
1139
    public function readFile($file)
1140
    {
1141
        $xml = $this->getDOM($file);
1142
        return $this->readNode($xml->documentElement, $file);
1143
    }
1144
1145
    /**
1146
     * @param string $file
1147
     *
1148
     * @return DOMDocument
1149
     *
1150
     * @throws IOException
1151
     */
1152
    private function getDOM($file)
1153
    {
1154
        $xml = new DOMDocument('1.0', 'UTF-8');
1155
        if (!$xml->load($file)) {
1156
            throw new IOException("Can't load the file $file");
1157
        }
1158
        return $xml;
1159
    }
1160
}
1161