Passed
Pull Request — master (#55)
by Tim
01:56
created

QNameValue::fromParts()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 15
rs 10
cc 3
nc 2
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Type;
6
7
use DOMElement;
8
use PREG_UNMATCHED_AS_NULL;
0 ignored issues
show
Bug introduced by
The type PREG_UNMATCHED_AS_NULL was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use SimpleSAML\XML\Assert\Assert;
10
use SimpleSAML\XML\Exception\SchemaViolationException;
11
use SimpleSAML\XML\Type\{AnyURIValue, NCNameValue};
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, SimpleSAML\XML\Type\AnyURIValue. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
Bug introduced by
This use statement conflicts with another class in this namespace, SimpleSAML\XML\Type\NCNameValue. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
13
use function preg_match;
14
15
/**
16
 * @package simplesaml/xml-common
17
 */
18
class QNameValue extends AbstractValueType
19
{
20
    protected ?AnyURIValue $namespaceURI;
21
    protected ?NCNameValue $namespacePrefix;
22
    protected NCNameValue $localName;
23
24
    private static string $qname_regex = '/^
25
        (?:
26
          \{                 # Match a literal {
27
            (\S+)            # Match one or more non-whitespace character
28
          \}                 # Match a literal }
29
          (?:
30
            ([\w_][\w.-]*)   # Match a-z or underscore followed by any word-character, dot or dash
31
            :                # Match a literal :
32
          )?
33
        )?                   # Namespace and prefix are optional
34
        ([\w_][\w.-]*)       # Match a-z or underscore followed by any word-character, dot or dash
35
        $/Dimx';
36
37
38
    /**
39
     * Sanitize the value.
40
     *
41
     * @param string $value  The unsanitized value
42
     * @return string
43
     */
44
    protected function sanitizeValue(string $value): string
45
    {
46
        return static::collapseWhitespace(static::normalizeWhitespace($value));
47
    }
48
49
50
    /**
51
     * Validate the value.
52
     *
53
     * @param string $value
54
     * @throws \SimpleSAML\XML\Exception\SchemaViolationException on failure
55
     * @return void
56
     */
57
    protected function validateValue(string $value): void
58
    {
59
        $qName = $this->sanitizeValue($value);
60
61
        /**
62
         * Split our custom format of {<namespaceURI>}<prefix>:<localName> into individual parts
63
         */
64
        $result = preg_match(
65
            self::$qname_regex,
66
            $qName,
67
            $matches,
68
            PREG_UNMATCHED_AS_NULL,
69
        );
70
        if ($result && count($matches) === 4) {
71
            list($qName, $namespaceURI, $namespacePrefix, $localName) = $matches;
72
73
            $this->namespaceURI = ($namespaceURI !== null) ? AnyURIValue::fromString($namespaceURI) : null;
74
            $this->namespacePrefix = ($namespacePrefix !== null) ? NCNameValue::fromString($namespacePrefix) : null;
75
            $this->localName = NCNameValue::fromString($localName);
76
        } else {
77
            throw new SchemaViolationException(sprintf('\'%s\' is not a valid xs:QName.', $qName));
78
        }
79
    }
80
81
82
    /**
83
     * Get the value.
84
     *
85
     * @return string
86
     */
87
    public function getValue(): string
88
    {
89
        return $this->getNamespacePrefix() . ':' . $this->getLocalName();
90
    }
91
92
93
    /**
94
     * Get the namespaceURI for this qualified name.
95
     *
96
     * @return \SimpleSAML\SAML11\Type\AnyURIValue|null
0 ignored issues
show
Bug introduced by
The type SimpleSAML\SAML11\Type\AnyURIValue was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
97
     */
98
    public function getNamespaceURI(): ?AnyURIValue
99
    {
100
        return $this->namespaceURI;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->namespaceURI also could return the type SimpleSAML\XML\Type\AnyURIValue which is incompatible with the documented return type SimpleSAML\SAML11\Type\AnyURIValue|null.
Loading history...
101
    }
102
103
104
    /**
105
     * Get the namespace-prefix for this qualified name.
106
     *
107
     * @return \SimpleSAML\XML\Type\NCNameValue|null
108
     */
109
    public function getNamespacePrefix(): ?NCNameValue
110
    {
111
        return $this->namespacePrefix;
112
    }
113
114
115
    /**
116
     * Get the local name for this qualified name.
117
     *
118
     * @return \SimpleSAML\XML\Type\NCNameValue
119
     */
120
    public function getLocalName(): NCNameValue
121
    {
122
        return $this->localName;
123
    }
124
125
126
    /**
127
     * @param \SimpleSAML\XML\Type\NCNameValue $localName
128
     * @param \SimpleSAML\XML\Type\AnyURIValue|null $namespaceURI
129
     * @param \SimpleSAML\XML\Type\NCNameValue|null $namespacePrefix
130
     * @return static
131
     */
132
    public static function fromParts(
133
        NCNameValue $localName,
134
        ?AnyURIValue $namespaceURI,
135
        ?NCNameValue $namespacePrefix,
136
    ): static {
137
        if ($namespaceURI === null) {
138
            // If we don't have a namespace, we can't have a prefix either
139
            Assert::null($namespacePrefix, SchemaViolationException::class);
140
            return new static($localName);
141
        }
142
143
        return new static(
144
            '{' . $namespaceURI->getValue() . '}'
145
            . ($namespacePrefix ? ($namespacePrefix->getValue() . ':') : '')
146
            . $localName,
147
        );
148
    }
149
150
151
    /**
152
     * @param string $qname
153
     */
154
    public static function fromDocument(
155
        string $qName,
156
        DOMElement $element,
157
    ) {
158
        $namespacePrefix = null;
159
        if (str_contains($qName, ':')) {
160
            list($namespacePrefix, $localName) = explode(':', $qName, 2);
161
        } else {
162
            // No prefix
163
            $localName = $qName;
164
        }
165
166
        // Will return the default namespace (if any) when prefix is NULL
167
        $namespaceURI = $element->lookupNamespaceUri($namespacePrefix);
168
169
        return new static('{' . $namespaceURI . '}' . $namespacePrefix . ':' . $localName);
170
    }
171
}
172