ci4

Форк
0
/
inflector_helper.php 
339 строк · 10.5 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
// CodeIgniter Inflector Helpers
15

16
if (! function_exists('singular')) {
17
    /**
18
     * Singular
19
     *
20
     * Takes a plural word and makes it singular
21
     *
22
     * @param string $string Input string
23
     */
24
    function singular(string $string): string
25
    {
26
        $result = $string;
27

28
        if (! is_pluralizable($result)) {
29
            return $result;
30
        }
31

32
        // Arranged in order.
33
        $singularRules = [
34
            '/(matr)ices$/'                                                   => '\1ix',
35
            '/(vert|ind)ices$/'                                               => '\1ex',
36
            '/^(ox)en/'                                                       => '\1',
37
            '/(alias)es$/'                                                    => '\1',
38
            '/([octop|vir])i$/'                                               => '\1us',
39
            '/(cris|ax|test)es$/'                                             => '\1is',
40
            '/(shoe)s$/'                                                      => '\1',
41
            '/(o)es$/'                                                        => '\1',
42
            '/(bus|campus)es$/'                                               => '\1',
43
            '/([m|l])ice$/'                                                   => '\1ouse',
44
            '/(x|ch|ss|sh)es$/'                                               => '\1',
45
            '/(m)ovies$/'                                                     => '\1\2ovie',
46
            '/(s)eries$/'                                                     => '\1\2eries',
47
            '/([^aeiouy]|qu)ies$/'                                            => '\1y',
48
            '/([lr])ves$/'                                                    => '\1f',
49
            '/(tive)s$/'                                                      => '\1',
50
            '/(hive)s$/'                                                      => '\1',
51
            '/([^f])ves$/'                                                    => '\1fe',
52
            '/(^analy)ses$/'                                                  => '\1sis',
53
            '/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis',
54
            '/([ti])a$/'                                                      => '\1um',
55
            '/(p)eople$/'                                                     => '\1\2erson',
56
            '/(m)en$/'                                                        => '\1an',
57
            '/(s)tatuses$/'                                                   => '\1\2tatus',
58
            '/(c)hildren$/'                                                   => '\1\2hild',
59
            '/(n)ews$/'                                                       => '\1\2ews',
60
            '/(quiz)zes$/'                                                    => '\1',
61
            '/([^us])s$/'                                                     => '\1',
62
        ];
63

64
        foreach ($singularRules as $rule => $replacement) {
65
            if (preg_match($rule, $result)) {
66
                $result = preg_replace($rule, $replacement, $result);
67
                break;
68
            }
69
        }
70

71
        return $result;
72
    }
73
}
74

75
if (! function_exists('plural')) {
76
    /**
77
     * Plural
78
     *
79
     * Takes a singular word and makes it plural
80
     *
81
     * @param string $string Input string
82
     */
83
    function plural(string $string): string
84
    {
85
        $result = $string;
86

87
        if (! is_pluralizable($result)) {
88
            return $result;
89
        }
90

91
        $pluralRules = [
92
            '/(quiz)$/'               => '\1zes',    // quizzes
93
            '/^(ox)$/'                => '\1\2en', // ox
94
            '/([m|l])ouse$/'          => '\1ice', // mouse, louse
95
            '/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index
96
            '/(x|ch|ss|sh)$/'         => '\1es', // search, switch, fix, box, process, address
97
            '/([^aeiouy]|qu)y$/'      => '\1ies', // query, ability, agency
98
            '/(hive)$/'               => '\1s', // archive, hive
99
            '/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife
100
            '/sis$/'                  => 'ses', // basis, diagnosis
101
            '/([ti])um$/'             => '\1a', // datum, medium
102
            '/(p)erson$/'             => '\1eople', // person, salesperson
103
            '/(m)an$/'                => '\1en', // man, woman, spokesman
104
            '/(c)hild$/'              => '\1hildren', // child
105
            '/(buffal|tomat)o$/'      => '\1\2oes', // buffalo, tomato
106
            '/(bu|campu)s$/'          => '\1\2ses', // bus, campus
107
            '/(alias|status|virus)$/' => '\1es', // alias
108
            '/(octop)us$/'            => '\1i', // octopus
109
            '/(ax|cris|test)is$/'     => '\1es', // axis, crisis
110
            '/s$/'                    => 's', // no change (compatibility)
111
            '/$/'                     => 's',
112
        ];
113

114
        foreach ($pluralRules as $rule => $replacement) {
115
            if (preg_match($rule, $result)) {
116
                $result = preg_replace($rule, $replacement, $result);
117
                break;
118
            }
119
        }
120

121
        return $result;
122
    }
123
}
124

125
if (! function_exists('counted')) {
126
    /**
127
     * Counted
128
     *
129
     * Takes a number and a word to return the plural or not
130
     * E.g. 0 cats, 1 cat, 2 cats, ...
131
     *
132
     * @param int    $count  Number of items
133
     * @param string $string Input string
134
     */
135
    function counted(int $count, string $string): string
136
    {
137
        $result = "{$count} ";
138

139
        return $result . ($count === 1 ? singular($string) : plural($string));
140
    }
141
}
142

143
if (! function_exists('camelize')) {
144
    /**
145
     * Camelize
146
     *
147
     * Takes multiple words separated by spaces or
148
     * underscores and converts them to camel case.
149
     *
150
     * @param string $string Input string
151
     */
152
    function camelize(string $string): string
153
    {
154
        return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[\s_]+/', ' ', $string))));
155
    }
156
}
157

158
if (! function_exists('pascalize')) {
159
    /**
160
     * Pascalize
161
     *
162
     * Takes multiple words separated by spaces or
163
     * underscores and converts them to Pascal case,
164
     * which is camel case with an uppercase first letter.
165
     *
166
     * @param string $string Input string
167
     */
168
    function pascalize(string $string): string
169
    {
170
        return ucfirst(camelize($string));
171
    }
172
}
173

174
if (! function_exists('underscore')) {
175
    /**
176
     * Underscore
177
     *
178
     * Takes multiple words separated by spaces and underscores them
179
     *
180
     * @param string $string Input string
181
     */
182
    function underscore(string $string): string
183
    {
184
        $replacement = trim($string);
185

186
        return preg_replace('/[\s]+/', '_', $replacement);
187
    }
188
}
189

190
if (! function_exists('decamelize')) {
191
    /**
192
     * Decamelize
193
     *
194
     * Takes multiple words separated by camel case and
195
     * underscores them.
196
     *
197
     * @param string $string Input string
198
     */
199
    function decamelize(string $string): string
200
    {
201
        return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', trim($string)));
202
    }
203
}
204

205
if (! function_exists('humanize')) {
206
    /**
207
     * Humanize
208
     *
209
     * Takes multiple words separated by the separator,
210
     * camelizes and changes them to spaces
211
     *
212
     * @param string $string    Input string
213
     * @param string $separator Input separator
214
     */
215
    function humanize(string $string, string $separator = '_'): string
216
    {
217
        $replacement = trim($string);
218

219
        return ucwords(preg_replace('/[' . $separator . ']+/', ' ', $replacement));
220
    }
221
}
222

223
if (! function_exists('is_pluralizable')) {
224
    /**
225
     * Checks if the given word has a plural version.
226
     *
227
     * @param string $word Word to check
228
     */
229
    function is_pluralizable(string $word): bool
230
    {
231
        $uncountables = in_array(
232
            strtolower($word),
233
            [
234
                'advice',
235
                'bravery',
236
                'butter',
237
                'chaos',
238
                'clarity',
239
                'coal',
240
                'courage',
241
                'cowardice',
242
                'curiosity',
243
                'education',
244
                'equipment',
245
                'evidence',
246
                'fish',
247
                'fun',
248
                'furniture',
249
                'greed',
250
                'help',
251
                'homework',
252
                'honesty',
253
                'information',
254
                'insurance',
255
                'jewelry',
256
                'knowledge',
257
                'livestock',
258
                'love',
259
                'luck',
260
                'marketing',
261
                'meta',
262
                'money',
263
                'mud',
264
                'news',
265
                'patriotism',
266
                'racism',
267
                'rice',
268
                'satisfaction',
269
                'scenery',
270
                'series',
271
                'sexism',
272
                'silence',
273
                'species',
274
                'spelling',
275
                'sugar',
276
                'water',
277
                'weather',
278
                'wisdom',
279
                'work',
280
            ],
281
            true
282
        );
283

284
        return ! $uncountables;
285
    }
286
}
287

288
if (! function_exists('dasherize')) {
289
    /**
290
     * Replaces underscores with dashes in the string.
291
     *
292
     * @param string $string Input string
293
     */
294
    function dasherize(string $string): string
295
    {
296
        return str_replace('_', '-', $string);
297
    }
298
}
299

300
if (! function_exists('ordinal')) {
301
    /**
302
     * Returns the suffix that should be added to a
303
     * number to denote the position in an ordered
304
     * sequence such as 1st, 2nd, 3rd, 4th.
305
     *
306
     * @param int $integer The integer to determine the suffix
307
     */
308
    function ordinal(int $integer): string
309
    {
310
        $suffixes = [
311
            'th',
312
            'st',
313
            'nd',
314
            'rd',
315
            'th',
316
            'th',
317
            'th',
318
            'th',
319
            'th',
320
            'th',
321
        ];
322

323
        return $integer % 100 >= 11 && $integer % 100 <= 13 ? 'th' : $suffixes[$integer % 10];
324
    }
325
}
326

327
if (! function_exists('ordinalize')) {
328
    /**
329
     * Turns a number into an ordinal string used
330
     * to denote the position in an ordered sequence
331
     * such as 1st, 2nd, 3rd, 4th.
332
     *
333
     * @param int $integer The integer to ordinalize
334
     */
335
    function ordinalize(int $integer): string
336
    {
337
        return $integer . ordinal($integer);
338
    }
339
}
340

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.