Passed
Push — validation ( c1c79f )
by Greg
11:49
created

Validator::optionalTree()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2021 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees;
21
22
use Aura\Router\Route;
23
use Closure;
24
use Fisharebest\Webtrees\Contracts\UserInterface;
25
use Fisharebest\Webtrees\Http\Exceptions\HttpBadRequestException;
26
use LogicException;
27
use Psr\Http\Message\ServerRequestInterface;
28
29
use function array_reduce;
30
use function ctype_digit;
31
use function is_array;
32
use function is_int;
33
use function is_string;
34
use function parse_url;
35
use function preg_match;
36
use function str_starts_with;
37
38
/**
39
 * Validate a parameter from an HTTP request
40
 */
41
class Validator
42
{
43
    /** @var array<string|Tree|UserInterface|array<string>> */
44
    private array $parameters;
45
46
    /** @var array<Closure> */
47
    private array $rules = [];
48
49
    /**
50
     * @param array<string|array<string>> $parameters
51
     */
52
    public function __construct(array $parameters)
53
    {
54
        $this->parameters = $parameters;
55
    }
56
57
    /**
58
     * @param ServerRequestInterface $request
59
     *
60
     * @return self
61
     */
62
    public static function attributes(ServerRequestInterface $request): self
63
    {
64
        return new self($request->getAttributes());
65
    }
66
67
    /**
68
     * @param ServerRequestInterface $request
69
     *
70
     * @return self
71
     */
72
    public static function parsedBody(ServerRequestInterface $request): self
73
    {
74
        return new self((array) $request->getParsedBody());
75
    }
76
77
    /**
78
     * @param ServerRequestInterface $request
79
     *
80
     * @return self
81
     */
82
    public static function queryParams(ServerRequestInterface $request): self
83
    {
84
        return new self($request->getQueryParams());
85
    }
86
87
    /**
88
     * @param int $minimum
89
     * @param int $maximum
90
     *
91
     * @return self
92
     */
93
    public function isBetween(int $minimum, int $maximum): self
94
    {
95
        $this->rules[] = static function (?int $value) use ($minimum, $maximum): ?int {
96
            if (is_int($value) && $value >= $minimum && $value <= $maximum) {
97
                return $value;
98
            }
99
100
            return null;
101
        };
102
103
        return $this;
104
    }
105
106
    /**
107
     * @param array<string> $values
108
     *
109
     * @return $this
110
     */
111
    public function isInArray(array $values): self
112
    {
113
        $this->rules[] = static fn (?string $value): ?string => is_string($value) && in_array($value, $values, true) ? $value : null;
114
115
        return $this;
116
    }
117
    /**
118
     * @param string $base_url
119
     *
120
     * @return $this
121
     */
122
    public function isLocalUrl(string $base_url): self
123
    {
124
        $this->rules[] = static function (?string $value) use ($base_url): ?string {
125
            if (is_string($value)) {
126
                $value_info    = parse_url($value);
127
                $base_url_info = parse_url($base_url);
128
129
                if (!is_array($base_url_info)) {
1 ignored issue
show
introduced by
The condition is_array($base_url_info) is always true.
Loading history...
130
                    throw new LogicException(__METHOD__ . ' needs a valid URL');
131
                }
132
133
                if (is_array($value_info)) {
1 ignored issue
show
introduced by
The condition is_array($value_info) is always true.
Loading history...
134
                    $scheme_ok = ($value_info['scheme'] ?? 'http') === ($base_url_info['scheme'] ?? 'http');
135
                    $host_ok   = ($value_info['host'] ?? '') === ($base_url_info['host'] ?? '');
136
                    $port_ok   = ($value_info['port'] ?? '') === ($base_url_info['port'] ?? '');
137
                    $user_ok   = ($value_info['user'] ?? '') === ($base_url_info['user'] ?? '');
138
                    $path_ok   = str_starts_with($value_info['path'] ?? '/', $base_url_info['path'] ?? '/');
139
140
                    if ($scheme_ok && $host_ok && $port_ok && $user_ok && $path_ok) {
141
                        return $value;
142
                    }
143
                }
144
            }
145
146
            return null;
147
        };
148
149
        return $this;
150
    }
151
152
    /**
153
     * @return $this
154
     */
155
    public function isXref(): self
156
    {
157
        $this->rules[] = static function (?string $value): ?string {
158
            if (is_string($value) && preg_match('/^' . Gedcom::REGEX_XREF . '$/', $value) === 1) {
159
                return $value;
160
            }
161
162
            return null;
163
        };
164
165
        return $this;
166
    }
167
168
    /**
169
     * @param string $parameter
170
     *
171
     * @return array<string>|null
172
     */
173
    public function optionalArray(string $parameter): ?array
174
    {
175
        $value = $this->parameters[$parameter] ?? null;
176
177
        if (!is_array($value)) {
178
            $value = null;
179
        }
180
181
        $callback = static fn (?array $value, Closure $rule): ?array => $rule($value);
182
183
        return array_reduce($this->rules, $callback, $value);
184
    }
185
186
    /**
187
     * @param string $parameter
188
     *
189
     * @return int|null
190
     */
191
    public function optionalInteger(string $parameter): ?int
192
    {
193
        $value = $this->parameters[$parameter] ?? null;
194
195
        if (is_string($value) && ctype_digit($value)) {
196
            $value = (int) $value;
197
        } else {
198
            $value = null;
199
        }
200
201
        $callback = static fn (?int $value, Closure $rule): ?int => $rule($value);
202
203
        return array_reduce($this->rules, $callback, $value);
204
    }
205
206
    /**
207
     * @param string $parameter
208
     *
209
     * @return string|null
210
     */
211
    public function optionalString(string $parameter): ?string
212
    {
213
        $value = $this->parameters[$parameter] ?? null;
214
215
        if (!is_string($value)) {
216
            $value = null;
217
        }
218
219
        $callback = static fn (?string $value, Closure $rule): ?string => $rule($value);
220
221
        return array_reduce($this->rules, $callback, $value);
222
    }
223
224
    /**
225
     * @param string $parameter
226
     *
227
     * @return Tree|null
228
     */
229
    public function optionalTree(string $parameter): ?Tree
230
    {
231
        $value = $this->parameters[$parameter] ?? null;
232
233
        if (!$value instanceof Tree) {
234
            $value = null;
235
        }
236
237
        $callback = static fn (?string $value, Closure $rule): ?Tree => $rule($value);
238
239
        return array_reduce($this->rules, $callback, $value);
240
    }
241
242
    /**
243
     * @param string $parameter
244
     *
245
     * @return UserInterface|null
246
     */
247
    public function optionalUser(string $parameter): ?UserInterface
248
    {
249
        $value = $this->parameters[$parameter] ?? null;
250
251
        if (!$value instanceof UserInterface) {
252
            $value = null;
253
        }
254
255
        $callback = static fn (?string $value, Closure $rule): ?UserInterface => $rule($value);
256
257
        return array_reduce($this->rules, $callback, $value);
258
    }
259
260
    /**
261
     * @param string $parameter
262
     *
263
     * @return array<string>
264
     */
265
    public function requiredArray(string $parameter): array
266
    {
267
        $value = $this->optionalArray($parameter);
268
269
        if ($value === null) {
270
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
271
        }
272
273
        return $value;
274
    }
275
276
    /**
277
     * @param string $parameter
278
     *
279
     * @return int
280
     */
281
    public function requiredInteger(string $parameter): int
282
    {
283
        $value = $this->optionalInteger($parameter);
284
285
        if ($value === null) {
286
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
287
        }
288
289
        return $value;
290
    }
291
292
    /**
293
     * @param string $parameter
294
     *
295
     * @return string
296
     */
297
    public function requiredString(string $parameter): string
298
    {
299
        $value = $this->optionalString($parameter);
300
301
        if ($value === null) {
302
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
303
        }
304
305
        return $value;
306
    }
307
308
    /**
309
     * @param string $parameter
310
     *
311
     * @return Route
312
     */
313
    public function route(string $parameter = 'route'): Route
314
    {
315
        $value = $this->parameters[$parameter] ?? null;
316
317
        if ($value instanceof Route) {
318
            return $value;
319
        }
320
321
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
322
    }
323
324
    /**
325
     * @param string $parameter
326
     *
327
     * @return Tree
328
     */
329
    public function tree(string $parameter = 'tree'): Tree
330
    {
331
        $value = $this->parameters[$parameter] ?? null;
332
333
        if ($value instanceof Tree) {
334
            return $value;
335
        }
336
337
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
338
    }
339
340
    /**
341
     * @param string $parameter
342
     *
343
     * @return UserInterface
344
     */
345
    public function user(string $parameter = 'user'): UserInterface
346
    {
347
        $value = $this->parameters[$parameter] ?? null;
348
349
        if ($value instanceof UserInterface) {
350
            return $value;
351
        }
352
353
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
354
    }
355
}
356