NounPluralization   F
last analyzed

Complexity

Total Complexity 65

Size/Duplication

Total Lines 280
Duplicated Lines 15 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 98.32%

Importance

Changes 0
Metric Value
dl 42
loc 280
ccs 117
cts 119
cp 0.9832
rs 3.2
c 0
b 0
f 0
wmc 65
lcom 1
cbo 5

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getRunAwayVowelsList() 8 8 2
C pluralize() 16 38 12
B getNumeralForm() 0 15 8
A getCase() 0 6 1
A getCases() 0 30 4
A declinateAdjective() 0 13 3
F declinateSubstative() 18 85 35

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like NounPluralization often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use NounPluralization, and based on these observations, apply Extract Interface, too.

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 78 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 78
        $runawayVowelsNormalized = [];
50 78
        foreach (static::$runawayVowelsExceptions as $word) {
51 78
            $runawayVowelsNormalized[str_replace('*', null, $word)] = S::indexOf($word, '*') - 1;
52
        }
53 78
        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 56
    public static function pluralize($word, $count = 2, $animateness = false, $case = null)
68
    {
69
        // меняем местами аргументы, если они переданы в старом формате
70 56 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 56
        if ($case !== null)
75 3
            $case = static::canonizeCase($case);
76
77
        // для адъективных существительных правила склонения проще:
78
        // только две формы
79 56 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 54
        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 3 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 3
            return NounDeclension::getCase($word, $case, $animateness);
102
        else
103 3
            return NounPluralization::getCase($word, $case, $animateness);
104
    }
105
106
    /**
107
     * @param $count
108
     * @return int
109
     */
110 68
    public static function getNumeralForm($count)
111
    {
112 68
        if ($count > 100) {
113 42
            $count %= 100;
114
        }
115 68
        $ending = $count % 10;
116
117 68
        if (($count > 20 && $ending == 1) || $count == 1) {
118 38
            return static::ONE;
119 67
        } elseif (($count > 20 && in_array($ending, range(2, 4))) || in_array($count, range(2, 4))) {
120 47
            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 43
    public static function getCase($word, $case, $animateness = false)
134
    {
135 43
        $case = static::canonizeCase($case);
136 43
        $forms = static::getCases($word, $animateness);
137 43
        return $forms[$case];
138
    }
139
140
    /**
141
     * @param $word
142
     * @param bool $animateness
143
     * @return array
144
     */
145 89
    public static function getCases($word, $animateness = false)
146
    {
147 89
        $word = S::lower($word);
148
149 89
        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 89
        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 88
        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 78
        return static::declinateSubstative($word, $animateness);
174
    }
175
176
    /**
177
     * Склонение обычных существительных.
178
     * @param $word
179
     * @param $animateness
180
     * @return array
181
     */
182 78
    protected static function declinateSubstative($word, $animateness)
183
    {
184 78
        $prefix = S::slice($word, 0, -1);
185 78
        $last = S::slice($word, -1);
186
187 78
        $runaway_vowels_list = static::getRunAwayVowelsList();
188 78
        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 78
        if (($declension = NounDeclension::getDeclension($word)) == NounDeclension::SECOND_DECLENSION) {
194 49
            $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 49
                        || S::slice($word, -2, -1) == 'и'));
198 49
            $prefix = NounDeclension::getPrefixOfSecondDeclension($word, $last);
199 35
        } elseif ($declension == NounDeclension::FIRST_DECLENSION) {
200 31
            $soft_last = static::checkLastConsonantSoftness($word);
201 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...
202 4
            $soft_last = in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true);
203
        }
204
205 78
        $forms = [];
206
207 78
        if (in_array($last, ['ч', 'г'], true)
208 76
            || in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь', 'рь'], true)
209 78
            || (static::isVowel($last) && in_array(S::slice($word, -2, -1), ['ч', 'к'], true))) { // before ч, чь, сь, ч+vowel, к+vowel
210 33
            $forms[Cases::IMENIT] = $prefix.'и';
211 50
        } elseif (in_array($last, ['н', 'ц', 'р', 'т'], true)) {
212 18
            $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 78
        if (isset(static::$genitiveExceptions[$word])) {
219 10
            $forms[Cases::RODIT] = static::$genitiveExceptions[$word];
220 70
        } 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 62
        } 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 55
        } elseif (in_array($last, ['а'], true)) { // обида, ябеда
238 22
            $forms[Cases::RODIT] = $prefix;
239 39 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 38
        } elseif (RussianLanguage::isHissingConsonant($last) || ($soft_last && $last != 'й') || in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true)) {
242 14
            $forms[Cases::RODIT] = $prefix.'ей';
243 26 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 19
            $forms[Cases::RODIT] = $prefix.'ов';
247
        }
248
249
        // DAT
250 78
        $forms[Cases::DAT] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ям', $prefix.'ам');
251
252
        // VINIT
253 78
        $forms[Cases::VINIT] = NounDeclension::getVinitCaseByAnimateness($forms, $animateness);
254
255
        // TVORIT
256
        // my personal rule
257 78
        if ($last == 'ь' && $declension == NounDeclension::THIRD_DECLENSION && !in_array(S::slice($word, -2), ['чь', 'сь', 'ть', 'нь'], true)) {
258
            $forms[Cases::TVORIT] = $prefix.'ми';
259
        } else {
260 78
            $forms[Cases::TVORIT] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ями', $prefix.'ами');
261
        }
262
263
        // PREDLOJ
264 78
        $forms[Cases::PREDLOJ] = static::chooseVowelAfterConsonant($last, $soft_last && S::slice($word, -2, -1) != 'ч', $prefix.'ях', $prefix.'ах');
265 78
        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