MediaWiki master
RemoteIcuCollation.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Collation;
4
5use Collator;
7use RuntimeException;
8use Shellbox\RPC\RpcClient;
9
16 private RpcClient $rpcClient;
17 private string $locale;
18
19 public function __construct( ShellboxClientFactory $shellboxClientFactory, string $locale ) {
20 $this->rpcClient = $shellboxClientFactory->getRpcClient(
21 [ 'service' => 'icu-collation' ] );
22 $this->locale = $locale;
23 }
24
26 public function getSortKey( $string ) {
27 return $this->getSortKeys( [ $string ] )[0];
28 }
29
36 private static function encode( $strings ) {
37 $ret = '';
38 foreach ( $strings as $s ) {
39 $ret .= sprintf( "%08x", strlen( $s ) ) . $s;
40 }
41 return $ret;
42 }
43
50 private static function decode( $blob ) {
51 $p = 0;
52 $ret = [];
53 while ( $p < strlen( $blob ) ) {
54 $len = intval( substr( $blob, $p, 8 ), 16 );
55 $p += 8;
56 $ret[] = substr( $blob, $p, $len );
57 $p += $len;
58 }
59 return $ret;
60 }
61
63 public function getSortKeys( $strings ) {
64 if ( !count( $strings ) ) {
65 return [];
66 }
67 $blob = $this->rpcClient->call(
68 'icu-collation',
69 [ self::class, 'doGetSortKeys' ],
70 [
71 $this->locale,
72 self::encode( array_values( $strings ) )
73 ],
74 [
75 'classes' => [ parent::class, self::class ],
76 'binary' => true
77 ]
78 );
79 return array_combine(
80 array_keys( $strings ),
81 self::decode( $blob )
82 );
83 }
84
86 public function getFirstLetter( $string ) {
87 // @phan-suppress-previous-line PhanPluginNeverReturnMethod
88 throw new RuntimeException( __METHOD__ . ': not implemented' );
89 }
90
98 public static function doGetSortKeys( $locale, $blob ) {
99 $mainCollator = Collator::create( $locale );
100 if ( !$mainCollator ) {
101 throw new RuntimeException( "Invalid ICU locale specified for collation: $locale" );
102 }
103
104 $ret = [];
105 foreach ( self::decode( $blob ) as $string ) {
106 $ret[] = $mainCollator->getSortKey( $string );
107 }
108 return self::encode( $ret );
109 }
110}
111
113class_alias( RemoteIcuCollation::class, 'RemoteIcuCollation' );
An ICU collation that uses a remote server to compute sort keys.
static doGetSortKeys( $locale, $blob)
The remote entry point.
__construct(ShellboxClientFactory $shellboxClientFactory, string $locale)
getSortKeys( $strings)
Get multiple sort keys.string[]
getSortKey( $string)
Given a string, convert it to a (hopefully short) key that can be used for efficient sorting....
getFirstLetter( $string)
Given a string, return the logical "first letter" to be used for grouping on category pages and so on...
This is a service which provides a configured client to access a remote Shellbox installation.
getRpcClient(array $options=[])
Get a Shellbox RPC client with specified options.