Passed
Push — validation ( c1c79f...1c78f5 )
by Greg
06:07 queued 11s
created

Validator::array()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
nc 4
nop 2
dl 0
loc 19
rs 9.9332
c 1
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 isTag(): self
156
    {
157
        $this->rules[] = static function (?string $value): ?string {
158
            if (is_string($value) && preg_match('/^' . Gedcom::REGEX_TAG . '$/', $value) === 1) {
159
                return $value;
160
            }
161
162
            return null;
163
        };
164
165
        return $this;
166
    }
167
168
    /**
169
     * @return $this
170
     */
171
    public function isXref(): self
172
    {
173
        $this->rules[] = static function (?string $value): ?string {
174
            if (is_string($value) && preg_match('/^' . Gedcom::REGEX_XREF . '$/', $value) === 1) {
175
                return $value;
176
            }
177
178
            return null;
179
        };
180
181
        return $this;
182
    }
183
184
    /**
185
     * @param string $parameter
186
     *
187
     * @return array<string>|null
188
     */
189
    public function optionalArray(string $parameter): ?array
190
    {
191
        $value = $this->parameters[$parameter] ?? null;
192
193
        if (!is_array($value)) {
194
            $value = null;
195
        }
196
197
        $callback = static fn (?array $value, Closure $rule): ?array => $rule($value);
198
199
        return array_reduce($this->rules, $callback, $value);
200
    }
201
202
    /**
203
     * @param string $parameter
204
     *
205
     * @return int|null
206
     */
207
    public function optionalInteger(string $parameter): ?int
208
    {
209
        $value = $this->parameters[$parameter] ?? null;
210
211
        if (is_string($value) && ctype_digit($value)) {
212
            $value = (int) $value;
213
        } else {
214
            $value = null;
215
        }
216
217
        $callback = static fn (?int $value, Closure $rule): ?int => $rule($value);
218
219
        return array_reduce($this->rules, $callback, $value);
220
    }
221
222
    /**
223
     * @param string $parameter
224
     *
225
     * @return string|null
226
     */
227
    public function optionalString(string $parameter): ?string
228
    {
229
        $value = $this->parameters[$parameter] ?? null;
230
231
        if (!is_string($value)) {
232
            $value = null;
233
        }
234
235
        $callback = static fn (?string $value, Closure $rule): ?string => $rule($value);
236
237
        return array_reduce($this->rules, $callback, $value);
238
    }
239
240
    /**
241
     * @param string    $parameter
242
     * @param bool|null $default
243
     *
244
     * @return bool
245
     */
246
    public function boolean(string $parameter, bool $default = null): bool
247
    {
248
        $value = $this->parameters[$parameter] ?? null;
249
250
        if (in_array($value, ['1', true], true)) {
251
            return true;
252
        }
253
254
        if (in_array($value, ['0', '', false], true)) {
255
            return false;
256
        }
257
258
        if ($default === null) {
259
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
260
        }
261
262
        return $default;
263
    }
264
265
    /**
266
     * @param string                 $parameter
267
     * @param array<int|string>|null $default
268
     *
269
     * @return array<string>
270
     */
271
    public function array(string $parameter, array $default = null): array
272
    {
273
        $value = $this->parameters[$parameter] ?? null;
274
275
        if (!is_array($value)) {
276
            $value = null;
277
        }
278
279
        $callback = static fn (?array $value, Closure $rule): ?array => $rule($value);
280
281
        $value = array_reduce($this->rules, $callback, $value);
282
283
        $value ??= $default;
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
     * @param int|null $default
295
     *
296
     * @return int
297
     */
298
    public function integer(string $parameter, int $default = null): int
299
    {
300
        $value = $this->parameters[$parameter] ?? null;
301
302
        if (is_string($value) && ctype_digit($value)) {
303
            $value = (int) $value;
304
        } else {
305
            $value = null;
306
        }
307
308
        $callback = static fn (?int $value, Closure $rule): ?int => $rule($value);
309
310
        $value = array_reduce($this->rules, $callback, $value);
311
312
        $value ??= $default;
313
314
        if ($value === null) {
315
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
316
        }
317
318
        return $value;
319
    }
320
321
    /**
322
     * @param string $parameter
323
     *
324
     * @return Route
325
     */
326
    public function route(string $parameter = 'route'): Route
327
    {
328
        $value = $this->parameters[$parameter] ?? null;
329
330
        if ($value instanceof Route) {
331
            return $value;
332
        }
333
334
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
335
    }
336
337
    /**
338
     * @param string      $parameter
339
     * @param string|null $default
340
     *
341
     * @return string
342
     */
343
    public function string(string $parameter, string $default = null): string
344
    {
345
        $value = $this->parameters[$parameter] ?? null;
346
347
        if (!is_string($value)) {
348
            $value = null;
349
        }
350
351
        $callback = static fn (?string $value, Closure $rule): ?string => $rule($value);
352
353
        $value =  array_reduce($this->rules, $callback, $value);
354
        $value ??= $default;
355
356
        if ($value === null) {
357
            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
358
        }
359
360
        return $value;
361
    }
362
363
    /**
364
     * @param string $parameter
365
     *
366
     * @return Tree
367
     */
368
    public function tree(string $parameter = 'tree'): Tree
369
    {
370
        $value = $this->parameters[$parameter] ?? null;
371
372
        if ($value instanceof Tree) {
373
            return $value;
374
        }
375
376
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
377
    }
378
379
    /**
380
     * @param string $parameter
381
     *
382
     * @return Tree|null
383
     */
384
    public function treeOptional(string $parameter = 'tree'): ?Tree
385
    {
386
        $value = $this->parameters[$parameter] ?? null;
387
388
        if ($value === null || $value instanceof Tree) {
389
            return $value;
390
        }
391
392
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
393
    }
394
395
    /**
396
     * @param string $parameter
397
     *
398
     * @return UserInterface
399
     */
400
    public function user(string $parameter = 'user'): UserInterface
401
    {
402
        $value = $this->parameters[$parameter] ?? null;
403
404
        if ($value instanceof UserInterface) {
405
            return $value;
406
        }
407
408
        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
409
    }
410
}
411