Completed
Push — master ( e625a1...0d2a97 )
by Veaceslav
02:33
created

UriConstraint   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 176
Duplicated Lines 10.23 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 25
lcom 1
cbo 5
dl 18
loc 176
ccs 78
cts 78
cp 1
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A assertPathSegment() 0 9 2
A assertPathParam() 0 12 1
C matches() 18 74 13
A failureDescription() 0 4 1
A additionalFailureDescription() 0 4 1
A toString() 0 4 1
A normalizeUri() 0 8 1
A normalizeJsonSchema() 0 4 1
A normalizeNumericString() 0 8 2
A splitString() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * This file is part of Rebilly.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @see http://rebilly.com
9
 */
10
11
namespace Rebilly\OpenAPI\PhpUnit;
12
13
use JsonSchema\Entity\JsonPointer;
14
use PHPUnit\Framework\Constraint\Constraint;
15
use Psr\Http\Message\UriInterface;
16
use Rebilly\OpenAPI\JsonSchema\Validator;
17
use Rebilly\OpenAPI\UnexpectedValueException;
18
use stdClass;
19
20
/**
21
 * Constraint that asserts that the URI matches the expected
22
 * allowed schemes, base URI, URI paths and query-params.
23
 */
24
final class UriConstraint extends Constraint
25
{
26
    private $servers;
27
28
    private $path;
29
30
    private $pathParameters;
31
32
    private $queryParameters;
33
34
    private $validator;
35
36
    private $errors = [];
37
38 11
    public function __construct(
39
        array $servers,
40
        string $path,
41
        array $pathParameters,
42
        array $queryParameters
43
    ) {
44 11
        parent::__construct();
45 11
        $this->servers = array_map('strtolower', $servers);
46 11
        $this->path = $path;
47 11
        $this->pathParameters = array_map([$this, 'normalizeJsonSchema'], $pathParameters);
48 11
        $this->queryParameters = array_map([$this, 'normalizeJsonSchema'], $queryParameters);
49 11
        $this->validator = new Validator('undefined');
50
    }
51
52 8
    private function assertPathSegment(string $expectedSegment, string $actualSegment)
53
    {
54 8
        if ($actualSegment !== $expectedSegment) {
55 1
            $this->errors[] = [
56 1
                'property' => 'path',
57 1
                'message' => "Missing path segment ({$expectedSegment})",
58
            ];
59
        }
60
    }
61
62 6
    private function assertPathParam(string $expectedSegment, string $actualSegment)
63
    {
64 6
        $pathParamSchema = $this->pathParameters[substr($expectedSegment, 1, -1)];
65
66
        // TODO: Consider to disallow non-string params in path, that make no sense
67 6
        $actualSegment = $this->normalizeNumericString($actualSegment);
68
69 6
        $this->errors = array_merge(
70 6
            $this->errors,
71 6
            $this->validator->validate($actualSegment, $pathParamSchema, new JsonPointer('#/path'))
72
        );
73
    }
74
75 11
    protected function matches($uri): bool
76
    {
77 11
        if (!$uri instanceof UriInterface) {
78 1
            throw new UnexpectedValueException('The object should implements UriInterface');
79
        }
80
81 10
        $baseUrl = null;
82
83 10
        foreach ($this->servers as $serverUrl) {
84 10
            if (strpos((string) $uri, $serverUrl) === 0) {
85 9
                $baseUrl = $serverUrl;
86
87 10
                continue;
88
            }
89
        }
90
91 10
        if ($baseUrl === null) {
92 1
            $this->errors[] = [
93 1
                'property' => 'baseUrl',
94 1
                'message' => sprintf('Unexpected URL, does not found in defined servers (%s)', implode(', ', $this->servers)),
95
            ];
96
97 1
            return false;
98
        }
99
100 9
        $pathStart = strlen($baseUrl) - strpos($baseUrl, '/', strpos($baseUrl, '://') + 3);
101 9
        $path = substr($uri->getPath(), $pathStart + 1);
102 9
        $actualSegments = $this->splitString('#\/#', $path);
103 9
        $expectedSegments = $this->splitString('#\/#', $this->path);
104
105 9
        if (count($actualSegments) !== count($expectedSegments)) {
106 1
            $this->errors[] = [
107 1
                'property' => 'path',
108 1
                'message' => "Unexpected URI path, does not match the template ({$this->path})",
109
            ];
110
111 1
            return false;
112
        }
113
114 8
        foreach ($expectedSegments as $i => $expectedSegment) {
115 8
            $actualSegment = $actualSegments[$i];
116 8
            strpos($expectedSegment, '{') === false
117 8
                ? $this->assertPathSegment($expectedSegment, $actualSegment)
118 8
                : $this->assertPathParam($expectedSegment, $actualSegment);
119
        }
120
121 8
        if (!empty($this->errors)) {
122 2
            return false;
123
        }
124
125 6
        parse_str($uri->getQuery(), $actualQueryParams);
126
127
        // TODO: Assert query params
128 6 View Code Duplication
        foreach ($this->queryParameters as $name => $queryParamSchema) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129 6
            if (isset($actualQueryParams[$name])) {
130 2
                $actualQueryParam = $actualQueryParams[$name];
131
132
                // TODO: Consider to disallow non-string params in query, that make no sense
133 2
                $actualQueryParam = $this->normalizeNumericString($actualQueryParam);
134
135 2
                $this->errors = array_merge(
136 2
                    $this->errors,
137 2
                    $this->validator->validate($actualQueryParam, $queryParamSchema, new JsonPointer('#/query'))
138
                );
139 4
            } elseif (isset($queryParamSchema->required) && $queryParamSchema->required) {
140 1
                $this->errors[] = [
141 1
                    'property' => 'query',
142 6
                    'message' => "Missing required query param ({$name})",
143
                ];
144
            }
145
        }
146
147 6
        return empty($this->errors);
148
    }
149
150 6
    protected function failureDescription($other): string
151
    {
152 6
        return json_encode((object) $this->normalizeUri($other)) . ' ' . $this->toString();
153
    }
154
155 6
    protected function additionalFailureDescription($other): string
156
    {
157 6
        return $this->validator->serializeErrors($this->errors);
158
    }
159
160 6
    public function toString(): string
161
    {
162 6
        return 'matches an specified URI parts';
163
    }
164
165 6
    private static function normalizeUri(UriInterface $uri): array
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
166
    {
167
        return [
168 6
            'schema' => $uri->getScheme(),
169 6
            'host' => $uri->getHost(),
170 6
            'path' => $uri->getPath(),
171
        ];
172
    }
173
174 11
    private static function normalizeJsonSchema($schema): stdClass
175
    {
176 11
        return (object) $schema;
177
    }
178
179
    /**
180
     * Cast numeric values, JSON validator does not do it.
181
     *
182
     * @param mixed $value
183
     *
184
     * @return mixed
185
     */
186 6
    private static function normalizeNumericString($value)
187
    {
188 6
        if (is_numeric($value)) {
189 4
            $value += 0;
190
        }
191
192 6
        return $value;
193
    }
194
195 9
    private static function splitString(string $pattern, string $subject): array
196
    {
197 9
        return preg_split($pattern, $subject, -1, PREG_SPLIT_NO_EMPTY);
198
    }
199
}
200