Debian Codegraph @

includes/user/TempUser/FilteredRadixSerialMapping.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\User\TempUser;
4
5 use 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 /** @var int */
19 private $radix;
20
21 /** @var int[] */
22 private $badIndexes;
23
24 /** @var bool */
25 private $uppercase;
26
27 /**
28 * @param array $config See MainConfigSchema::AutoCreateTempUser
29 */
30 public function __construct( $config ) {
31 $this->radix = $config['radix'] ?? 10;
32 $this->badIndexes = $config['badIndexes'] ?? [];
33 $this->uppercase = $config['uppercase'] ?? false;
34 }
35
36 public function getSerialIdForIndex( int $index ): string {
37 $index = $this->adjustID( $index );
38 return \Wikimedia\base_convert( (string)$index, 10, $this->radix, 1, !$this->uppercase );
39 }
40
41 /**
42 * Add the number of "bad" IDs less than or equal to the given ID to the
43 * given ID, thus mapping the set of all integers to the "good" set.
44 *
45 * @param int $id
46 * @return int
47 */
48 private function adjustID( int $id ): int {
49 $pos = ArrayUtils::findLowerBound(
50 function ( $i ) {
51 return $this->badIndexes[$i];
52 },
53 count( $this->badIndexes ),
54 static function ( $a, $b ) {
55 return $a <=> $b;
56 },
57 $id
58 );
59 return $pos === false ? $id : $id + $pos + 1;
60 }
61 }