Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
8 / 8 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
GlobalNameUtils | |
100.00% |
8 / 8 |
|
100.00% |
2 / 2 |
5 | |
100.00% |
1 / 1 |
buildGlobalName | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
splitGlobalName | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | |
3 | namespace MediaWiki\Extension\AbuseFilter; |
4 | |
5 | use InvalidArgumentException; |
6 | |
7 | /** |
8 | * @internal |
9 | */ |
10 | class GlobalNameUtils { |
11 | /** @var string The prefix to use for global filters */ |
12 | public const GLOBAL_FILTER_PREFIX = 'global-'; |
13 | |
14 | /** |
15 | * Given a filter ID and a boolean indicating whether it's global, build a string like |
16 | * "<GLOBAL_FILTER_PREFIX>$ID". Note that, with global = false, $id is casted to string. |
17 | * This reverses self::splitGlobalName. |
18 | * |
19 | * @param int $id The filter ID |
20 | * @param bool $global Whether the filter is global |
21 | * @return string |
22 | * @todo Calling this method should be avoided wherever possible |
23 | */ |
24 | public static function buildGlobalName( int $id, bool $global = true ): string { |
25 | $prefix = $global ? self::GLOBAL_FILTER_PREFIX : ''; |
26 | return "$prefix$id"; |
27 | } |
28 | |
29 | /** |
30 | * Utility function to split "<GLOBAL_FILTER_PREFIX>$index" to an array [ $id, $global ], where |
31 | * $id is $index casted to int, and $global is a boolean: true if the filter is global, |
32 | * false otherwise (i.e. if the $filter === $index). Note that the $index |
33 | * is always casted to int. Passing anything which isn't an integer-like value or a string |
34 | * in the shape "<GLOBAL_FILTER_PREFIX>integer" will throw. |
35 | * This reverses self::buildGlobalName |
36 | * |
37 | * @param string|int $filter |
38 | * @return array |
39 | * @phan-return array{0:int,1:bool} |
40 | * @throws InvalidArgumentException |
41 | */ |
42 | public static function splitGlobalName( $filter ): array { |
43 | if ( preg_match( '/^' . self::GLOBAL_FILTER_PREFIX . '\d+$/', $filter ) === 1 ) { |
44 | $id = intval( substr( $filter, strlen( self::GLOBAL_FILTER_PREFIX ) ) ); |
45 | return [ $id, true ]; |
46 | } elseif ( is_numeric( $filter ) ) { |
47 | return [ (int)$filter, false ]; |
48 | } else { |
49 | throw new InvalidArgumentException( "Invalid filter name: $filter" ); |
50 | } |
51 | } |
52 | } |