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{0:int,1:bool} |
| 39 | * @throws InvalidArgumentException |
| 40 | */ |
| 41 | public static function splitGlobalName( $filter ): array { |
| 42 | if ( preg_match( '/^' . self::GLOBAL_FILTER_PREFIX . '\d+$/', $filter ) === 1 ) { |
| 43 | $id = intval( substr( $filter, strlen( self::GLOBAL_FILTER_PREFIX ) ) ); |
| 44 | return [ $id, true ]; |
| 45 | } elseif ( is_numeric( $filter ) ) { |
| 46 | return [ (int)$filter, false ]; |
| 47 | } else { |
| 48 | throw new InvalidArgumentException( "Invalid filter name: $filter" ); |
| 49 | } |
| 50 | } |
| 51 | } |