Passed
Push — static-analysis ( 40ab55...7ed12d )
by SignpostMarv
05:41
created

maybeLoadSequenceFromElementContainer()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.5388

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 3
cts 11
cp 0.2727
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 1
nop 2
crap 3.5388
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 = [
299 135
            [$this, 'loadSequenceChildNodeLoadSequence'],
300
            [
301 135
                $elementContainer,
302 135
                $childNode,
303 90
                $max
304 45
            ]
305 45
        ];
306
        $methods = [
307 135
            'choice' => $loadSeq,
308 135
            'sequence' => $loadSeq,
309 135
            'all' => $loadSeq,
310
            'element' => [
311 135
                [$this, 'loadSequenceChildNodeLoadElement'],
312
                [
313 135
                    $elementContainer,
314 135
                    $node,
315 135
                    $childNode,
316 90
                    $max
317 45
                ]
318 45
            ],
319
            'group' => [
320 135
                [$this, 'loadSequenceChildNodeLoadGroup'],
321
                [
322 135
                    $elementContainer,
323 135
                    $node,
324 90
                    $childNode
325 45
                ]
326 45
            ],
327 45
        ];
328
329 135
        $this->maybeCallCallableWithArgs($childNode, $methods);
330 135
    }
331
332
    /**
333
    * @param mixed[][] $methods
334
    *
335
    * @return mixed
336
    */
337 135
    private function maybeCallCallableWithArgs(
338
        DOMElement $childNode,
339
        array $methods
340
    ) {
341 135
        if (isset($methods[$childNode->localName])) {
342 135
            list ($callable, $args) = $methods[$childNode->localName];
343
344 135
            return call_user_func_array($callable, $args);
345
        }
346 135
    }
347
348
    /**
349
    * @param int|null $max
350
    */
351 135
    private function loadSequenceChildNodeLoadSequence(
352
        ElementContainer $elementContainer,
353
        DOMElement $childNode,
354
        $max
355
    ) {
356 135
        $this->loadSequence($elementContainer, $childNode, $max);
357 135
    }
358
359
    /**
360
    * @param int|null $max
361
    */
362 135
    private function loadSequenceChildNodeLoadElement(
363
        ElementContainer $elementContainer,
364
        DOMElement $node,
365
        DOMElement $childNode,
366
        $max
367
    ) {
368 135
        if ($childNode->hasAttribute("ref")) {
369
            /**
370
            * @var ElementDef $referencedElement
371
            */
372 135
            $referencedElement = $this->findSomething('findElement', $elementContainer->getSchema(), $node, $childNode->getAttribute("ref"));
373 135
            $element = ElementRef::loadElementRef(
374 135
                $referencedElement,
375 90
                $childNode
376 45
            );
377 45
        } else {
378 135
            $element = Element::loadElement(
379 135
                $this,
380 135
                $elementContainer->getSchema(),
381 90
                $childNode
382 45
            );
383
        }
384 135
        if (is_int($max) && (bool) $max) {
385 135
            $element->setMax($max);
386 45
        }
387 135
        $elementContainer->addElement($element);
388 135
    }
389
390 135
    private function loadSequenceChildNodeLoadGroup(
391
        ElementContainer $elementContainer,
392
        DOMElement $node,
393
        DOMElement $childNode
394
    ) {
395 135
        $this->addGroupAsElement(
396 135
            $elementContainer->getSchema(),
397 135
            $node,
398 135
            $childNode,
399 90
            $elementContainer
400 45
        );
401 135
    }
402
403 135
    private function addGroupAsElement(
404
        Schema $schema,
405
        DOMElement $node,
406
        DOMElement $childNode,
407
        ElementContainer $elementContainer
408
    ) {
409
        /**
410
        * @var Group $referencedGroup
411
        */
412 135
        $referencedGroup = $this->findSomething(
413 135
            'findGroup',
414 135
            $schema,
415 135
            $node,
416 135
            $childNode->getAttribute("ref")
417 45
        );
418
419 135
        $group = GroupRef::loadGroupRef($referencedGroup, $childNode);
420 135
        $elementContainer->addElement($group);
421 135
    }
422
423 135
    private function maybeLoadSequenceFromElementContainer(
424
        BaseComplexType $type,
425
        DOMElement $childNode
426
    ) {
427 135
        if (! ($type instanceof ElementContainer)) {
428
            throw new RuntimeException(
429
                '$type passed to ' .
430
                __FUNCTION__ .
431
                'expected to be an instance of ' .
432
                ElementContainer::class .
433
                ' when child node localName is "group", ' .
434
                get_class($type) .
435
                ' given.'
436
            );
437
        }
438 135
        $this->loadSequence($type, $childNode);
439 135
    }
440
441
    /**
442
    * @return Closure
443
    */
444 135
    private function loadGroup(Schema $schema, DOMElement $node)
445
    {
446 135
        return Group::loadGroup($this, $schema, $node);
447
    }
448
449
    /**
450
    * @param Closure|null $callback
451
    *
452
    * @return Closure
453
    */
454 135
    private function loadComplexType(Schema $schema, DOMElement $node, $callback = null)
455
    {
456 135
        $isSimple = false;
457
458 135
        foreach ($node->childNodes as $childNode) {
459 135
            if ($childNode->localName === "simpleContent") {
460 6
                $isSimple = true;
461 49
                break;
462
            }
463 45
        }
464
465 135
        $type = $isSimple ? new ComplexTypeSimpleContent($schema, $node->getAttribute("name")) : new ComplexType($schema, $node->getAttribute("name"));
466
467 135
        $type->setDoc(static::getDocumentation($node));
468 135
        if ($node->getAttribute("name")) {
469 135
            $schema->addType($type);
470 45
        }
471
472 135
        return $this->makeCallbackCallback(
473 135
            $type,
474 135
            $node,
475
                function (
476
                    DOMElement $node,
477
                    DOMElement $childNode
478
                ) use(
479 135
                    $schema,
480 135
                    $type
481
                ) {
482 135
                    $this->loadComplexTypeFromChildNode(
483 135
                        $type,
484 135
                        $node,
485 135
                        $childNode,
486 90
                        $schema
487 45
                    );
488 135
                },
489 90
            $callback
490 45
        );
491
    }
492
493
    /**
494
    * @param Closure|null $callback
495
    *
496
    * @return Closure
497
    */
498 135
    private function makeCallbackCallback(
499
        Type $type,
500
        DOMElement $node,
501
        Closure $callbackCallback,
502
        $callback = null
503
    ) {
504
        return function (
505
        ) use (
506 135
            $type,
507 135
            $node,
508 135
            $callbackCallback,
509 135
            $callback
510
        ) {
511 135
            $this->runCallbackAgainstDOMNodeList(
512 135
                $type,
513 135
                $node,
514 135
                $callbackCallback,
515 90
                $callback
516 45
            );
517 135
        };
518
    }
519
520
    /**
521
    * @param Closure|null $callback
522
    */
523 135
    private function runCallbackAgainstDOMNodeList(
524
        Type $type,
525
        DOMElement $node,
526
        Closure $againstNodeList,
527
        $callback = null
528
    ) {
529 135
        $this->fillTypeNode($type, $node, true);
530
531 135
        foreach ($node->childNodes as $childNode) {
532 135
            if ($childNode instanceof DOMElement) {
533 135
                $againstNodeList(
534 135
                    $node,
535 90
                    $childNode
536 45
                );
537 45
            }
538 45
        }
539
540 135
        if ($callback) {
541 135
            call_user_func($callback, $type);
542 45
        }
543 135
    }
544
545 135
    private function loadComplexTypeFromChildNode(
546
        BaseComplexType $type,
547
        DOMElement $node,
548
        DOMElement $childNode,
549
        Schema $schema
550
    ) {
551
        $maybeLoadSeq = [
552 135
            [$this, 'maybeLoadSequenceFromElementContainer'],
553
            [
554 135
                $type,
555 90
                $childNode
556 45
            ]
557 45
        ];
558
        $methods = [
559 135
            'sequence' => $maybeLoadSeq,
560 135
            'choice' => $maybeLoadSeq,
561 135
            'all' => $maybeLoadSeq,
562
            'attribute' => [
563 135
                [$type, 'addAttributeFromAttributeOrRef'],
564
                [
565 135
                    $this,
566 135
                    $childNode,
567 135
                    $schema,
568 90
                    $node
569 45
                ]
570 45
            ],
571
            'attributeGroup' => [
572 45
                (AttributeGroup::class . '::findSomethingLikeThis'),
573
                [
574 135
                    $this,
575 135
                    $schema,
576 135
                    $node,
577 135
                    $childNode,
578 90
                    $type
579 45
                ]
580 45
            ],
581 45
        ];
582
        if (
583 90
            $type instanceof ComplexType
584 45
        ) {
585 135
            $methods['group'] = [
586 135
                [$this, 'addGroupAsElement'],
587
                [
588 135
                    $schema,
589 135
                    $node,
590 135
                    $childNode,
591 90
                    $type
592 45
                ]
593 45
            ];
594 45
        }
595
596 135
        $this->maybeCallCallableWithArgs($childNode, $methods);
597 135
    }
598
599
    /**
600
    * @param Closure|null $callback
601
    *
602
    * @return Closure
603
    */
604 135
    private function loadSimpleType(Schema $schema, DOMElement $node, $callback = null)
605
    {
606 135
        $type = new SimpleType($schema, $node->getAttribute("name"));
607 135
        $type->setDoc(static::getDocumentation($node));
608 135
        if ($node->getAttribute("name")) {
609 135
            $schema->addType($type);
610 45
        }
611
612 90
        static $methods = [
613
            'union' => 'loadUnion',
614
            'list' => 'loadList',
615 45
        ];
616
617 135
        return $this->makeCallbackCallback(
618 135
            $type,
619 135
            $node,
620
            function (
621
                DOMElement $node,
622
                DOMElement $childNode
623
            ) use (
624 135
                $methods,
625 135
                $type
626
            ) {
627 135
                $this->maybeCallMethod(
628 135
                    $methods,
629 135
                    $childNode->localName,
630 135
                    $childNode,
631 135
                    $type,
632 90
                    $childNode
633 45
                );
634 135
            },
635 90
            $callback
636 45
        );
637
    }
638
639 135
    private function loadList(SimpleType $type, DOMElement $node)
640
    {
641 135
        if ($node->hasAttribute("itemType")) {
642
            /**
643
            * @var SimpleType $listType
644
            */
645 135
            $listType = $this->findSomeType($type, $node, 'itemType');
646 135
            $type->setList($listType);
647 45
        } else {
648
            $addCallback = function (SimpleType $list) use ($type) {
649 135
                $type->setList($list);
650 135
            };
651
652 135
            Type::loadTypeWithCallbackOnChildNodes(
653 135
                $this,
654 135
                $type->getSchema(),
655 135
                $node,
656 90
                $addCallback
657 45
            );
658
        }
659 135
    }
660
661
    /**
662
    * @param string $attributeName
663
    *
664
    * @return SchemaItem
665
    */
666 135
    private function findSomeType(
667
        SchemaItem $fromThis,
668
        DOMElement $node,
669
        $attributeName
670
    ) {
671 135
        return $this->findSomeTypeFromAttribute(
672 135
            $fromThis,
673 135
            $node,
674 135
            $node->getAttribute($attributeName)
675 45
        );
676
    }
677
678
    /**
679
    * @param string $attributeName
680
    *
681
    * @return SchemaItem
682
    */
683 135
    private function findSomeTypeFromAttribute(
684
        SchemaItem $fromThis,
685
        DOMElement $node,
686
        $attributeName
687
    ) {
688
        /**
689
        * @var SchemaItem $out
690
        */
691 135
        $out = $this->findSomething(
692 135
            'findType',
693 135
            $fromThis->getSchema(),
694 135
            $node,
695 90
            $attributeName
696 45
        );
697
698 135
        return $out;
699
    }
700
701 135
    private function loadUnion(SimpleType $type, DOMElement $node)
702
    {
703 135
        if ($node->hasAttribute("memberTypes")) {
704 135
            $types = preg_split('/\s+/', $node->getAttribute("memberTypes"));
705 135
            foreach ($types as $typeName) {
706
                /**
707
                * @var SimpleType $unionType
708
                */
709 135
                $unionType = $this->findSomeTypeFromAttribute(
710 135
                    $type,
711 135
                    $node,
712 90
                    $typeName
713 45
                );
714 135
                $type->addUnion($unionType);
715 45
            }
716 45
        }
717
        $addCallback = function (SimpleType $unType) use ($type) {
718 135
            $type->addUnion($unType);
719 135
        };
720
721 135
        Type::loadTypeWithCallbackOnChildNodes(
722 135
            $this,
723 135
            $type->getSchema(),
724 135
            $node,
725 90
            $addCallback
726 45
        );
727 135
    }
728
729
    /**
730
    * @param bool $checkAbstract
731
    */
732 135
    private function fillTypeNode(Type $type, DOMElement $node, $checkAbstract = false)
733
    {
734
735 135
        if ($checkAbstract) {
736 135
            $type->setAbstract($node->getAttribute("abstract") === "true" || $node->getAttribute("abstract") === "1");
737 45
        }
738
739 90
        static $methods = [
740
            'restriction' => 'loadRestriction',
741
            'extension' => 'maybeLoadExtensionFromBaseComplexType',
742
            'simpleContent' => 'fillTypeNode',
743
            'complexContent' => 'fillTypeNode',
744 45
        ];
745
746 135
        foreach ($node->childNodes as $childNode) {
747 135
            $this->maybeCallMethod(
748 135
                $methods,
749 135
                (string) $childNode->localName,
750 135
                $childNode,
751 135
                $type,
752 90
                $childNode
753 45
            );
754 45
        }
755 135
    }
756
757
    /**
758
    * @return mixed[][]
759
    */
760 135
    private function loadExtensionMakeMethods(
761
        BaseComplexType $type,
762
        DOMElement $node,
763
        DOMElement $childNode
764
    ) {
765
        $seqFromElement = [
766 135
            [$this, 'maybeLoadSequenceFromElementContainer'],
767
            [
768 135
                $type,
769 90
                $childNode
770 45
            ]
771 45
        ];
772
773
        $methods = [
774 135
            'sequence' => $seqFromElement,
775 135
            'choice' => $seqFromElement,
776 135
            'all' => $seqFromElement,
777
            'attribute' => [
778 135
                [$type, 'addAttributeFromAttributeOrRef'],
779
                [
780 135
                    $this,
781 135
                    $childNode,
782 135
                    $type->getSchema(),
783 90
                    $node
784 45
                ]
785 45
            ],
786
            'attributeGroup' => [
787 45
                (AttributeGroup::class . '::findSomethingLikeThis'),
788
                [
789 135
                    $this,
790 135
                    $type->getSchema(),
791 135
                    $node,
792 135
                    $childNode,
793 90
                    $type
794 45
                ]
795 45
            ],
796 45
        ];
797
798 135
        return $methods;
799
    }
800
801 135
    private function loadExtension(BaseComplexType $type, DOMElement $node)
802
    {
803 135
        $extension = new Extension();
804 135
        $type->setExtension($extension);
805
806 135
        if ($node->hasAttribute("base")) {
807 135
            $this->findAndSetSomeBase(
808 135
                $type,
809 135
                $extension,
810 90
                $node
811 45
            );
812 45
        }
813
814 135
        foreach ($node->childNodes as $childNode) {
815 135
            if ($childNode instanceof DOMElement) {
816 135
                $methods = $this->loadExtensionMakeMethods(
817 135
                    $type,
818 135
                    $node,
819 90
                    $childNode
820 45
                );
821 135
                $this->maybeCallCallableWithArgs($childNode, $methods);
822 45
            }
823 45
        }
824 135
    }
825
826 135
    public function findAndSetSomeBase(
827
        Type $type,
828
        Base $setBaseOnThis,
829
        DOMElement $node
830
    ) {
831
        /**
832
        * @var Type $parent
833
        */
834 135
        $parent = $this->findSomeType($type, $node, 'base');
835 135
        $setBaseOnThis->setBase($parent);
836 135
    }
837
838 135
    private function maybeLoadExtensionFromBaseComplexType(
839
        Type $type,
840
        DOMElement $childNode
841
    ) {
842 135
        if (! ($type instanceof BaseComplexType)) {
843
            throw new RuntimeException(
844
                'Argument 1 passed to ' .
845
                __METHOD__ .
846
                ' needs to be an instance of ' .
847
                BaseComplexType::class .
848
                ' when passed onto ' .
849
                static::class .
850
                '::loadExtension(), ' .
851
                get_class($type) .
852
                ' given.'
853
            );
854
        }
855 135
        $this->loadExtension($type, $childNode);
856 135
    }
857
858 135
    private function loadRestriction(Type $type, DOMElement $node)
859
    {
860 135
        Restriction::loadRestriction($this, $type, $node);
861 135
    }
862
863
    /**
864
    * @param string $typeName
865
    *
866
    * @return mixed[]
867
    */
868 135
    private static function splitParts(DOMElement $node, $typeName)
869
    {
870 135
        $prefix = null;
871 135
        $name = $typeName;
872 135
        if (strpos($typeName, ':') !== false) {
873 135
            list ($prefix, $name) = explode(':', $typeName);
874 45
        }
875
876 135
        $namespace = $node->lookupNamespaceUri($prefix ?: '');
877
        return array(
878 135
            $name,
879 135
            $namespace,
880 90
            $prefix
881 45
        );
882
    }
883
884
    /**
885
     *
886
     * @param string $finder
887
     * @param Schema $schema
888
     * @param DOMElement $node
889
     * @param string $typeName
890
     * @throws TypeException
891
     * @return ElementItem|Group|AttributeItem|AttributeGroup|Type
892
     */
893 135
    public function findSomething($finder, Schema $schema, DOMElement $node, $typeName)
894
    {
895 135
        list ($name, $namespace) = self::splitParts($node, $typeName);
896
897 135
        $namespace = $namespace ?: $schema->getTargetNamespace();
898
899
        try {
900 135
            return $schema->$finder($name, $namespace);
901
        } catch (TypeNotFoundException $e) {
902
            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);
903
        }
904
    }
905
906
    /**
907
    * @return Closure
908
    */
909 135
    private function loadElementDef(Schema $schema, DOMElement $node)
910
    {
911 135
        return $this->loadAttributeOrElementDef($schema, $node, false);
912
    }
913
914 135
    public function fillItem(Item $element, DOMElement $node)
915
    {
916 135
        foreach ($node->childNodes as $childNode) {
917
            if (
918 135
                in_array(
919 135
                    $childNode->localName,
920
                    [
921 135
                        'complexType',
922 45
                        'simpleType',
923
                    ]
924 45
                )
925 45
            ) {
926 135
                Type::loadTypeWithCallback(
927 135
                    $this,
928 135
                    $element->getSchema(),
929 135
                    $childNode,
930
                    function (Type $type) use ($element) {
931 135
                        $element->setType($type);
932 135
                    }
933 45
                );
934 135
                return;
935
            }
936 45
        }
937
938 135
        $this->fillItemNonLocalType($element, $node);
939 135
    }
940
941 135
    private function fillItemNonLocalType(Item $element, DOMElement $node)
942
    {
943 135
        if ($node->getAttribute("type")) {
944
            /**
945
            * @var Type $type
946
            */
947 135
            $type = $this->findSomeType($element, $node, 'type');
948 45
        } else {
949
            /**
950
            * @var Type $type
951
            */
952 135
            $type = $this->findSomeTypeFromAttribute(
953 135
                $element,
954 135
                $node,
955 135
                ($node->lookupPrefix(self::XSD_NS) . ':anyType')
956 45
            );
957
        }
958
959 135
        $element->setType($type);
960 135
    }
961
962
    /**
963
    * @return Closure
964
    */
965 135
    private function loadImport(Schema $schema, DOMElement $node)
966
    {
967 135
        $base = urldecode($node->ownerDocument->documentURI);
968 135
        $file = UrlUtils::resolveRelativeUrl($base, $node->getAttribute("schemaLocation"));
969
970 135
        $namespace = $node->getAttribute("namespace");
971
972
        if (
973
            (
974 135
                isset(self::$globalSchemaInfo[$namespace]) &&
975 135
                Schema::hasLoadedFile(
976 135
                    $loadedFilesKey = self::$globalSchemaInfo[$namespace]
977 45
                )
978 45
            ) ||
979 9
            Schema::hasLoadedFile(
980 9
                $loadedFilesKey = $this->getNamespaceSpecificFileIndex(
981 9
                    $file,
982 6
                    $namespace
983 3
                )
984 3
            ) ||
985 47
            Schema::hasLoadedFile($loadedFilesKey = $file)
986 45
        ) {
987 135
            $schema->addSchema(Schema::getLoadedFile($loadedFilesKey));
988
989
            return function() {
990 135
            };
991
        }
992
993 3
        return $this->loadImportFresh($schema, $node, $file, $namespace);
994
    }
995
996
    /**
997
    * @param string $file
998
    * @param string $namespace
999
    *
1000
    * @return Closure
1001
    */
1002 3
    private function loadImportFresh(
1003
        Schema $schema,
1004
        DOMElement $node,
1005
        $file,
1006
        $namespace
1007
    ) {
1008 3
        if (! $namespace) {
1009 3
            $newSchema = Schema::setLoadedFile($file, $schema);
1010 1
        } else {
1011
            $newSchema = Schema::setLoadedFile($file, new Schema());
1012
            $newSchema->addSchema($this->getGlobalSchema());
1013
        }
1014
1015 3
        $xml = $this->getDOM(isset($this->knownLocationSchemas[$file]) ? $this->knownLocationSchemas[$file] : $file);
1016
1017 3
        $callbacks = $this->schemaNode($newSchema, $xml->documentElement, $schema);
1018
1019 3
        if ($namespace) {
1020
            $schema->addSchema($newSchema);
1021
        }
1022
1023
1024 3
        return function () use ($callbacks) {
1025 3
            foreach ($callbacks as $callback) {
1026 3
                $callback();
1027 1
            }
1028 3
        };
1029
    }
1030
1031
    /**
1032
    * @var Schema|null
1033
    */
1034
    private $globalSchema;
1035
1036
    /**
1037
     *
1038
     * @return Schema
1039
     */
1040 135
    public function getGlobalSchema()
1041
    {
1042 135
        if (!$this->globalSchema) {
1043 135
            $callbacks = array();
1044 135
            $globalSchemas = array();
1045 135
            foreach (self::$globalSchemaInfo as $namespace => $uri) {
1046 135
                Schema::setLoadedFile(
1047 135
                    $uri,
1048 135
                    $globalSchemas[$namespace] = $schema = new Schema()
1049 45
                );
1050 135
                if ($namespace === self::XSD_NS) {
1051 135
                    $this->globalSchema = $schema;
1052 45
                }
1053 135
                $xml = $this->getDOM($this->knownLocationSchemas[$uri]);
1054 135
                $callbacks = array_merge($callbacks, $this->schemaNode($schema, $xml->documentElement));
1055 45
            }
1056
1057 135
            $globalSchemas[self::XSD_NS]->addType(new SimpleType($globalSchemas[self::XSD_NS], "anySimpleType"));
1058 135
            $globalSchemas[self::XSD_NS]->addType(new SimpleType($globalSchemas[self::XSD_NS], "anyType"));
1059
1060 135
            $globalSchemas[self::XML_NS]->addSchema($globalSchemas[self::XSD_NS], self::XSD_NS);
1061 135
            $globalSchemas[self::XSD_NS]->addSchema($globalSchemas[self::XML_NS], self::XML_NS);
1062
1063 135
            foreach ($callbacks as $callback) {
1064 135
                $callback();
1065 45
            }
1066 45
        }
1067
1068
        /**
1069
        * @var Schema $out
1070
        */
1071 135
        $out = $this->globalSchema;
1072
1073 135
        return $out;
1074
    }
1075
1076
    /**
1077
     * @param DOMElement $node
1078
     * @param string  $file
1079
     *
1080
     * @return Schema
1081
     */
1082 135
    public function readNode(DOMElement $node, $file = 'schema.xsd')
1083
    {
1084 135
        $fileKey = $node->hasAttribute('targetNamespace') ? $this->getNamespaceSpecificFileIndex($file, $node->getAttribute('targetNamespace')) : $file;
1085 135
        Schema::setLoadedFile($fileKey, $rootSchema = new Schema());
1086
1087 135
        $rootSchema->addSchema($this->getGlobalSchema());
1088 135
        $callbacks = $this->schemaNode($rootSchema, $node);
1089
1090 135
        foreach ($callbacks as $callback) {
1091 117
            call_user_func($callback);
1092 45
        }
1093
1094 135
        return $rootSchema;
1095
    }
1096
1097
    /**
1098
     * It is possible that a single file contains multiple <xsd:schema/> nodes, for instance in a WSDL file.
1099
     *
1100
     * Each of these  <xsd:schema/> nodes typically target a specific namespace. Append the target namespace to the
1101
     * file to distinguish between multiple schemas in a single file.
1102
     *
1103
     * @param string $file
1104
     * @param string $targetNamespace
1105
     *
1106
     * @return string
1107
     */
1108 135
    private function getNamespaceSpecificFileIndex($file, $targetNamespace)
1109
    {
1110 135
        return $file . '#' . $targetNamespace;
1111
    }
1112
1113
    /**
1114
     * @param string $content
1115
     * @param string $file
1116
     *
1117
     * @return Schema
1118
     *
1119
     * @throws IOException
1120
     */
1121 132
    public function readString($content, $file = 'schema.xsd')
1122
    {
1123 132
        $xml = new DOMDocument('1.0', 'UTF-8');
1124 132
        if (!$xml->loadXML($content)) {
1125
            throw new IOException("Can't load the schema");
1126
        }
1127 132
        $xml->documentURI = $file;
1128
1129 132
        return $this->readNode($xml->documentElement, $file);
1130
    }
1131
1132
    /**
1133
     * @param string $file
1134
     *
1135
     * @return Schema
1136
     */
1137 3
    public function readFile($file)
1138
    {
1139 3
        $xml = $this->getDOM($file);
1140 3
        return $this->readNode($xml->documentElement, $file);
1141
    }
1142
1143
    /**
1144
     * @param string $file
1145
     *
1146
     * @return DOMDocument
1147
     *
1148
     * @throws IOException
1149
     */
1150 135
    private function getDOM($file)
1151
    {
1152 135
        $xml = new DOMDocument('1.0', 'UTF-8');
1153 135
        if (!$xml->load($file)) {
1154
            throw new IOException("Can't load the file $file");
1155
        }
1156 135
        return $xml;
1157
    }
1158
}
1159