Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.25% covered (warning)
85.25%
52 / 61
50.00% covered (danger)
50.00%
4 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
CrhConverter
85.25% covered (warning)
85.25%
52 / 61
50.00% covered (danger)
50.00%
4 / 8
25.85
0.00% covered (danger)
0.00%
0 / 1
 getMainCode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getLanguageVariants
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getVariantsFallbacks
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 loadDefaultTables
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 loadExceptions
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
2.01
 translate
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
9
 regsConverter
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
8.09
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21use MediaWiki\Language\Language;
22use MediaWiki\Language\ReplacementArray;
23use MediaWiki\Languages\Data\CrhExceptions;
24use MediaWiki\StubObject\StubUserLang;
25
26/**
27 * Crimean Tatar (Qırımtatarca) converter routines.
28 *
29 * Adapted from https://crh.wikipedia.org/wiki/Qullan%C4%B1c%C4%B1:Don_Alessandro/Translit
30 *
31 * @ingroup Languages
32 */
33class CrhConverter extends LanguageConverterSpecific {
34    // Defines working character ranges
35
36    // Cyrillic
37    # Crimean Tatar Cyrillic uppercase
38    public const C_UC = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ';
39    # Crimean Tatar Cyrillic lowercase
40    public const C_LC = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя';
41    # Crimean Tatar Cyrillic + CÑ uppercase consonants
42    public const C_CONS_UC = 'БВГДЖЗЙКЛМНПРСТФХЦЧШЩCÑ';
43    # Crimean Tatar Cyrillic + CÑ lowercase consonants
44    public const C_CONS_LC = 'бвгджзйклмнпрстфхцчшщcñ';
45    # Crimean Tatar Cyrillic M-type consonants
46    public const C_M_CONS = 'бгкмшcБГКМШC';
47
48    // Crimean Tatar Cyrillic + CÑ consonants
49    public const C_CONS = 'бвгджзйклмнпрстфхцчшщcñБВГДЖЗЙКЛМНПРСТФХЦЧШЩCÑ';
50
51    // Latin
52    # Crimean Tatar Latin uppercase
53    public const L_UC = 'AÂBCÇDEFGĞHIİJKLMNÑOÖPQRSŞTUÜVYZ';
54    # Crimean Tatar Latin lowercase
55    public const L_LC = 'aâbcçdefgğhıijklmnñoöpqrsştuüvyz';
56    # Crimean Tatar Latin N-type upper case consonants
57    public const L_N_CONS_UC = 'ÇNRSTZ';
58    # Crimean Tatar Latin N-type lower case consonants
59    public const L_N_CONS_LC = 'çnrstz';
60    # Crimean Tatar Latin N-type consonants
61    public const L_N_CONS = 'çnrstzÇNRSTZ';
62    # Crimean Tatar Latin M-type consonants
63    public const L_M_CONS = 'bcgkmpşBCGKMPŞ';
64    # Crimean Tatar Latin uppercase consonants
65    public const L_CONS_UC = 'BCÇDFGĞHJKLMNÑPQRSŞTVZ';
66    # Crimean Tatar Latin lowercase consonants
67    public const L_CONS_LC = 'bcçdfgğhjklmnñpqrsştvz';
68    # Crimean Tatar Latin consonants
69    public const L_CONS = 'bcçdfgğhjklmnñpqrsştvzBCÇDFGĞHJKLMNÑPQRSŞTVZ';
70    # Crimean Tatar Latin uppercase vowels
71    public const L_VOW_UC = 'AÂEIİOÖUÜ';
72    # Crimean Tatar Latin vowels
73    public const L_VOW = 'aâeıioöuüAÂEIİOÖUÜ';
74    # Crimean Tatar Latin uppercase front vowels
75    public const L_F_UC = 'EİÖÜ';
76    # Crimean Tatar Latin front vowels
77    public const L_F = 'eiöüEİÖÜ';
78
79    public function getMainCode(): string {
80        return 'crh';
81    }
82
83    public function getLanguageVariants(): array {
84        return [ 'crh', 'crh-cyrl', 'crh-latn' ];
85    }
86
87    public function getVariantsFallbacks(): array {
88        return [
89            'crh' => 'crh-latn',
90            'crh-cyrl' => 'crh-latn',
91            'crh-latn' => 'crh-cyrl',
92        ];
93    }
94
95    /**
96     * @param Language|StubUserLang $langobj
97     */
98    public function __construct( $langobj ) {
99        parent::__construct( $langobj );
100
101        // No point delaying this since they're in code.
102        // Waiting until loadDefaultTables() means they never get loaded
103        // when the tables themselves are loaded from the cache.
104        $this->loadExceptions();
105    }
106
107    public const CYRILLIC_TO_LATIN = [
108        ## these are independent of location in the word, but have
109        ## to go first so other transforms don't bleed them
110        'гъ' => 'ğ', 'Гъ' => 'Ğ', 'ГЪ' => 'Ğ',
111        'къ' => 'q', 'Къ' => 'Q', 'КЪ' => 'Q',
112        'нъ' => 'ñ', 'Нъ' => 'Ñ', 'НЪ' => 'Ñ',
113        'дж' => 'c', 'Дж' => 'C', 'ДЖ' => 'C',
114
115        'А' => 'A', 'а' => 'a', 'Б' => 'B', 'б' => 'b',
116        'В' => 'V', 'в' => 'v', 'Г' => 'G', 'г' => 'g',
117        'Д' => 'D', 'д' => 'd', 'Ж' => 'J', 'ж' => 'j',
118        'З' => 'Z', 'з' => 'z', 'И' => 'İ', 'и' => 'i',
119        'Й' => 'Y', 'й' => 'y', 'К' => 'K', 'к' => 'k',
120        'Л' => 'L', 'л' => 'l', 'М' => 'M', 'м' => 'm',
121        'Н' => 'N', 'н' => 'n', 'П' => 'P', 'п' => 'p',
122        'Р' => 'R', 'р' => 'r', 'С' => 'S', 'с' => 's',
123        'Т' => 'T', 'т' => 't', 'Ф' => 'F', 'ф' => 'f',
124        'Х' => 'H', 'х' => 'h', 'Ч' => 'Ç', 'ч' => 'ç',
125        'Ш' => 'Ş', 'ш' => 'ş', 'Ы' => 'I', 'ы' => 'ı',
126        'Э' => 'E', 'э' => 'e', 'Е' => 'E', 'е' => 'e',
127        'Я' => 'Â', 'я' => 'â', 'У' => 'U', 'у' => 'u',
128        'О' => 'O', 'о' => 'o',
129
130        'Ё' => 'Yo', 'ё' => 'yo', 'Ю' => 'Yu', 'ю' => 'yu',
131        'Ц' => 'Ts', 'ц' => 'ts', 'Щ' => 'Şç', 'щ' => 'şç',
132        'Ь' => '', 'ь' => '', 'Ъ' => '', 'ъ' => '',
133    ];
134
135    public const LATIN_TO_CYRILLIC = [
136        'Â' => 'Я', 'â' => 'я', 'B' => 'Б', 'b' => 'б',
137        'Ç' => 'Ч', 'ç' => 'ч', 'D' => 'Д', 'd' => 'д',
138        'F' => 'Ф', 'f' => 'ф', 'G' => 'Г', 'g' => 'г',
139        'H' => 'Х', 'h' => 'х', 'I' => 'Ы', 'ı' => 'ы',
140        'İ' => 'И', 'i' => 'и', 'J' => 'Ж', 'j' => 'ж',
141        'K' => 'К', 'k' => 'к', 'L' => 'Л', 'l' => 'л',
142        'M' => 'М', 'm' => 'м', 'N' => 'Н', 'n' => 'н',
143        'O' => 'О', 'o' => 'о', 'P' => 'П', 'p' => 'п',
144        'R' => 'Р', 'r' => 'р', 'S' => 'С', 's' => 'с',
145        'Ş' => 'Ш', 'ş' => 'ш', 'T' => 'Т', 't' => 'т',
146        'V' => 'В', 'v' => 'в', 'Z' => 'З', 'z' => 'з',
147
148        'ya' => 'я', 'Ya' => 'Я', 'YA' => 'Я',
149        'ye' => 'е', 'YE' => 'Е', 'Ye' => 'Е',
150
151        // hack, hack, hack
152        'A' => 'А', 'a' => 'а', 'E' => 'Е', 'e' => 'е',
153        'Ö' => 'Ё', 'ö' => 'ё', 'U' => 'У', 'u' => 'у',
154        'Ü' => 'Ю', 'ü' => 'ю', 'Y' => 'Й', 'y' => 'й',
155        'C' => 'Дж', 'c' => 'дж', 'Ğ' => 'Гъ', 'ğ' => 'гъ',
156        'Ñ' => 'Нъ', 'ñ' => 'нъ', 'Q' => 'Къ', 'q' => 'къ',
157    ];
158
159    /** @var string[] */
160    private array $mCyrl2LatnExceptions = [];
161    /** @var string[] */
162    private array $mLatn2CyrlExceptions = [];
163
164    /** @var string[] */
165    private array $mCyrl2LatnPatterns = [];
166    /** @var string[] */
167    private array $mLatn2CyrlPatterns = [];
168
169    /** @var string[] */
170    private array $mCyrlCleanUpRegexes = [];
171
172    private bool $mExceptionsLoaded = false;
173
174    /**
175     * @inheritDoc
176     */
177    protected function loadDefaultTables(): array {
178        return [
179            'crh-latn' => new ReplacementArray( self::CYRILLIC_TO_LATIN ),
180            'crh-cyrl' => new ReplacementArray( self::LATIN_TO_CYRILLIC ),
181            'crh' => new ReplacementArray()
182        ];
183    }
184
185    private function loadExceptions() {
186        if ( $this->mExceptionsLoaded ) {
187            return;
188        }
189
190        $this->mExceptionsLoaded = true;
191        $crhExceptions = new CrhExceptions();
192        [ $this->mCyrl2LatnExceptions, $this->mLatn2CyrlExceptions,
193            $this->mCyrl2LatnPatterns, $this->mLatn2CyrlPatterns, $this->mCyrlCleanUpRegexes ] =
194            $crhExceptions->loadExceptions( self::L_LC . self::C_LC, self::L_UC . self::C_UC );
195    }
196
197    /**
198     * It translates text into variant, specials:
199     * - omitting roman numbers
200     *
201     * @param string $text
202     * @param string $toVariant
203     * @return string
204     */
205    public function translate( $text, $toVariant ) {
206        switch ( $toVariant ) {
207            case 'crh-cyrl':
208            case 'crh-latn':
209                break;
210            default:
211                return $text;
212        }
213
214        $this->loadTables();
215
216        if ( !isset( $this->mTables[$toVariant] ) ) {
217            throw new LogicException( "Broken variant table: " . implode( ',', array_keys( $this->mTables ) ) );
218        }
219
220        switch ( $toVariant ) {
221            case 'crh-cyrl':
222                /* Check for roman numbers like VII, XIX...
223                 * Only need to split on Roman numerals when converting to Cyrillic
224                 * Lookahead assertion ensures $roman doesn't match the empty string, and
225                 * non-period after the first "Roman" character allows initials to be converted
226                 */
227                $roman = '(?=[MDCLXVI]([^.]|$))M{0,4}(C[DM]|D?C{0,3})(X[LC]|L?X{0,3})(I[VX]|V?I{0,3})';
228
229                $breaks = '([^\w\x80-\xff])';
230
231                // allow for multiple Roman numerals in a row; rare but it happens
232                $romanRegex = '/^' . $roman . '$|^(' . $roman . $breaks . ')+|(' . $breaks . $roman . ')+$|' .
233                    $breaks . '(' . $roman . $breaks . ')+/';
234
235                $matches = preg_split( $romanRegex, $text, -1, PREG_SPLIT_OFFSET_CAPTURE );
236                $mstart = 0;
237                $ret = '';
238                foreach ( $matches as $m ) {
239                    // copy over Roman numerals
240                    $ret .= substr( $text, $mstart, (int)$m[1] - $mstart );
241
242                    // process everything else
243                    if ( $m[0] !== '' ) {
244                        $ret .= $this->regsConverter( $m[0], $toVariant );
245                    }
246
247                    $mstart = (int)$m[1] + strlen( $m[0] );
248                }
249
250                return $ret;
251
252            default:
253                // Just process the whole string in one go
254                return $this->regsConverter( $text, $toVariant );
255        }
256    }
257
258    private function regsConverter( string $text, string $toVariant ): string {
259        if ( $text == '' ) {
260            return $text;
261        }
262
263        switch ( $toVariant ) {
264            case 'crh-latn':
265                $text = strtr( $text, $this->mCyrl2LatnExceptions );
266                foreach ( $this->mCyrl2LatnPatterns as $pat => $rep ) {
267                    $text = preg_replace( $pat, $rep, $text );
268                }
269                $text = parent::translate( $text, $toVariant );
270                return strtr( $text, [ '«' => '"', '»' => '"', ] );
271
272            case 'crh-cyrl':
273                $text = strtr( $text, $this->mLatn2CyrlExceptions );
274                foreach ( $this->mLatn2CyrlPatterns as $pat => $rep ) {
275                    $text = preg_replace( $pat, $rep, $text );
276                }
277                $text = parent::translate( $text, $toVariant );
278                $text = strtr( $text, [ '“' => '«', '”' => '»', ] );
279                foreach ( $this->mCyrlCleanUpRegexes as $pat => $rep ) {
280                    $text = preg_replace( $pat, $rep, $text );
281                }
282                return $text;
283
284            default:
285                return $text;
286        }
287    }
288}