MediaWiki master
NumericUppercaseCollation.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Collation;
8
10use MediaWiki\Languages\LanguageFactory;
11
27
31 private $digitTransformLang;
32
39 public function __construct(
40 LanguageFactory $languageFactory,
41 $digitTransformLang
42 ) {
43 $this->digitTransformLang = $digitTransformLang instanceof Language
44 ? $digitTransformLang
45 : $languageFactory->getLanguage( $digitTransformLang );
46 parent::__construct( $languageFactory );
47 }
48
50 public function getSortKey( $string ) {
51 $sortkey = parent::getSortKey( $string );
52 $sortkey = $this->convertDigits( $sortkey );
53 // For each sequence of digits, insert the digit '0' and then the length of the sequence
54 // (encoded in two bytes) before it. That's all folks, it sorts correctly now! The '0' ensures
55 // correct position (where digits would normally sort), then the length will be compared putting
56 // shorter numbers before longer ones; if identical, then the characters will be compared, which
57 // generates the correct results for numbers of equal length.
58 $sortkey = preg_replace_callback( '/\d+/', static function ( $matches ) {
59 // Strip any leading zeros
60 $number = ltrim( $matches[0], '0' );
61 $len = strlen( $number );
62 // This allows sequences of up to 65536 numeric characters to be handled correctly. One byte
63 // would allow only for 256, which doesn't feel future-proof.
64 $prefix = chr( (int)floor( $len / 256 ) ) . chr( $len % 256 );
65 return '0' . $prefix . $number;
66 }, $sortkey );
67
68 return $sortkey;
69 }
70
79 private function convertDigits( $string ) {
80 $table = $this->digitTransformLang->digitTransformTable();
81 if ( $table ) {
82 $table = array_filter( $table );
83 $flipped = array_flip( $table );
84 // Some languages seem to also have commas in this table.
85 $flipped = array_filter( $flipped, 'is_numeric' );
86 $string = strtr( $string, $flipped );
87 }
88 return $string;
89 }
90
92 public function getFirstLetter( $string ) {
93 $convertedString = $this->convertDigits( $string );
94
95 if ( preg_match( '/^\d/', $convertedString ) ) {
96 return wfMessage( 'category-header-numerals' )
97 ->numParams( 0, 9 )
98 ->text();
99 } else {
100 return parent::getFirstLetter( $string );
101 }
102 }
103}
104
106class_alias( NumericUppercaseCollation::class, 'NumericUppercaseCollation' );
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Collation that orders text with numbers "naturally", so that 'Foo 1' < 'Foo 2' < 'Foo 12'.
getSortKey( $string)
Given a string, convert it to a (hopefully short) key that can be used for efficient sorting....
__construct(LanguageFactory $languageFactory, $digitTransformLang)
getFirstLetter( $string)
Given a string, return the logical "first letter" to be used for grouping on category pages and so on...
Base class for language-specific code.
Definition Language.php:70