xref: /webtrees/app/Validator.php (revision 46b31fc102c48c09a46fa5b1685ad83d1204ac6a)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees;
21
22use Aura\Router\Route;
23use Closure;
24use Fisharebest\Webtrees\Contracts\UserInterface;
25use Fisharebest\Webtrees\Http\Exceptions\HttpBadRequestException;
26use LogicException;
27use Psr\Http\Message\ServerRequestInterface;
28
29use function array_reduce;
30use function ctype_digit;
31use function in_array;
32use function is_array;
33use function is_int;
34use function is_string;
35use function parse_url;
36use function preg_match;
37use function str_starts_with;
38
39/**
40 * Validate a parameter from an HTTP request
41 */
42class Validator
43{
44    /** @var array<int|string|Tree|UserInterface|array<int|string>> */
45    private array $parameters;
46
47    /** @var array<Closure> */
48    private array $rules = [];
49
50    /**
51     * @param array<int|string|Tree|UserInterface|array<int|string>> $parameters
52     */
53    public function __construct(array $parameters)
54    {
55        $this->parameters = $parameters;
56    }
57
58    /**
59     * @param ServerRequestInterface $request
60     *
61     * @return self
62     */
63    public static function attributes(ServerRequestInterface $request): self
64    {
65        return new self($request->getAttributes());
66    }
67
68    /**
69     * @param ServerRequestInterface $request
70     *
71     * @return self
72     */
73    public static function parsedBody(ServerRequestInterface $request): self
74    {
75        return new self((array) $request->getParsedBody());
76    }
77
78    /**
79     * @param ServerRequestInterface $request
80     *
81     * @return self
82     */
83    public static function queryParams(ServerRequestInterface $request): self
84    {
85        return new self($request->getQueryParams());
86    }
87
88    /**
89     * @param ServerRequestInterface $request
90     *
91     * @return self
92     */
93    public static function serverParams(ServerRequestInterface $request): self
94    {
95        return new self($request->getServerParams());
96    }
97
98    /**
99     * @param int $minimum
100     * @param int $maximum
101     *
102     * @return self
103     */
104    public function isBetween(int $minimum, int $maximum): self
105    {
106        $this->rules[] = static function (?int $value) use ($minimum, $maximum): ?int {
107            if (is_int($value) && $value >= $minimum && $value <= $maximum) {
108                return $value;
109            }
110
111            return null;
112        };
113
114        return $this;
115    }
116
117    /**
118     * @param array<string> $values
119     *
120     * @return self
121     */
122    public function isInArray(array $values): self
123    {
124        $this->rules[] = static fn (int|string|null $value): int|string|null => $value !== null && in_array($value, $values, true) ? $value : null;
125
126        return $this;
127    }
128
129    /**
130     * @param array<string> $values
131     *
132     * @return self
133     */
134    public function isInArrayKeys(array $values): self
135    {
136        return $this->isInArray(array_keys($values));
137    }
138
139    /**
140     * @return self
141     */
142    public function isNotEmpty(): self
143    {
144        $this->rules[] = static fn (?string $value): ?string => $value !== null && $value !== '' ? $value : null;
145
146        return $this;
147    }
148
149    /**
150     * @param string $base_url
151     *
152     * @return self
153     */
154    public function isLocalUrl(string $base_url): self
155    {
156        $this->rules[] = static function (?string $value) use ($base_url): ?string {
157            if ($value !== null) {
158                $value_info    = parse_url($value);
159                $base_url_info = parse_url($base_url);
160
161                if (!is_array($base_url_info)) {
162                    throw new LogicException(__METHOD__ . ' needs a valid URL');
163                }
164
165                if (is_array($value_info)) {
166                    $scheme_ok = ($value_info['scheme'] ?? 'http') === ($base_url_info['scheme'] ?? 'http');
167                    $host_ok   = ($value_info['host'] ?? '') === ($base_url_info['host'] ?? '');
168                    $port_ok   = ($value_info['port'] ?? '') === ($base_url_info['port'] ?? '');
169                    $user_ok   = ($value_info['user'] ?? '') === ($base_url_info['user'] ?? '');
170                    $path_ok   = str_starts_with($value_info['path'] ?? '/', $base_url_info['path'] ?? '/');
171
172                    if ($scheme_ok && $host_ok && $port_ok && $user_ok && $path_ok) {
173                        return $value;
174                    }
175                }
176            }
177
178            return null;
179        };
180
181        return $this;
182    }
183
184    /**
185     * @return self
186     */
187    public function isTag(): self
188    {
189        $this->rules[] = static function (?string $value): ?string {
190            if ($value !== null && preg_match('/^' . Gedcom::REGEX_TAG . '$/', $value) === 1) {
191                return $value;
192            }
193
194            return null;
195        };
196
197        return $this;
198    }
199
200    /**
201     * @return self
202     */
203    public function isXref(): self
204    {
205        $this->rules[] = static function (?string $value): ?string {
206            if ($value !== null && preg_match('/^' . Gedcom::REGEX_XREF . '$/', $value) === 1) {
207                return $value;
208            }
209
210            return null;
211        };
212
213        return $this;
214    }
215
216    /**
217     * @param string    $parameter
218     * @param bool|null $default
219     *
220     * @return bool
221     */
222    public function boolean(string $parameter, bool $default = null): bool
223    {
224        $value = $this->parameters[$parameter] ?? null;
225
226        if (in_array($value, ['1', 'on', true], true)) {
227            return true;
228        }
229
230        if (in_array($value, ['0', '', false], true)) {
231            return false;
232        }
233
234        if ($default === null) {
235            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
236        }
237
238        return $default;
239    }
240
241    /**
242     * @param string $parameter
243     *
244     * @return array<string>
245     */
246    public function array(string $parameter): array
247    {
248        $value = $this->parameters[$parameter] ?? null;
249
250        if (!is_array($value) && $value !== null) {
251            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
252        }
253
254        $callback = static fn (?array $value, Closure $rule): ?array => $rule($value);
255
256        $value = array_reduce($this->rules, $callback, $value);
257        $value ??= [];
258
259        $check_utf8 = static function ($v, $k) use ($parameter) {
260            if (is_string($k) && !preg_match('//u', $k) || is_string($v) && !preg_match('//u', $v)) {
261                throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
262            }
263        };
264
265        array_walk_recursive($value, $check_utf8);
266
267        return $value;
268    }
269
270    /**
271     * @param string   $parameter
272     * @param int|null $default
273     *
274     * @return int
275     */
276    public function integer(string $parameter, int $default = null): int
277    {
278        $value = $this->parameters[$parameter] ?? null;
279
280        if (is_string($value) && ctype_digit($value)) {
281            $value = (int) $value;
282        } elseif (!is_int($value)) {
283            $value = null;
284        }
285
286        $callback = static fn (?int $value, Closure $rule): ?int => $rule($value);
287
288        $value = array_reduce($this->rules, $callback, $value);
289
290        $value ??= $default;
291
292        if ($value === null) {
293            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
294        }
295
296        return $value;
297    }
298
299    /**
300     * @param string $parameter
301     *
302     * @return Route
303     */
304    public function route(string $parameter = 'route'): Route
305    {
306        $value = $this->parameters[$parameter] ?? null;
307
308        if ($value instanceof Route) {
309            return $value;
310        }
311
312        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
313    }
314
315    /**
316     * @param string      $parameter
317     * @param string|null $default
318     *
319     * @return string
320     */
321    public function string(string $parameter, string $default = null): string
322    {
323        $value = $this->parameters[$parameter] ?? null;
324
325        if (!is_string($value)) {
326            $value = null;
327        }
328
329        $callback = static fn (?string $value, Closure $rule): ?string => $rule($value);
330
331        $value =  array_reduce($this->rules, $callback, $value);
332        $value ??= $default;
333
334        if ($value === null || preg_match('//u', $value) !== 1) {
335            throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
336        }
337
338        return $value;
339    }
340
341    /**
342     * @param string $parameter
343     *
344     * @return Tree
345     */
346    public function tree(string $parameter = 'tree'): Tree
347    {
348        $value = $this->parameters[$parameter] ?? null;
349
350        if ($value instanceof Tree) {
351            return $value;
352        }
353
354        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
355    }
356
357    /**
358     * @param string $parameter
359     *
360     * @return Tree|null
361     */
362    public function treeOptional(string $parameter = 'tree'): ?Tree
363    {
364        $value = $this->parameters[$parameter] ?? null;
365
366        if ($value === null || $value instanceof Tree) {
367            return $value;
368        }
369
370        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
371    }
372
373    /**
374     * @param string $parameter
375     *
376     * @return UserInterface
377     */
378    public function user(string $parameter = 'user'): UserInterface
379    {
380        $value = $this->parameters[$parameter] ?? null;
381
382        if ($value instanceof UserInterface) {
383            return $value;
384        }
385
386        throw new HttpBadRequestException(I18N::translate('The parameter “%s” is missing.', $parameter));
387    }
388}
389