NounPluralization::declinateSubstative()   F
last analyzed

Complexity

Conditions 35
Paths 1008

Size

Total Lines 85

Duplication

Lines 15
Ratio 17.65 %

Code Coverage

Tests 52
CRAP Score 35.0082

Importance

Changes 0
Metric Value
cc 35
nc 1008
nop 2
dl 15
loc 85
ccs 52
cts 53
cp 0.9811
crap 35.0082
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace morphos\Russian;
3
4
use morphos\S;
5
6
/**
7
 * Rules are from http://morpher.ru/Russian/Noun.aspx
8
 */
9
class NounPluralization extends \morphos\BasePluralization implements Cases
10
{
11
    use RussianLanguage, CasesHelper;
12
13
    const ONE = 1;
14
    const TWO_FOUR = 2;
15
    const FIVE_OTHER = 3;
16
17
    protected static $abnormalExceptions = [
18
        'человек' => ['люди', 'человек', 'людям', 'людей', 'людьми', 'людях'],
19
    ];
20
21
    protected static $neuterExceptions = [
22
        'поле',
23
        'море',
24
    ];
25
26
    protected static $genitiveExceptions = [
27
        'письмо' => 'писем',
28
        'пятно' => 'пятен',
29
        'кресло' => 'кресел',
30
        'коромысло' => 'коромысел',
31
        'ядро' => 'ядер',
32
        'блюдце' => 'блюдец',
33
        'полотенце' => 'полотенец',
34
        'гривна' => 'гривен',
35
        'год' => 'лет',
36
    ];
37
38
    protected static $runawayVowelsExceptions = [
39
        'писе*ц',
40
        'песе*ц',
41
        'глото*к',
42
    ];
43
44
    /**
45
     * @return array|bool
46
     */
47 77 View Code Duplication
    protected static function getRunAwayVowelsList()
0 ignored issues
show
Duplication introduced by wapmorgan
This method seems to be duplicated in 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...
48
    {
49 77
        $runawayVowelsNormalized = [];
50 77
        foreach (static::$runawayVowelsExceptions as $word) {
51 77
            $runawayVowelsNormalized[str_replace('*', null, $word)] = S::indexOf($word, '*') - 1;
52
        }
53 77
        return $runawayVowelsNormalized;
54
    }
55
56
    /**
57
     * Склонение существительного для сочетания с числом (кол-вом предметов).
58
     *
59
     * @param string|int $word        Название предмета
60
     * @param int|string $count       Количество предметов
61
     * @param bool       $animateness Признак одушевленности
62
     * @param string     $case        Род существительного
63
     *
64
     * @return string
65
     * @throws \Exception
66
     */
67 55
    public static function pluralize($word, $count = 2, $animateness = false, $case = null)
68
    {
69
        // меняем местами аргументы, если они переданы в старом формате
70 55 View Code Duplication
        if (is_string($count) && is_numeric($word)) {
0 ignored issues
show
Duplication introduced by wapmorgan
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...
71 1
            list($count, $word) = [$word, $count];
72
        }
73
74 55
        if ($case !== null)
75 2
            $case = static::canonizeCase($case);
76
77
        // для адъективных существительных правила склонения проще:
78
        // только две формы
79 55 View Code Duplication
        if (static::isAdjectiveNoun($word)) {
0 ignored issues
show
Duplication introduced by wapmorgan
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...
80 3
            if (static::getNumeralForm($count) == static::ONE)
81 2
                return $word;
82
            else
83 3
                return NounPluralization::getCase($word,
84 3
                    $case !== null
85
                        ? $case
86 3
                        : static::RODIT, $animateness);
87
        }
88
89 53
        if ($case === null) {
90 51
            switch (static::getNumeralForm($count)) {
91 51
                case static::ONE:
92 29
                    return $word;
93 51
                case static::TWO_FOUR:
94 36
                    return NounDeclension::getCase($word, static::RODIT, $animateness);
95 38
                case static::FIVE_OTHER:
96 38
                    return NounPluralization::getCase($word, static::RODIT, $animateness);
97
            }
98
        }
99
100 2 View Code Duplication
        if (static::getNumeralForm($count) == static::ONE)
0 ignored issues
show
Duplication introduced by wapmorgan
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...
101 2
            return NounDeclension::getCase($word, $case, $animateness);
102
        else
103 2
            return NounPluralization::getCase($word, $case, $animateness);
104
    }
105
106
    /**
107
     * @param $count
108
     * @return int
109
     */
110 67
    public static function getNumeralForm($count)
111
    {
112 67
        if ($count > 100) {
113 41
            $count %= 100;
114
        }
115 67
        $ending = $count % 10;
116
117 67
        if (($count > 20 && $ending == 1) || $count == 1) {
118 37
            return static::ONE;
119 66
        } elseif (($count > 20 && in_array($ending, range(2, 4))) || in_array($count, range(2, 4))) {
120 46
            return static::TWO_FOUR;
121
        } else {
122 50
            return static::FIVE_OTHER;
123
        }
124
    }
125
126
    /**
127
     * @param $word
128
     * @param $case
129
     * @param bool $animateness
130
     * @return string
131
     * @throws \Exception
132
     */
133 42
    public static function getCase($word, $case, $animateness = false)
134
    {
135 42
        $case = static::canonizeCase($case);
136 42
        $forms = static::getCases($word, $animateness);
137 42
        return $forms[$case];
138
    }
139
140
    /**
141
     * @param $word
142
     * @param bool $animateness
143
     * @return array
144
     */
145 88
    public static function getCases($word, $animateness = false)
146
    {
147 88
        $word = S::lower($word);
148
149 88
        if (in_array($word, NounDeclension::$immutableWords, true)) {
150
            return [
151 1
                static::IMENIT => $word,
152 1
                static::RODIT => $word,
153 1
                static::DAT => $word,
154 1
                static::VINIT => $word,
155 1
                static::TVORIT => $word,
156 1
                static::PREDLOJ => $word,
157
            ];
158
        }
159
160 88
        if (isset(static::$abnormalExceptions[$word])) {
161 1
            return array_combine(
162 1
                [static::IMENIT, static::RODIT, static::DAT, static::VINIT, static::TVORIT, static::PREDLOJ],
163 1
                static::$abnormalExceptions[$word]);
164
        }
165
166
        // Адъективное склонение (Сущ, образованные от прилагательных и причастий)
167
        // Пример: прохожий, существительное
168 87
        if (static::isAdjectiveNoun($word)) {
0 ignored issues
show
Bug introduced by wapmorgan
It seems like $word defined by \morphos\S::lower($word) on line 147 can also be of type boolean; however, morphos\Russian\RussianLanguage::isAdjectiveNoun() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
169 11
            return static::declinateAdjective($word, $animateness);
170
        }
171
172
        // Субстантивное склонение (существительные)
173 77
        return static::declinateSubstative($word, $animateness);
174
    }
175
176
    /**
177
     * Склонение обычных существительных.
178
     * @param $word
179
     * @param $animateness
180
     * @return array
181
     */
182 77
    protected static function declinateSubstative($word, $animateness)
183
    {
184 77
        $prefix = S::slice($word, 0, -1);
185 77
        $last = S::slice($word, -1);
186
187 77
        $runaway_vowels_list = static::getRunAwayVowelsList();
188 77
        if (isset($runaway_vowels_list[$word])) {
189 1
            $vowel_offset = $runaway_vowels_list[$word];
190 1
            $word = S::slice($word, 0, $vowel_offset) . S::slice($word, $vowel_offset + 1);
191
        }
192
193 77
        if (($declension = NounDeclension::getDeclension($word)) == NounDeclension::SECOND_DECLENSION) {
194 48
            $soft_last = $last == 'й' || (in_array($last, ['ь', 'е', 'ё', 'ю', 'я'], true)
195
                    && ((
196 14
                        static::isConsonant(S::slice($word, -2, -1)) && !static::isHissingConsonant(S::slice($word, -2, -1)))
197 48
                        || S::slice($word, -2, -1) == 'и'));
198 48
            $prefix = NounDeclension::getPrefixOfSecondDeclension($word, $last);
199 35
        } elseif ($declension == NounDeclension::FIRST_DECLENSION) {
200 31
            $soft_last = static::checkLastConsonantSoftness($word);
201
        } else {
202 4
            $soft_last = in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true);
203
        }
204
205 77
        $forms = [];
206
207 77
        if (in_array($last, ['ч', 'г'], true)
208 75
            || in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь', 'рь'], true)
209 77
            || (static::isVowel($last) && in_array(S::slice($word, -2, -1), ['ч', 'к'], true))) { // before ч, чь, сь, ч+vowel, к+vowel
210 33
            $forms[Cases::IMENIT] = $prefix.'и';
211 49
        } elseif (in_array($last, ['н', 'ц', 'р', 'т'], true)) {
212 17
            $forms[Cases::IMENIT] = $prefix.'ы';
213 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by wapmorgan
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...
214 35
            $forms[Cases::IMENIT] = static::chooseVowelAfterConsonant($last, $soft_last, $prefix.'я', $prefix.'а');
215
        }
216
217
        // RODIT
218 77
        if (isset(static::$genitiveExceptions[$word])) {
219 10
            $forms[Cases::RODIT] = static::$genitiveExceptions[$word];
220 69
        } elseif (in_array($last, ['о', 'е'], true)) {
221
            // exceptions
222 8
            if (in_array($word, static::$neuterExceptions, true)) {
223 3
                $forms[Cases::RODIT] = $prefix.'ей';
224 5 View Code Duplication
            } elseif (S::slice($word, -2, -1) == 'и') {
0 ignored issues
show
Duplication introduced by wapmorgan
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...
225 2
                $forms[Cases::RODIT] = $prefix.'й';
226
            } else {
227 8
                $forms[Cases::RODIT] = $prefix;
228
            }
229 61
        } elseif (S::slice($word, -2) == 'ка' && S::slice($word, -3, -2) !== 'и') { // words ending with -ка: чашка, вилка, ложка, тарелка, копейка, батарейка
230 7
            if (S::slice($word, -3, -2) == 'л') {
231 2
                $forms[Cases::RODIT] = S::slice($word, 0, -2).'ок';
232 5 View Code Duplication
            } elseif (S::slice($word, -3, -2) == 'й') {
0 ignored issues
show
Duplication introduced by wapmorgan
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...
233 3
                $forms[Cases::RODIT] = S::slice($word, 0, -3).'ек';
234
            } else {
235 7
                $forms[Cases::RODIT] = S::slice($word, 0, -2).'ек';
236
            }
237 54
        } elseif (in_array($last, ['а'], true)) { // обида, ябеда
238 22
            $forms[Cases::RODIT] = $prefix;
239 38 View Code Duplication
        } elseif (in_array($last, ['я'], true)) { // молния
0 ignored issues
show
Duplication introduced by wapmorgan
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...
240 1
            $forms[Cases::RODIT] = $prefix.'й';
241 37
        } elseif (RussianLanguage::isHissingConsonant($last) || ($soft_last && $last != 'й') || in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true)) {
242 14
            $forms[Cases::RODIT] = $prefix.'ей';
243 25 View Code Duplication
        } elseif ($last == 'й' || S::slice($word, -2) == 'яц') { // месяц
0 ignored issues
show
Duplication introduced by wapmorgan
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...
244 7
            $forms[Cases::RODIT] = $prefix.'ев';
245
        } else { // (static::isConsonant($last) && !RussianLanguage::isHissingConsonant($last))
246 18
            $forms[Cases::RODIT] = $prefix.'ов';
247
        }
248
249
        // DAT
250 77
        $forms[Cases::DAT] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ям', $prefix.'ам');
251
252
        // VINIT
253 77
        $forms[Cases::VINIT] = NounDeclension::getVinitCaseByAnimateness($forms, $animateness);
254
255
        // TVORIT
256
        // my personal rule
257 77
        if ($last == 'ь' && $declension == NounDeclension::THIRD_DECLENSION && !in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true)) {
258
            $forms[Cases::TVORIT] = $prefix.'ми';
259
        } else {
260 77
            $forms[Cases::TVORIT] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ями', $prefix.'ами');
261
        }
262
263
        // PREDLOJ
264 77
        $forms[Cases::PREDLOJ] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ях', $prefix.'ах');
265 77
        return $forms;
266
    }
267
268
    /**
269
     * Склонение существительных, образованных от прилагательных и причастий.
270
     * Rules are from http://rusgram.narod.ru/1216-1231.html
271
     * @param $word
272
     * @param $animateness
273
     * @return array
274
     */
275 11
    protected static function declinateAdjective($word, $animateness)
276
    {
277 11
        $prefix = S::slice($word, 0, -2);
278 11
        $vowel = static::isHissingConsonant(S::slice($prefix, -1)) ? 'и' : 'ы';
0 ignored issues
show
Security Bug introduced by wapmorgan
It seems like $prefix defined by \morphos\S::slice($word, 0, -2) on line 277 can also be of type false; however, morphos\S::slice() does only seem to accept string, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
279
        return [
280 11
            Cases::IMENIT => $prefix.$vowel.'е',
281 11
            Cases::RODIT => $prefix.$vowel.'х',
282 11
            Cases::DAT => $prefix.$vowel.'м',
283 11
            Cases::VINIT => $prefix.$vowel.($animateness ? 'х' : 'е'),
284 11
            Cases::TVORIT => $prefix.$vowel.'ми',
285 11
            Cases::PREDLOJ => $prefix.$vowel.'х',
286
        ];
287
    }
288
}
289