OrdinalNumeralGenerator::getCase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
namespace morphos\Russian;
3
4
use morphos\NumeralGenerator;
5
use morphos\S;
6
use RuntimeException;
7
8
/**
9
 * Rules are from http://www.fio.ru/pravila/grammatika/sklonenie-imen-chislitelnykh/
10
 *            and http://school-collection.edu.ru/dlrstore-wrapper/ebbc76cf-46b6-4d51-ad92-d9a84db35cfa/[I-RUS_06-05]_[TE_16-SU]/[I-RUS_06-05]_[TE_16-SU].html
11
 */
12
class OrdinalNumeralGenerator extends NumeralGenerator implements Cases
13
{
14
    use RussianLanguage, CasesHelper;
15
16
    /**
17
     * @var string[]
18
     * @phpstan-var array<int, string>
19
     */
20
    protected static $words = [
21
        1 => 'первый',
22
        2 => 'второй',
23
        3 => 'третий',
24
        4 => 'четвертый',
25
        5 => 'пятый',
26
        6 => 'шестой',
27
        7 => 'седьмой',
28
        8 => 'восьмой',
29
        9 => 'девятый',
30
        10 => 'десятый',
31
        11 => 'одиннадцатый',
32
        12 => 'двенадцатый',
33
        13 => 'тринадцатый',
34
        14 => 'четырнадцатый',
35
        15 => 'пятнадцатый',
36
        16 => 'шестнадцатый',
37
        17 => 'семнадцатый',
38
        18 => 'восемнадцатый',
39
        19 => 'девятнадцатый',
40
        20 => 'двадцатый',
41
        30 => 'тридцатый',
42
        40 => 'сороковой',
43
        50 => 'пятьдесятый',
44
        60 => 'шестьдесятый',
45
        70 => 'семьдесятый',
46
        80 => 'восемьдесятый',
47
        90 => 'девяностый',
48
        100 => 'сотый',
49
        200 => 'двухсотый',
50
        300 => 'трехсотый',
51
        400 => 'четырехсотый',
52
        500 => 'пятисотый',
53
        600 => 'шестисотый',
54
        700 => 'семисотый',
55
        800 => 'восемисотый',
56
        900 => 'девятисотый',
57
    ];
58
59
    /**
60
     * @var string[]
61
     * @phpstan-var array<int, string>
62
     */
63
    protected static $exponents = [
64
        1000 => 'тысячный',
65
        1000000 => 'миллионный',
66
        1000000000 => 'миллиардный',
67
        1000000000000 => 'триллионный',
68
    ];
69
70
    /**
71
     * @var string[]
72
     * @phpstan-var array<int, string>
73
     */
74
    protected static $multipliers = [
75
        2 => 'двух',
76
        3 => 'трех',
77
        4 => 'четырех',
78
        5 => 'пяти',
79
        6 => 'шести',
80
        7 => 'седьми',
81
        8 => 'восьми',
82
        9 => 'девяти',
83
        10 => 'десяти',
84
        11 => 'одиннадцати',
85
        12 => 'двенадцати',
86
        13 => 'тринадцати',
87
        14 => 'четырнадцати',
88
        15 => 'пятнадцати',
89
        16 => 'шестнадцати',
90
        17 => 'семнадцати',
91
        18 => 'восемнадцати',
92
        19 => 'девятнадцати',
93
        20 => 'двадцати',
94
        30 => 'тридцати',
95
        40 => 'сорока',
96
        50 => 'пятьдесяти',
97
        60 => 'шестьдесяти',
98
        70 => 'семьдесяти',
99
        80 => 'восемьдесяти',
100
        90 => 'девяности',
101
        100 => 'сто',
102
        200 => 'двухста',
103
        300 => 'трехста',
104
        400 => 'четырехста',
105
        500 => 'пятиста',
106
        600 => 'шестиста',
107
        700 => 'семиста',
108
        800 => 'восемиста',
109
        900 => 'девятиста',
110
    ];
111
112
    /**
113
     * @param int $number
114
     * @param string $gender
115
     *
116
     * @return string[]
117
     * @phpstan-return array<string, string>
118
     * @throws \Exception
119
     */
120 36
    public static function getCases($number, $gender = self::MALE)
121
    {
122
        // simple numeral
123 36
        if (isset(static::$words[$number]) || isset(static::$exponents[$number])) {
124 36
            $word = isset(static::$words[$number]) ? static::$words[$number] : static::$exponents[$number];
125
            // special rules for 3
126 36
            if ($number == 3) {
127 2
                $prefix = S::slice($word, 0, -2);
128
                return [
129 2
                    static::IMENIT => $prefix.($gender == static::MALE ? 'ий' : ($gender == static::FEMALE ? 'ья' : 'ье')),
130 2
                    static::RODIT => $prefix.($gender == static::FEMALE ? 'ьей' : 'ьего'),
131 2
                    static::DAT => $prefix.($gender == static::FEMALE ? 'ьей' : 'ьему'),
132 2
                    static::VINIT => $prefix.($gender == static::FEMALE ? 'ью' : 'ьего'),
133 2
                    static::TVORIT => $prefix.($gender == static::FEMALE ? 'ьей' : 'ьим'),
134 2
                    static::PREDLOJ => $prefix.($gender == static::FEMALE ? 'ьей' : 'ьем'),
135
                ];
136
            }
137
138
            switch ($gender) {
139 34 View Code Duplication
                case static::MALE:
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...
140 28
                    $prefix = S::slice($word, 0, -2);
141
                    return [
142 28
                        static::IMENIT => $word,
143 28
                        static::RODIT => $prefix.'ого',
144 28
                        static::DAT => $prefix.'ому',
145 28
                        static::VINIT => $word,
146 28
                        static::TVORIT => $prefix.'ым',
147 28
                        static::PREDLOJ => $prefix.'ом',
148
                    ];
149
150 6 View Code Duplication
                case static::FEMALE:
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...
151 2
                    $prefix = S::slice($word, 0, -2);
152
                    return [
153 2
                        static::IMENIT => $prefix.'ая',
154 2
                        static::RODIT => $prefix.'ой',
155 2
                        static::DAT => $prefix.'ой',
156 2
                        static::VINIT => $prefix.'ую',
157 2
                        static::TVORIT => $prefix.'ой',
158 2
                        static::PREDLOJ => $prefix.'ой',
159
                    ];
160
161 4 View Code Duplication
                case static::NEUTER:
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...
162 4
                    $prefix = S::slice($word, 0, -2);
163
                    return [
164 4
                        static::IMENIT => $prefix.'ое',
165 4
                        static::RODIT => $prefix.'ого',
166 4
                        static::DAT => $prefix.'ому',
167 4
                        static::VINIT => $prefix.'ое',
168 4
                        static::TVORIT => $prefix.'ым',
169 4
                        static::PREDLOJ => $prefix.'ом',
170
                    ];
171
172
                default:
173
                    throw new RuntimeException('Unreacheable');
174
            }
175
        }
176
177
        // compound numeral
178 20
        $ordinal_part = null;
179 20
        $ordinal_prefix = null;
180 20
        $result = [];
181
182
        // test for exponents. If smaller summand of number is an exponent, declinate it
183 20
        foreach (array_reverse(static::$exponents, true) as $word_number => $word) {
184 20
            if ($number >= $word_number && ($number % $word_number) == 0) {
185
                $count = floor($number / $word_number) % 1000;
186
                $number -= ($count * $word_number);
187
                foreach (array_reverse(static::$multipliers, true) as $multiplier => $multipliers_word) {
188
                    if ($count >= $multiplier) {
189
                        $ordinal_prefix .= $multipliers_word;
190
                        $count -= $multiplier;
191
                    }
192
                }
193
                $ordinal_part = static::getCases($word_number, $gender);
194
                foreach ($ordinal_part as $case => $ordinal_word) {
0 ignored issues
show
Bug introduced by
The expression $ordinal_part of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
195
                    $ordinal_part[$case] = $ordinal_prefix.$ordinal_part[$case];
196
                }
197
198 20
                break;
199
            }
200
        }
201
202
        // otherwise, test if smaller summand is just a number with it's own name
203 20
        if (empty($ordinal_part)) {
204
            // get the smallest number with it's own name
205 20
            foreach (static::$words as $word_number => $word) {
206 20
                if ($number >= $word_number) {
207 20
                    if ($word_number <= 9) {
208 20
                        if ($number % 10 == 0) {
209 4
                            continue;
210
                        }
211
                        // check for case when word_number smaller than should be used (e.g. 1,2,3 when it can be 4 (number: 344))
212 16
                        if (($number % 10) > $word_number) {
213 12
                            continue;
214
                        }
215
                        // check that there is no two-digits number with it's own name (e.g. 13 for 113)
216 16
                        if (isset(static::$words[$number % 100]) && $number % 100 > $word_number) {
217 16
                            continue;
218
                        }
219 10
                    } elseif ($word_number <= 90) {
220
                        // check for case when word_number smaller than should be used (e.g. 10, 11, 12 when it can be 13)
221 10
                        if (($number % 100) > $word_number) {
222 10
                            continue;
223
                        }
224
                    }
225 20
                    $ordinal_part = static::getCases($word_number, $gender);
226 20
                    $number -= $word_number;
227 20
                    break;
228
                }
229
            }
230
        }
231
232
        // if number has second summand, get cardinal form of it
233 20
        if ($number > 0) {
234 20
            $cardinal_part = CardinalNumeralGenerator::getCase($number, static::IMENIT, $gender);
235
236
            // make one array with cases and delete 'o/об' prepositional from all parts except the last one
237 20
            foreach ([static::IMENIT, static::RODIT, static::DAT, static::VINIT, static::TVORIT, static::PREDLOJ] as $case) {
238 20
                $result[$case] = $cardinal_part.' '.$ordinal_part[$case];
239
            }
240
        } else {
241
            $result = $ordinal_part;
242
        }
243
244 20
        return $result;
245
    }
246
247
    /**
248
     * @param int $number
249
     * @param string $case
250
     * @param string $gender
251
     * @return mixed
252
     * @throws \Exception
253
     */
254 18
    public static function getCase($number, $case, $gender = self::MALE)
255
    {
256 18
        $case = static::canonizeCase($case);
257 18
        $forms = static::getCases($number, $gender);
258 18
        return $forms[$case];
259
    }
260
}
261