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
|
|
|
|
18
|
|
|
declare(strict_types=1); |
19
|
|
|
|
20
|
|
|
namespace Fisharebest\Webtrees; |
21
|
|
|
|
22
|
|
|
use RuntimeException; |
23
|
|
|
|
24
|
|
|
use function preg_last_error_msg; |
25
|
|
|
use function preg_match; |
26
|
|
|
use function preg_replace; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Wrappers around PHP functions that throw exceptions instead of returning error values. |
30
|
|
|
* Eliminates many false-positives during static analysis. |
31
|
|
|
*/ |
32
|
|
|
class PHP |
33
|
|
|
{ |
34
|
|
|
/** |
35
|
|
|
* @template T of 0|256|512|768 |
36
|
|
|
* |
37
|
|
|
* @param string $pattern |
38
|
|
|
* @param string $subject |
39
|
|
|
* @param array<string>|null $matches |
40
|
|
|
* @param T $flags |
41
|
|
|
* @param int $offset |
42
|
|
|
* |
43
|
|
|
* @return int |
44
|
|
|
*/ |
45
|
|
|
public static function pregMatch(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int |
46
|
|
|
{ |
47
|
|
|
$result = preg_match($pattern, $subject, $matches, $flags, $offset); |
48
|
|
|
|
49
|
|
|
if ($result === false) { |
50
|
|
|
throw new RuntimeException(preg_last_error_msg()); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $result; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @template T of string|array<int,string> |
58
|
|
|
* |
59
|
|
|
* @param string|array<string> $pattern |
60
|
|
|
* @param string|array<string> $replacement |
61
|
|
|
* @param T $subject |
62
|
|
|
* @param int $limit |
63
|
|
|
* @param int|null $count |
64
|
|
|
* |
65
|
|
|
* @return T |
66
|
|
|
*/ |
67
|
|
|
public static function pregReplace( |
68
|
|
|
string|array $pattern, |
69
|
|
|
string|array $replacement, |
70
|
|
|
string|array $subject, |
71
|
|
|
int $limit = -1, |
72
|
|
|
int &$count = null |
73
|
|
|
): string|array { |
74
|
|
|
$result = preg_replace($pattern, $replacement, $subject, $limit, $count); |
75
|
|
|
|
76
|
|
|
if ($result === null) { |
77
|
|
|
throw new RuntimeException(preg_last_error_msg()); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $result; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|