RussianLanguage::in()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 2
Ratio 28.57 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 2
loc 7
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace morphos\Russian;
3
4
use morphos\Gender;
5
use morphos\S;
6
7
trait RussianLanguage
8
{
9
    /**
10
     * @var string[] Все гласные
11
     */
12
    public static $vowels = [
13
        'а',
14
        'е',
15
        'ё',
16
        'и',
17
        'о',
18
        'у',
19
        'ы',
20
        'э',
21
        'ю',
22
        'я',
23
    ];
24
25
    /**
26
     * @var string[] Все согласные
27
     */
28
    public static $consonants = [
29
        'б',
30
        'в',
31
        'г',
32
        'д',
33
        'ж',
34
        'з',
35
        'й',
36
        'к',
37
        'л',
38
        'м',
39
        'н',
40
        'п',
41
        'р',
42
        'с',
43
        'т',
44
        'ф',
45
        'х',
46
        'ц',
47
        'ч',
48
        'ш',
49
        'щ',
50
    ];
51
52
    /**
53
     * @var string[] Пары согласных
54
     * @phpstan-var array<string, string>
55
     */
56
    public static $pairs = [
57
        'б' => 'п',
58
        'в' => 'ф',
59
        'г' => 'к',
60
        'д' => 'т',
61
        'ж' => 'ш',
62
        'з' => 'с',
63
    ];
64
65
    /**
66
     * @var string[] Звонкие согласные
67
     */
68
    public static $sonorousConsonants = ['б', 'в', 'г', 'д', 'з', 'ж', 'л', 'м', 'н', 'р'];
69
    /**
70
     * @var string[] Глухие согласные
71
     */
72
    public static $deafConsonants = ['п', 'ф', 'к', 'т', 'с', 'ш', 'х', 'ч', 'щ'];
73
74
    /**
75
     * @var string[] Союзы
76
     */
77
    public static $unions = ['и', 'или'];
78
79
    /**
80
     * @return string[]
81
     */
82
    public static function getVowels()
83
    {
84
        return self::$vowels;
85
    }
86
87
    /**
88
     * Проверка гласной
89
     * @param string $char
90
     * @return bool
91
     */
92 354
    public static function isVowel($char)
93
    {
94 354
        return in_array($char, static::$vowels, true);
95
    }
96
97
    /**
98
     * Проверка согласной
99
     * @param string $char
100
     * @return bool
101
     */
102 240
    public static function isConsonant($char)
103
    {
104 240
        return in_array($char, static::$consonants, true);
105
    }
106
107
    /**
108
     * Проверка звонкости согласной
109
     * @param string $char
110
     * @return bool
111
     */
112 3
    public static function isSonorousConsonant($char)
113
    {
114 3
        return in_array($char, static::$sonorousConsonants, true);
115
    }
116
117
    /**
118
     * Проверка глухости согласной
119
     * @param string $char
120
     * @return bool
121
     */
122 8
    public static function isDeafConsonant($char)
123
    {
124 8
        return in_array($char, static::$deafConsonants, true);
125
    }
126
127
    /**
128
     * Щипящая ли согласная
129
     * @param string $consonant
130
     * @return bool
131
     */
132 454
    public static function isHissingConsonant($consonant)
133
    {
134 454
        return in_array(S::lower($consonant), ['ж', 'ш', 'ч', 'щ'], true);
135
    }
136
137
    /**
138
     * Проверка на велярность согласной
139
     * @param string $consonant
140
     * @return bool
141
     */
142 19
    protected static function isVelarConsonant($consonant)
143
    {
144 19
        return in_array(S::lower($consonant), ['г', 'к', 'х'], true);
145
    }
146
147
    /**
148
     * Подсчет слогов
149
     * @param string $string
150
     * @return bool|int
151
     */
152
    public static function countSyllables($string)
153
    {
154
        return S::countChars($string, static::$vowels);
155
    }
156
157
    /**
158
     * Проверка парности согласной
159
     *
160
     * @param string $consonant
161
     * @return bool
162
     */
163
    public static function isPairedConsonant($consonant)
164
    {
165
        $consonant = S::lower($consonant);
166
        return array_key_exists($consonant, static::$pairs) || (array_search($consonant, static::$pairs) !== false);
167
    }
168
169
    /**
170
     * Проверка мягкости последней согласной
171
     * @param string $word
172
     * @return bool
173
     */
174 54
    public static function checkLastConsonantSoftness($word)
175
    {
176 54 View Code Duplication
        if (($substring = S::findLastPositionForOneOfChars(S::lower($word), static::$consonants)) !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177 54
            if (in_array(S::slice($substring, 0, 1), ['й', 'ч', 'щ', 'ш'], true)) { // always soft consonants
178 15
                return true;
179
            }
180
181 40
            if (S::length($substring) > 1 && in_array(S::slice($substring, 1, 2), ['е', 'ё', 'и', 'ю', 'я', 'ь'], true)) { // consonants are soft if they are trailed with these vowels
182 3
                return true;
183
            }
184
        }
185 37
        return false;
186
    }
187
188
    /**
189
     * Проверка мягкости последней согласной, за исключением Н
190
     * @param string $word
191
     * @return bool
192
     */
193 13
    public static function checkBaseLastConsonantSoftness($word)
194
    {
195 13
        $consonants = static::$consonants;
196 13
        unset($consonants[array_search('н', $consonants)]);
197 13
        unset($consonants[array_search('й', $consonants)]);
198
199 13 View Code Duplication
        if (($substring = S::findLastPositionForOneOfChars(S::lower($word), $consonants)) !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
            if (in_array(S::slice($substring, 0, 1), ['й', 'ч', 'щ', 'ш'], true)) { // always soft consonants
201
                return true;
202
            }
203
204
            if (S::length($substring) > 1 && in_array(S::slice($substring, 1, 2), ['е', 'ё', 'и', 'ю', 'я', 'ь'], true)) { // consonants are soft if they are trailed with these vowels
205
                return true;
206
            }
207
        }
208 13
        return false;
209
    }
210
211
    /**
212
     * Проверяет, что гласная образует два звука в словах
213
     * @param string $vowel
214
     * @return bool
215
     */
216 2
    public static function isBinaryVowel($vowel)
217
    {
218 2
        return in_array(S::lower($vowel), ['е', 'ё', 'ю', 'я'], true);
219
    }
220
221
    /**
222
     * Выбор предлога по первой букве
223
     *
224
     * @param string $word Слово
225
     * @param string $prepositionWithVowel Предлог, если слово начинается с гласной
226
     * @param string $preposition Предлог, если слово не начинается с гласной
227
     *
228
     * @return string
229
     */
230
    public static function choosePrepositionByFirstLetter($word, $prepositionWithVowel, $preposition)
231
    {
232
        if (in_array(S::lower(S::slice($word, 0, 1)), ['а', 'о', 'и', 'у', 'э'], true)) {
233
            return $prepositionWithVowel;
234
        }
235
236
        return $preposition;
237
    }
238
239
    /**
240
     * Выбор окончания в зависимости от мягкости
241
     *
242
     * @param string $last
243
     * @param bool $softLast
244
     * @param string $afterSoft
245
     * @param string $afterHard
246
     *
247
     * @return string
248
     */
249 151
    public static function chooseVowelAfterConsonant($last, $softLast, $afterSoft, $afterHard)
250
    {
251 151
        if ($last !== 'щ' && /*static::isVelarConsonant($last) ||*/ $softLast) {
252 57
            return $afterSoft;
253
        }
254
255 116
        return $afterHard;
256
    }
257
258
    /**
259
     * @param string $verb Verb to modify if gender is female
260
     * @param string $gender If not `m`, verb will be modified
261
     * @return string Correct verb
262
     */
263 10
    public static function verb($verb, $gender)
264
    {
265 10
        $verb = S::lower($verb);
266
        // возвратный глагол
267 10
        if (S::slice($verb, -2) === 'ся') {
268
269 5
            return ($gender == Gender::MALE
270 2
                ? $verb
271 5
                : S::slice($verb, 0, -2).(S::slice($verb, -3, -2) === 'л' ? null : 'л').'ась');
272
        }
273
274
        // обычный глагол
275 5
        return ($gender == Gender::MALE
276 2
            ? $verb
277 5
            : $verb.(S::slice($verb, -1) === 'л' ? null : 'л').'а');
278
    }
279
280
    /**
281
     * Add 'в' or 'во' prepositional before the word
282
     * @param string $word
283
     * @return string
284
     */
285 1
    public static function in($word)
286
    {
287 1
        $normalized = trim(S::lower($word));
288 1 View Code Duplication
        if (in_array(S::slice($normalized, 0, 1), ['в', 'ф'], true))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
289 1
            return 'во '.$word;
290 1
        return 'в '.$word;
291
    }
292
293
    /**
294
     * Add 'с' or 'со' prepositional before the word
295
     * @param string $word
296
     * @return string
297
     */
298 1
    public static function with($word)
299
    {
300 1
        $normalized = trim(S::lower($word));
301 1
        if (in_array(S::slice($normalized, 0, 1), ['c', 'з', 'ш', 'ж'], true) && static::isConsonant(S::slice($normalized, 1, 2)) || S::slice($normalized, 0, 1) === 'щ')
302 1
            return 'со '.$word;
303 1
        return 'с '.$word;
304
    }
305
306
    /**
307
     * Add 'о' or 'об' or 'обо' prepositional before the word
308
     * @param string $word
309
     * @return string
310
     */
311 1
    public static function about($word)
312
    {
313 1
        $normalized = trim(S::lower($word));
314 1
        if (static::isVowel(S::slice($normalized, 0, 1)) && !in_array(S::slice($normalized, 0, 1), ['е', 'ё', 'ю', 'я'], true))
315 1
            return 'об '.$word;
316
317 1
        if (in_array(S::slice($normalized, 0, 3), ['все', 'всё', 'всю', 'что', 'мне'], true))
318 1
            return 'обо '.$word;
319
320 1
        return 'о '.$word;
321
    }
322
323
    /**
324
     * Выбирает первое или второе окончание в зависимости от звонкости/глухости в конце слова.
325
     * @param string $word Слово (или префикс), на основе звонкости которого нужно выбрать окончание
326
     * @param string $ifSonorous Окончание, если слово оканчивается на звонкую согласную
327
     * @param string $ifDeaf Окончание, если слово оканчивается на глухую согласную
328
     * @return string Первое или второе окончание
329
     * @throws \Exception
330
     */
331 3
    public static function chooseEndingBySonority($word, $ifSonorous, $ifDeaf)
332
    {
333 3
        $last = S::slice($word, -1);
334 3
        if (static::isSonorousConsonant($last))
335 2
            return $ifSonorous;
336 1
        if (static::isDeafConsonant($last))
337 1
            return $ifDeaf;
338
339
        throw new \Exception('Not implemented');
340
    }
341
342
    /**
343
     * Проверяет, является ли существительно адъективным существительным
344
     * @param string $noun Существительное
345
     * @return bool
346
     */
347 178
    public static function isAdjectiveNoun($noun)
348
    {
349 178
        return in_array(S::slice($noun, -2), ['ой', 'ий', 'ый', 'ая', 'ое', 'ее'])
350 178
            && !in_array($noun, ['гений', 'комментарий']);
351
    }
352
353
    /**
354
     * @param string[] $forms
355
     * @phpstan-param array<string, string> $forms
356
     * @param bool $animate
357
     * @return string
358
     */
359 144
    public static function getVinitCaseByAnimateness(array $forms, $animate)
360
    {
361 144
        if ($animate) {
362 13
            return $forms[Cases::RODIT];
363
        }
364
365 131
        return $forms[Cases::IMENIT];
366
    }
367
}
368