Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| FilteredRadixSerialMapping | |
100.00% |
12 / 12 |
|
100.00% |
3 / 3 |
4 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| getSerialIdForIndex | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| adjustID | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace MediaWiki\User\TempUser; |
| 4 | |
| 5 | use Wikimedia\ArrayUtils\ArrayUtils; |
| 6 | |
| 7 | /** |
| 8 | * Since "base" is an overused term in class names and mostly means something |
| 9 | * else, we will call the base of a numeric representation a radix. |
| 10 | * |
| 11 | * This class converts integer serial numbers to strings using an arbitrary |
| 12 | * base between 2 and 36. It can skip certain IDs deemed to be "bad", e.g. |
| 13 | * because they spell offensive words. |
| 14 | * |
| 15 | * @since 1.39 |
| 16 | */ |
| 17 | class FilteredRadixSerialMapping implements SerialMapping { |
| 18 | private readonly int $radix; |
| 19 | |
| 20 | /** @var int[] */ |
| 21 | private readonly array $badIndexes; |
| 22 | |
| 23 | private readonly bool $uppercase; |
| 24 | |
| 25 | /** |
| 26 | * @param array $config See MainConfigSchema::AutoCreateTempUser |
| 27 | */ |
| 28 | public function __construct( array $config ) { |
| 29 | $this->radix = $config['radix'] ?? 10; |
| 30 | $this->badIndexes = $config['badIndexes'] ?? []; |
| 31 | $this->uppercase = $config['uppercase'] ?? false; |
| 32 | } |
| 33 | |
| 34 | public function getSerialIdForIndex( int $index ): string { |
| 35 | $index = $this->adjustID( $index ); |
| 36 | return \Wikimedia\base_convert( (string)$index, 10, $this->radix, 1, !$this->uppercase ); |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Add the number of "bad" IDs less than or equal to the given ID to the |
| 41 | * given ID, thus mapping the set of all integers to the "good" set. |
| 42 | * |
| 43 | * @param int $id |
| 44 | * @return int |
| 45 | */ |
| 46 | private function adjustID( int $id ): int { |
| 47 | $pos = ArrayUtils::findLowerBound( |
| 48 | fn ( $i ) => $this->badIndexes[$i], |
| 49 | count( $this->badIndexes ), |
| 50 | static fn ( $a, $b ) => $a <=> $b, |
| 51 | $id |
| 52 | ); |
| 53 | return $pos === false ? $id : $id + $pos + 1; |
| 54 | } |
| 55 | } |