Passed
Push — master ( aae6d5...8ff6a9 )
by Alexander
01:59
created

InflectorTest::camel2idProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 36
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 28
nc 1
nop 0
dl 0
loc 36
rs 9.472
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Strings\Tests;
4
5
use PHPUnit\Framework\TestCase;
6
use Yiisoft\Strings\Inflector;
7
8
final class InflectorTest extends TestCase
9
{
10
    private function getTestDataForPluralize(): array
11
    {
12
        return [
13
            'access' => 'accesses',
14
            'address' => 'addresses',
15
            'move' => 'moves',
16
            'foot' => 'feet',
17
            'child' => 'children',
18
            'human' => 'humans',
19
            'man' => 'men',
20
            'staff' => 'staff',
21
            'tooth' => 'teeth',
22
            'person' => 'people',
23
            'mouse' => 'mice',
24
            'touch' => 'touches',
25
            'hash' => 'hashes',
26
            'shelf' => 'shelves',
27
            'potato' => 'potatoes',
28
            'bus' => 'buses',
29
            'test' => 'tests',
30
            'car' => 'cars',
31
            'netherlands' => 'netherlands',
32
            'currency' => 'currencies',
33
            'criterion' => 'criteria',
34
            'analysis' => 'analyses',
35
            'datum' => 'data',
36
            'schema' => 'schemas',
37
        ];
38
    }
39
40
    private function getTestDataForSignularize(): array
41
    {
42
        return array_flip($this->getTestDataForPluralize());
43
    }
44
45
    public function testPluralize(): void
46
    {
47
        $inflector = new Inflector();
48
49
        foreach ($this->getTestDataForPluralize() as $testIn => $testOut) {
50
            $this->assertEquals($testOut, $inflector->pluralize($testIn), 'Should be ' . $testIn . ' -> ' . $testOut);
51
            $this->assertEquals(ucfirst($testOut), ucfirst($inflector->pluralize($testIn)));
52
        }
53
    }
54
55
    public function testSingularize(): void
56
    {
57
        $inflector = new Inflector();
58
59
        foreach ($this->getTestDataForSignularize() as $testIn => $testOut) {
60
            $this->assertEquals($testOut, $inflector->singularize($testIn), 'Should be ' . $testIn . ' -> ' . $testOut);
61
            $this->assertEquals(ucfirst($testOut), ucfirst($inflector->singularize($testIn)));
62
        }
63
    }
64
65
    public function testTitleize(): void
66
    {
67
        $inflector = new Inflector();
68
69
        $this->assertEquals('Me my self and i', $inflector->titleize('MeMySelfAndI'));
70
        $this->assertEquals('Me My Self And I', $inflector->titleize('MeMySelfAndI', true));
71
        $this->assertEquals('Треба Більше Тестів!', $inflector->titleize('ТребаБільшеТестів!', true));
72
    }
73
74
    public function testCamelize(): void
75
    {
76
        $inflector = new Inflector();
77
78
        $this->assertEquals('MeMySelfAndI', $inflector->camelize('me my_self-andI'));
79
        $this->assertEquals('QweQweEwq', $inflector->camelize('qwe qwe^ewq'));
80
        $this->assertEquals('ВідомоЩоТестиЗберігатьНашіНЕРВИ', $inflector->camelize('Відомо, що тести зберігать наші НЕРВИ! 🙃'));
81
    }
82
83
    public function testUnderscore(): void
84
    {
85
        $inflector = new Inflector();
86
87
        $this->assertEquals('me_my_self_and_i', $inflector->underscore('MeMySelfAndI'));
88
        $this->assertEquals('кожний_тест_особливий', $inflector->underscore('КожнийТестОсобливий'));
89
    }
90
91
    public function testCamel2words(): void
92
    {
93
        $inflector = new Inflector();
94
95
        $this->assertEquals('Camel Case', $inflector->camel2words('camelCase'));
96
        $this->assertEquals('Lower Case', $inflector->camel2words('lower_case'));
97
        $this->assertEquals('Tricky Stuff It Is Testing', $inflector->camel2words(' tricky_stuff.it-is testing... '));
98
        $this->assertEquals('І Це Дійсно Так!', $inflector->camel2words('ІЦеДійсноТак!'));
99
    }
100
101
    /**
102
     * @dataProvider camel2idProvider()
103
     */
104
    public function testCamel2id(string $expectedResult, array $arguments): void
105
    {
106
        $inflector = new Inflector();
107
108
        $result = call_user_func_array([$inflector, 'camel2id'], $arguments);
109
110
        $this->assertEquals($expectedResult, $result);
111
    }
112
113
114
    /**
115
     * @dataProvider id2camelProvider()
116
     */
117
    public function testId2camel(string $expectedResult, array $arguments): void
118
    {
119
        $inflector = new Inflector();
120
121
        $result = call_user_func_array([$inflector, 'id2camel'], $arguments);
122
123
        $this->assertEquals($expectedResult, $result);
124
    }
125
126
    public function testHumanize(): void
127
    {
128
        $inflector = new Inflector();
129
130
        $this->assertEquals('Me my self and i', $inflector->humanize('me_my_self_and_i'));
131
        $this->assertEquals('Me My Self And I', $inflector->humanize('me_my_self_and_i', true));
132
        $this->assertEquals('Але й веселі ці ваші тести', $inflector->humanize('але_й_веселі_ці_ваші_тести'));
133
    }
134
135
    public function testVariablize(): void
136
    {
137
        $inflector = new Inflector();
138
139
        $this->assertEquals('customerTable', $inflector->variablize('customer_table'));
140
        $this->assertEquals('ひらがなHepimiz', $inflector->variablize('ひらがな_hepimiz'));
141
    }
142
143
    public function testTableize(): void
144
    {
145
        $inflector = new Inflector();
146
147
        $this->assertEquals('customer_tables', $inflector->tableize('customerTable'));
148
    }
149
150
    public function slugCommonsDataProvider(): array
151
    {
152
        return [
153
            ['', ''],
154
            ['hello world 123', 'hello-world-123'],
155
            ['remove.!?[]{}…symbols', 'remove-symbols'],
156
            ['minus-sign', 'minus-sign'],
157
            ['mdash—sign', 'mdash-sign'],
158
            ['ndash–sign', 'ndash-sign'],
159
            ['áàâéèêíìîóòôúùûã', 'aaaeeeiiiooouuua'],
160
            ['älä lyö ääliö ööliä läikkyy', 'ala-lyo-aalio-oolia-laikkyy'],
161
            'start' => ['---test', 'test'],
162
            'end' => ['test---', 'test'],
163
            'startAndEnd' => ['---test---', 'test'],
164
            'repeated' => ['hello----world', 'hello-world'],
165
            ['dont replace_replacement', 'dont_replace_replacement', '_'],
166
            ['_remove trailing replacements_', 'remove_trailing_replacements', '_'],
167
            ['this is REP-lacement', 'thisrepisreprepreplacement', 'REP'],
168
            ['0-100 Km/h', '0_100_km_h', '_'],
169
            ['test empty', 'testempty', ''],
170
        ];
171
    }
172
173
    /**
174
     * @dataProvider slugCommonsDataProvider
175
     */
176
    public function testSlugCommons(string $input, string $expected, string $replacement = '-'): void
177
    {
178
        $inflector = new Inflector();
179
        if (extension_loaded('intl')) {
180
            $this->assertEquals($expected, $inflector->slug($input, $replacement));
181
        }
182
        $this->assertEquals($expected, $inflector->withoutIntl()->slug($input, $replacement));
183
    }
184
185
    public function testSlugIntl(): void
186
    {
187
        if (!extension_loaded('intl')) {
188
            $this->markTestSkipped('intl extension is required.');
189
        }
190
191
        // Some test strings are from https://github.com/bergie/midgardmvc_helper_urlize. Thank you, Henri Bergius!
192
        $data = [
193
            // Korean
194
            '해동검도' => 'haedong-geomdo',
195
            // Hiragana
196
            'ひらがな' => 'hiragana',
197
            // Georgian
198
            'საქართველო' => 'sakartvelo',
199
            // Arabic
200
            'العربي' => 'alrby',
201
            'عرب' => 'rb',
202
            // Hebrew
203
            'עִבְרִית' => 'iberiyt',
204
            // Turkish
205
            'Sanırım hepimiz aynı şeyi düşünüyoruz.' => 'sanirim-hepimiz-ayni-seyi-dusunuyoruz',
206
            // Russian
207
            'недвижимость' => 'nedvizimost',
208
            'Контакты' => 'kontakty',
209
            // Chinese
210
            '美国' => 'mei-guo',
211
            // Estonian
212
            'Jääär' => 'jaaar',
213
        ];
214
215
        $inflector = new Inflector();
216
217
        foreach ($data as $source => $expected) {
218
            $this->assertEquals($expected, $inflector->slug($source));
219
        }
220
    }
221
222
    public function testTransliterateStrict(): void
223
    {
224
        if (!extension_loaded('intl')) {
225
            $this->markTestSkipped('intl extension is required.');
226
        }
227
228
        // Some test strings are from https://github.com/bergie/midgardmvc_helper_urlize. Thank you, Henri Bergius!
229
        $data = [
230
            // Korean
231
            '해동검도' => 'haedong-geomdo',
232
            // Hiragana
233
            'ひらがな' => 'hiragana',
234
            // Georgian
235
            'საქართველო' => 'sakartvelo',
236
            // Arabic
237
            'العربي' => 'ạlʿrby',
238
            'عرب' => 'ʿrb',
239
            // Hebrew
240
            'עִבְרִית' => 'ʻibĕriyţ',
241
            // Turkish
242
            'Sanırım hepimiz aynı şeyi düşünüyoruz.' => 'Sanırım hepimiz aynı şeyi düşünüyoruz.',
243
244
            // Russian
245
            'недвижимость' => 'nedvižimostʹ',
246
            'Контакты' => 'Kontakty',
247
248
            // Ukrainian
249
            'Українська: ґанок, європа' => 'Ukraí̈nsʹka: g̀anok, êvropa',
250
251
            // Serbian
252
            'Српска: ђ, њ, џ!' => 'Srpska: đ, n̂, d̂!',
253
254
            // Spanish
255
            '¿Español?' => '¿Español?',
256
            // Chinese
257
            '美国' => 'měi guó',
258
        ];
259
260
        $inflector = new Inflector();
261
262
        foreach ($data as $source => $expected) {
263
            $this->assertEquals($expected, $inflector->transliterate($source, Inflector::TRANSLITERATE_STRICT));
264
        }
265
    }
266
267
    public function testTransliterateMedium(): void
268
    {
269
        if (!extension_loaded('intl')) {
270
            $this->markTestSkipped('intl extension is required.');
271
        }
272
273
        // Some test strings are from https://github.com/bergie/midgardmvc_helper_urlize. Thank you, Henri Bergius!
274
        $data = [
275
            // Korean
276
            '해동검도' => ['haedong-geomdo'],
277
            // Hiragana
278
            'ひらがな' => ['hiragana'],
279
            // Georgian
280
            'საქართველო' => ['sakartvelo'],
281
            // Arabic
282
            'العربي' => ['alʿrby'],
283
            'عرب' => ['ʿrb'],
284
            // Hebrew
285
            'עִבְרִית' => ['\'iberiyt', 'ʻiberiyt'],
286
            // Turkish
287
            'Sanırım hepimiz aynı şeyi düşünüyoruz.' => ['Sanirim hepimiz ayni seyi dusunuyoruz.'],
288
289
            // Russian
290
            'недвижимость' => ['nedvizimost\'', 'nedvizimostʹ'],
291
            'Контакты' => ['Kontakty'],
292
293
            // Ukrainian
294
            'Українська: ґанок, європа' => ['Ukrainsʹka: ganok, evropa', 'Ukrains\'ka: ganok, evropa'],
295
296
            // Serbian
297
            'Српска: ђ, њ, џ!' => ['Srpska: d, n, d!'],
298
299
            // Spanish
300
            '¿Español?' => ['¿Espanol?'],
301
            // Chinese
302
            '美国' => ['mei guo'],
303
        ];
304
305
        $inflector = new Inflector();
306
307
        foreach ($data as $source => $allowed) {
308
            $this->assertIsOneOf($inflector->transliterate($source, Inflector::TRANSLITERATE_MEDIUM), $allowed);
309
        }
310
    }
311
312
    public function testTransliterateLoose(): void
313
    {
314
        if (!extension_loaded('intl')) {
315
            $this->markTestSkipped('intl extension is required.');
316
        }
317
318
        // Some test strings are from https://github.com/bergie/midgardmvc_helper_urlize. Thank you, Henri Bergius!
319
        $data = [
320
            // Korean
321
            '해동검도' => ['haedong-geomdo'],
322
            // Hiragana
323
            'ひらがな' => ['hiragana'],
324
            // Georgian
325
            'საქართველო' => ['sakartvelo'],
326
            // Arabic
327
            'العربي' => ['alrby'],
328
            'عرب' => ['rb'],
329
            // Hebrew
330
            'עִבְרִית' => ['\'iberiyt', 'iberiyt'],
331
            // Turkish
332
            'Sanırım hepimiz aynı şeyi düşünüyoruz.' => ['Sanirim hepimiz ayni seyi dusunuyoruz.'],
333
334
            // Russian
335
            'недвижимость' => ['nedvizimost\'', 'nedvizimost'],
336
            'Контакты' => ['Kontakty'],
337
338
            // Ukrainian
339
            'Українська: ґанок, європа' => ['Ukrainska: ganok, evropa', 'Ukrains\'ka: ganok, evropa'],
340
341
            // Serbian
342
            'Српска: ђ, њ, џ!' => ['Srpska: d, n, d!'],
343
344
            // Spanish
345
            '¿Español?' => ['Espanol?'],
346
            // Chinese
347
            '美国' => ['mei guo'],
348
        ];
349
350
        $inflector = new Inflector();
351
352
        foreach ($data as $source => $allowed) {
353
            $this->assertIsOneOf($inflector->transliterate($source, Inflector::TRANSLITERATE_LOOSE), $allowed);
354
        }
355
    }
356
357
    public function testSlugPhp(): void
358
    {
359
        $data = [
360
            'we have недвижимость' => 'we-have',
361
        ];
362
363
        $inflector = (new Inflector())->withoutIntl();
364
365
        foreach ($data as $source => $expected) {
366
            $this->assertEquals($expected, $inflector->slug($source));
367
        }
368
    }
369
370
    public function testClassify(): void
371
    {
372
        $inflector = new Inflector();
373
374
        $this->assertEquals('CustomerTable', $inflector->classify('customer_tables'));
375
    }
376
377
    public function testOrdinalize(): void
378
    {
379
        $inflector = new Inflector();
380
381
        $this->assertEquals('21st', $inflector->ordinalize('21'));
382
        $this->assertEquals('22nd', $inflector->ordinalize('22'));
383
        $this->assertEquals('23rd', $inflector->ordinalize('23'));
384
        $this->assertEquals('24th', $inflector->ordinalize('24'));
385
        $this->assertEquals('25th', $inflector->ordinalize('25'));
386
        $this->assertEquals('111th', $inflector->ordinalize('111'));
387
        $this->assertEquals('113th', $inflector->ordinalize('113'));
388
    }
389
390
    public function testSentence(): void
391
    {
392
        $inflector = new Inflector();
393
394
        $array = [];
395
        $this->assertEquals('', $inflector->sentence($array));
396
397
        $array = ['Spain'];
398
        $this->assertEquals('Spain', $inflector->sentence($array));
399
400
        $array = ['Spain', 'France'];
401
        $this->assertEquals('Spain and France', $inflector->sentence($array));
402
403
        $array = ['Spain', 'France', 'Italy'];
404
        $this->assertEquals('Spain, France and Italy', $inflector->sentence($array));
405
406
        $array = ['Spain', 'France', 'Italy', 'Germany'];
407
        $this->assertEquals('Spain, France, Italy and Germany', $inflector->sentence($array));
408
409
        $array = ['Spain', 'France'];
410
        $this->assertEquals('Spain or France', $inflector->sentence($array, ' or '));
411
412
        $array = ['Spain', 'France', 'Italy'];
413
        $this->assertEquals('Spain, France or Italy', $inflector->sentence($array, ' or '));
414
415
        $array = ['Spain', 'France'];
416
        $this->assertEquals('Spain and France', $inflector->sentence($array, ' and ', ' or ', ' - '));
417
418
        $array = ['Spain', 'France', 'Italy'];
419
        $this->assertEquals('Spain - France or Italy', $inflector->sentence($array, ' and ', ' or ', ' - '));
420
    }
421
422
    /** Asserts that value is one of expected values.
423
     *
424
     * @param mixed $actual
425
     * @param array $expected
426
     * @param string $message
427
     */
428
    private function assertIsOneOf($actual, array $expected, $message = ''): void
429
    {
430
        self::assertThat($actual, new IsOneOfAssert($expected), $message);
431
    }
432
433
    public function camel2idProvider(): array
434
    {
435
        return [
436
            ['photo\\album-controller', ['Photo\\AlbumController', '-', false]],
437
            ['photo\\album-controller', ['Photo\\AlbumController', '-', true]],
438
            ['photo\\album\\controller', ['Photo\\Album\\Controller', '-', false]],
439
            ['photo\\album\\controller', ['Photo\\Album\\Controller', '-', true]],
440
441
            ['photo\\album_controller', ['Photo\\AlbumController', '_', false]],
442
            ['photo\\album_controller', ['Photo\\AlbumController', '_', true]],
443
            ['photo\\album\\controller', ['Photo\\AlbumController', '\\', false]],
444
            ['photo\\album\\controller', ['Photo\\AlbumController', '\\', true]],
445
            ['photo\\album/controller', ['Photo\\AlbumController', '/', false]],
446
            ['photo\\album/controller', ['Photo\\AlbumController', '/', true]],
447
            ['photo\\album\\controller', ['Photo\\Album\\Controller', '_', false]],
448
            ['photo\\album\\controller', ['Photo\\Album\\Controller', '_', true]],
449
450
            ['photo/album/controller', ['Photo/Album/Controller', '-', false]],
451
            ['photo/album/controller', ['Photo/Album/Controller', '-', true]],
452
453
            ['post-tag', ['PostTag']],
454
            ['post_tag', ['PostTag', '_']],
455
            ['єдиний_код', ['ЄдинийКод', '_']],
456
457
            ['post-tag', ['postTag']],
458
            ['post_tag', ['postTag', '_']],
459
            ['єдиний_код', ['єдинийКод', '_']],
460
461
            ['foo-ybar', ['FooYBar', '-', false]],
462
            ['foo_ybar', ['fooYBar', '_', false]],
463
            ['невже_іце_працює', ['НевжеІЦеПрацює', '_', false]],
464
465
            ['foo-y-bar', ['FooYBar', '-', true]],
466
            ['foo_y_bar', ['fooYBar', '_', true]],
467
            ['foo_y_bar', ['fooYBar', '_', true]],
468
            ['невже_і_це_працює', ['НевжеІЦеПрацює', '_', true]],
469
470
        ];
471
    }
472
473
    public function id2camelProvider(): array
474
    {
475
        return [
476
            ['PostTag', ['post-tag']],
477
            ['PostTag', ['post_tag', '_']],
478
            ['ЄдинийСвіт', ['єдиний_світ', '_']],
479
480
            ['PostTag', ['post-tag']],
481
            ['PostTag', ['post_tag', '_']],
482
            ['НевжеІЦеПрацює', ['невже_і_це_працює', '_']],
483
484
            ['ShouldNotBecomeLowercased', ['ShouldNotBecomeLowercased', '_']],
485
486
            ['FooYBar', ['foo-y-bar']],
487
            ['FooYBar', ['foo_y_bar', '_']],
488
        ];
489
    }
490
}
491