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

QNameValue::validateValue()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 22
rs 9.5222
cc 5
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Type;
6
7
use DOMElement;
8
use SimpleSAML\XML\Assert\Assert;
9
use SimpleSAML\XML\Exception\SchemaViolationException;
10
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\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...
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...
11
12
use function preg_match;
13
14
/**
15
 * @package simplesaml/xml-common
16
 */
17
class QNameValue extends AbstractValueType
18
{
19
    protected ?AnyURIValue $namespaceURI;
20
    protected ?NCNameValue $namespacePrefix;
21
    protected NCNameValue $localName;
22
23
    private static string $qname_regex = '/^
24
        (?:
25
          \{                 # Match a literal {
26
            (\S+)            # Match one or more non-whitespace character
27
          \}                 # Match a literal }
28
          (?:
29
            ([\w_][\w.-]*)   # Match a-z or underscore followed by any word-character, dot or dash
30
            :                # Match a literal :
31
          )?
32
        )?                   # Namespace and prefix are optional
33
        ([\w_][\w.-]*)       # Match a-z or underscore followed by any word-character, dot or dash
34
        $/Dimx';
35
36
37
    /**
38
     * Sanitize the value.
39
     *
40
     * @param string $value  The unsanitized value
41
     * @return string
42
     */
43
    protected function sanitizeValue(string $value): string
44
    {
45
        return static::collapseWhitespace(static::normalizeWhitespace($value));
46
    }
47
48
49
    /**
50
     * Validate the value.
51
     *
52
     * @param string $value
53
     * @throws \SimpleSAML\XML\Exception\SchemaViolationException on failure
54
     * @return void
55
     */
56
    protected function validateValue(string $value): void
57
    {
58
        $qName = $this->sanitizeValue($value);
59
60
        /**
61
         * Split our custom format of {<namespaceURI>}<prefix>:<localName> into individual parts
62
         */
63
        $result = preg_match(
64
            self::$qname_regex,
65
            $qName,
66
            $matches,
67
            PREG_UNMATCHED_AS_NULL,
68
        );
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\XML\Type\AnyURIValue|null
97
     */
98
    public function getNamespaceURI(): ?AnyURIValue
99
    {
100
        return $this->namespaceURI;
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->getValue(), SchemaViolationException::class);
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on null. ( Ignorable by Annotation )

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

139
            Assert::null($namespacePrefix->/** @scrutinizer ignore-call */ getValue(), SchemaViolationException::class);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
140
            return new static($localName->getValue());
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
    ): static {
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