Passed
Pull Request — develop (#27)
by Glynn
02:48
created

StringFunctionTest   A

Complexity

Total Complexity 40

Size/Duplication

Total Lines 477
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 249
dl 0
loc 477
rs 9.2
c 0
b 0
f 0
wmc 40

How to fix   Complexity   

Complex Class

Complex classes like StringFunctionTest 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.

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 StringFunctionTest, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
use PHPUnit\Framework\TestCase;
6
use PinkCrab\FunctionConstructors\Functions;
7
use PinkCrab\FunctionConstructors\Strings as Str;
8
use PinkCrab\FunctionConstructors\FunctionsLoader;
9
10
/**
11
 * StringFunction class.
12
 */
13
class StringFunctionTest extends TestCase
14
{
15
    public function setup(): void
16
    {
17
        FunctionsLoader::include();
18
    }
19
20
    public function testCanWrapStringWithHTMLTags(): void
21
    {
22
        $asDiv = Str\tagWrap('div class="test"', 'div');
23
        $this->assertEquals('<div class="test">HI</div>', $asDiv('HI'));
24
        $this->assertEquals('<div class="test">123</div>', $asDiv('123'));
25
26
        $asLi = Str\tagWrap('li');
27
        $this->assertEquals('<li>HI</li>', $asLi('HI'));
28
        $this->assertEquals('<li>123</li>', $asLi('123'));
29
    }
30
31
    public function testCanWrapString(): void
32
    {
33
        $foo = Str\wrap('--', '++');
34
        $this->assertEquals('--HI++', $foo('HI'));
35
        $this->assertEquals('--123++', $foo('123'));
36
37
        $bar = Str\wrap('\/');
38
        $this->assertEquals('\/HI\/', $bar('HI'));
39
        $this->assertEquals('\/123\/', $bar('123'));
40
    }
41
42
    public function testCanMakeUrl(): void
43
    {
44
        $makeUrl = Str\asUrl('http://test.com');
45
        $this->assertEquals(
46
            "<a href='http://test.com'>test</a>",
47
            $makeUrl('test')
48
        );
49
50
        $makeUrlBlank = Str\asUrl('http://test.com', '_blank');
51
        $this->assertEquals(
52
            "<a href='http://test.com' target='_blank'>test</a>",
53
            $makeUrlBlank('test')
54
        );
55
    }
56
57
    public function testCanPrependString(): void
58
    {
59
        $prep10 = Str\prepend('10');
60
        $this->assertEquals('10HI', $prep10('HI'));
61
        $this->assertEquals('1077', $prep10('77'));
62
    }
63
64
    public function testCanAppendString(): void
65
    {
66
        $append10 = Str\append('10');
67
        $this->assertEquals('HI10', $append10('HI'));
68
        $this->assertEquals('7710', $append10('77'));
69
    }
70
71
    public function testCanCurryReplace(): void
72
    {
73
        $find_to_mask = Str\findToReplace('to mask');
74
75
        // Mask with XX
76
        $maskWithXX = $find_to_mask('xx');
77
        $string     = 'This has some test to mask and some more to mask';
78
        $this->assertEquals(
79
            'This has some test xx and some more xx',
80
            $maskWithXX($string)
81
        );
82
83
        // Mask with YY
84
        $maskWithYY = $find_to_mask('yy');
85
        $string     = 'This has some test to mask and some more to mask';
86
        $this->assertEquals(
87
            'This has some test yy and some more yy',
88
            $maskWithYY($string)
89
        );
90
91
        // Inlined.
92
        $this->assertEquals(
93
            'This has some test xx and some more xx',
94
            Str\findToReplace('to mask')('xx')($string)
95
        );
96
    }
97
98
    public function testCanReplaceInString(): void
99
    {
100
        $replaceGlynnWithHa = Str\replaceWith('glynn', 'ha');
101
        $this->assertEquals('Hi ha', $replaceGlynnWithHa('Hi glynn'));
102
        $this->assertEquals('ha ha ha', $replaceGlynnWithHa('glynn glynn glynn'));
103
    }
104
105
    public function testCanReplaceSubStrings()
106
    {
107
        $atStart = Str\replaceSubString('PHP');
108
        $startAt10 = Str\replaceSubString('PHP', 10);
109
        $startAt10For5 = Str\replaceSubString('PHP', 10, 5);
110
111
        $string = "abcdefghijklmnopqrstuvwxyz";
112
113
        $this->assertEquals('PHP', $atStart($string));
114
        $this->assertEquals('abcdefghijPHP', $startAt10($string));
115
        $this->assertEquals('abcdefghijPHPpqrstuvwxyz', $startAt10For5($string));
116
    }
117
118
    public function testStringContains(): void
119
    {
120
        $contains = Str\contains('--');
121
        $this->assertTrue($contains('--True'));
122
        $this->assertFalse($contains('++False'));
123
    }
124
125
    public function testStringStartWith(): void
126
    {
127
        $startsWithA = Str\startsWith('--');
128
        $this->assertTrue($startsWithA('--True'));
129
        $this->assertFalse($startsWithA('++False'));
130
    }
131
132
    public function testStringEndWith(): void
133
    {
134
        $endsWith = Str\endsWith('--');
135
        $this->assertTrue($endsWith('--True--'));
136
        $this->assertFalse($endsWith('++False++'));
137
    }
138
139
    public function testCanDoContainsPattern()
140
    {
141
        $hasFooWithoutPreceedingBar = Str\containsPattern('/(?!.*bar)(?=.*foo)^(\w+)$/');
142
143
        $this->assertTrue($hasFooWithoutPreceedingBar('blahfooblah'));
144
        $this->assertTrue($hasFooWithoutPreceedingBar('somethingfoo'));
145
        $this->assertFalse($hasFooWithoutPreceedingBar('blahfooblahbarfail'));
146
        $this->assertFalse($hasFooWithoutPreceedingBar('shouldbarfooshouldfail'));
147
        $this->assertFalse($hasFooWithoutPreceedingBar('barfoofail'));
148
    }
149
150
    public function testCanSplitStringWithPattern()
151
    {
152
        $splitter = Str\splitPattern("/-/");
153
        $date1 = "1970-01-01";
154
        $date2 = "2020-11-11";
155
        $dateFail = "RETURNED1";
156
157
        $this->assertEquals('1970', $splitter($date1)[0]);
158
        $this->assertEquals('01', $splitter($date1)[1]);
159
        $this->assertEquals('01', $splitter($date1)[2]);
160
161
        $this->assertEquals('2020', $splitter($date2)[0]);
162
        $this->assertEquals('11', $splitter($date2)[1]);
163
        $this->assertEquals('11', $splitter($date2)[2]);
164
165
        $this->assertEquals('RETURNED1', $splitter($dateFail)[0]);
166
    }
167
168
    public function testCanFormatDecimalNumber()
169
    {
170
        $eightDecimalPlaces = Str\decimalNumber(8);
171
        $tenDecimalPlaces = Str\decimalNumber(10);
172
        $doubleDecimalPlaces = Str\decimalNumber(2);
173
174
        $this->assertEquals('3.50000000', $eightDecimalPlaces(3.5));
175
        $this->assertEquals('2.6580000000', $tenDecimalPlaces("2.658"));
176
        $this->assertEquals('3.14', $doubleDecimalPlaces(M_PI));
177
178
        // With thousand separator
179
        $withPipe = Str\decimalNumber(2, '.', '|');
180
        $this->assertEquals('123|456|789.12', $withPipe(123456789.123456));
181
    }
182
183
    public function testCanStripCSlashes()
184
    {
185
        $escA_C_U = Str\addSlashes('ACU');
186
187
        $this->assertEquals('\Abcd\Cfjruuuu\U', $escA_C_U('AbcdCfjruuuuU'));
188
    }
189
190
    public function testCanComposeWithSafeStrings(): void
191
    {
192
        $reutrnsArray = function ($e) {
193
            return array();
194
        };
195
196
        $function = Str\composeSafeStringFunc(
197
            Str\replaceWith('3344', '*\/*'),
198
            Str\replaceWith('5566', '=/\='),
199
            $reutrnsArray,
200
            Str\prepend('00'),
201
            Str\append('99')
202
        );
203
        $this->assertNull($function('1122334455667788'));
204
    }
205
206
    public function testStringCompilerCanBeUsedAsAJournal(): void
207
    {
208
        $journal = Str\stringCompiler('');
209
        $journal = $journal('11');
210
        $this->assertEquals('11', $journal());
211
        $journal = $journal('22');
212
        $this->assertEquals('1122', $journal());
213
        $journal = $journal('33');
214
        $this->assertEquals('112233', $journal());
215
    }
216
217
    public function testComposedWithArrayMap(): void
218
    {
219
        $function = Str\composeSafeStringFunc(
220
            Str\replaceWith('a', '_a_'),
221
            Str\replaceWith('t', '-t-'),
222
            Str\prepend('00'),
223
            Str\append('99')
224
        );
225
226
        $results = array_map($function, array('1a2', '1b3', '1t4'));
227
        $this->assertEquals('001_a_299', $results[0]);
228
        $this->assertEquals('001b399', $results[1]);
229
        $this->assertEquals('001-t-499', $results[2]);
230
    }
231
232
    public function testCanAddSlashes()
233
    {
234
        $slashA = Str\addSlashes('a');
235
        $this->assertEquals('h\appy d\ays', $slashA('happy days'));
236
237
        $slashAD = Str\addSlashes('ad');
238
        $this->assertEquals('h\appy \d\ays', $slashAD('happy days'));
239
    }
240
241
    public function testCanSplitString()
242
    {
243
        $splitIntoFours = Str\split(4);
244
245
        $split = $splitIntoFours('AAAABBBBCCCCDDDD');
246
        $this->assertEquals('AAAA', $split[0]);
247
        $this->assertEquals('BBBB', $split[1]);
248
        $this->assertEquals('CCCC', $split[2]);
249
        $this->assertEquals('DDDD', $split[3]);
250
    }
251
252
    public function testCanSplitChunkString()
253
    {
254
        $in5s = Str\chunk(5, '-');
255
        $this->assertEquals('aaaaa-bbbbb-ccccc-', $in5s('aaaaabbbbbccccc'));
256
    }
257
258
    public function testCanCountCharsInString()
259
    {
260
        $getOccurances = Str\countChars();
261
        $this->assertCount(4, $getOccurances('Hello'));
262
        $this->assertCount(1, $getOccurances('a'));
263
        $this->assertCount(8, $getOccurances('asfetwafgh'));
264
    }
265
266
    public function testCanwordWrap()
267
    {
268
        $loose10 = Str\wordWrap(10, '--');
269
        $tight5 = Str\wordWrap(5, '--', true);
270
271
        $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
272
        $this->assertEquals('ABCDEFGHIJKLMNOPQRSTUVWXYZ', $loose10($string));
273
        $this->assertEquals('ABCDE--FGHIJ--KLMNO--PQRST--UVWXY--Z', $tight5($string));
274
275
        $string = "ABCDEF GHIJK LMN OPQ RST UV WX YZ";
276
        $this->assertEquals('ABCDEF--GHIJK LMN--OPQ RST UV--WX YZ', $loose10($string));
277
        $this->assertEquals('ABCDE--F--GHIJK--LMN--OPQ--RST--UV WX--YZ', $tight5($string));
278
    }
279
280
    public function testCanDoTrim()
281
    {
282
        $trimZ = Str\trim("zZ");
283
        $this->assertEquals('44455', $trimZ("zzzz44455ZZZZZZZZZ"));
284
285
286
        $trimAB = Str\lTrim("AB");
287
        $this->assertEquals('STD', $trimAB("ABSTD"));
288
        $this->assertEquals('HFJKGHDJKGHFJKFGJKFGJK', $trimAB("ABHFJKGHDJKGHFJKFGJKFGJK"));
289
290
        $trimIU = Str\trim("IU");
291
        $this->assertEquals('RESSTD', $trimIU("IURESSTDIU"));
292
        $this->assertEquals('TREHFJKGHDJKGHFJKFGJKFGJK', $trimIU("IUIUIUTREHFJKGHDJKGHFJKFGJKFGJKIUIUIUIUIUIUIUIUIUIU"));
293
294
        $this->assertEquals('CLEAR', Str\trim()("\t\nCLEAR\r\0"));
295
296
        $trimYZ = Str\rTrim("YZ");
297
        $this->assertEquals('STD', $trimYZ("STDYZ"));
298
        $this->assertEquals('ABHFJKGHDJKGHFJKFGJKFGJK', $trimYZ("ABHFJKGHDJKGHFJKFGJKFGJKYZ"));
299
    }
300
301
    public function testCanDosimilarAsBase()
302
    {
303
        $compareTheBaseAsChars = Str\similarAsBase("THE BASE");
304
        $compareTheBaseAsPC = Str\similarAsBase("THE BASE", true);
305
        $this->assertEquals(4, $compareTheBaseAsChars('BASE'));
306
        $this->assertEquals((6 / 9) * 100, $compareTheBaseAsPC('BASE'));
307
    }
308
309
    public function testCanDosimilarAsComparisson()
310
    {
311
        $compareTheBaseAsChars = Str\similarAsComparison("BASE");
312
        $compareTheBaseAsPC = Str\similarAsComparison("BASE", true);
313
        $this->assertEquals(4, $compareTheBaseAsChars('THE BASE'));
314
315
        // This is not the calc done in the fucntion, but give the desired answer simpler!
316
        $this->assertEquals(66.66666666666667, $compareTheBaseAsPC('THE BASE'));
317
    }
318
319
    public function testCanPadStrings()
320
    {
321
        $padLeft10 = Str\pad(10, '.', STR_PAD_LEFT);
322
        $padRight10 = Str\pad(10, '_', STR_PAD_RIGHT);
323
        $padBoth10 = Str\pad(10, '\'', STR_PAD_BOTH);
324
325
        $this->assertEquals('........HI', $padLeft10('HI'));
326
        $this->assertEquals('HI________', $padRight10('HI'));
327
        $this->assertEquals("''''HI''''", $padBoth10('HI'));
328
    }
329
330
    public function testCanRepeatString()
331
    {
332
        $sayItTrice = Str\repeat(3);
333
        $this->assertEquals('HIHIHI', $sayItTrice('HI'));
334
    }
335
336
    public function testCanDoWordCounts()
337
    {
338
        // Check can count words and reutrn count.
339
        $WordCount = Str\wordCount(WORD_COUNT_NUMBER_OF_WORDS);
340
        $this->assertEquals(3, $WordCount('HI HI HI'));
341
342
        // Test can return array of word counts.
343
        $wordList = Str\wordCount(WORD_COUNT_ARRAY)('HI BYE MAYBE');
344
        $this->assertEquals('HI', $wordList[0]);
345
        $this->assertEquals('BYE', $wordList[1]);
346
        $this->assertEquals('MAYBE', $wordList[2]);
347
348
        // Test can return ass array of word counts with positions.
349
        $wordListPositions = Str\wordCount(WORD_COUNT_ASSOCIATIVE_ARRAY)('HI BYE MAYBE');
350
        $this->assertEquals('HI', $wordListPositions[0]);
351
        $this->assertEquals('BYE', $wordListPositions[3]);
352
        $this->assertEquals('MAYBE', $wordListPositions[7]);
353
    }
354
355
    public function testCanCountSubStrings()
356
    {
357
        $findNemoAll = Str\countSubString('Nemo');
358
        $findNemoAllAfter20 = Str\countSubString('Nemo', 20);
359
        $findNemoAllAfter20OnlyFor40More = Str\countSubString('Nemo', 20, 40);
360
361
        $haystack1 = str_repeat('Nemo is a fish.', 11); // 15 chars
362
        $haystack2 = str_repeat('Nemo = Fish |', 14); // 13 chars
363
364
        $this->assertEquals(11, $findNemoAll($haystack1));
365
        $this->assertEquals(14, $findNemoAll($haystack2));
366
367
        $this->assertEquals(9, $findNemoAllAfter20($haystack1));
368
        $this->assertEquals(12, $findNemoAllAfter20($haystack2));
369
370
        $this->assertEquals(2, $findNemoAllAfter20OnlyFor40More($haystack1));
371
        $this->assertEquals(3, $findNemoAllAfter20OnlyFor40More($haystack2));
372
    }
373
374
    public function testCanStripTags()
375
    {
376
        $allTags = Str\stripTags();
377
        $allowPTags = Str\stripTags('<p><a>');
378
379
        $this->assertEquals('1Stuff', $allTags('1<p>Stuff</p>'));
380
        $this->assertEquals('1<p>Stuff</p>', $allowPTags('1<p>Stuff</p>'));
381
    }
382
383
    public function testCanFindFirstPosition()
384
    {
385
        $findAppleCaseSense = Str\firstPosition('Apple');
386
        $this->assertEquals(0, $findAppleCaseSense('Apple are tasty'));
387
        $this->assertEquals(19, $findAppleCaseSense('I really dont like Apples'));
388
        $this->assertNull($findAppleCaseSense('APPLES ARE TASTY'));
389
390
        $findAppleCaseInsense = Str\firstPosition('ApPle', 10, STRINGS_CASE_INSENSITIVE);
391
        $this->assertNull($findAppleCaseInsense('Hmm yes, APPLES are really tasty'));
392
        $this->assertEquals(19, $findAppleCaseInsense('I really dont like APplE Tree'));
393
    }
394
395
    public function testCanFindLastPosition()
396
    {
397
        $findLastAppleCaseSense = Str\lastPosition('Apple');
398
        $this->assertEquals(13, $findLastAppleCaseSense('Apple a day, Apple are tasty'));
399
        $this->assertEquals(47, $findLastAppleCaseSense('I really dont like Apples but i do really like Apple skin'));
400
        $this->assertNull($findLastAppleCaseSense('APPLES ARE TASTY'));
401
402
        $findAppleCaseInsense = Str\lastPosition('ApPle', 0, STRINGS_CASE_INSENSITIVE);
403
        $this->assertEquals(25, $findAppleCaseInsense('APPLES are tasty, I like ApPleS'));
404
        $this->assertEquals(41, $findAppleCaseInsense('I really dont like APplE Tree, they grow ApPLES'));
405
    }
406
407
    public function testCanFindSubStrings()
408
    {
409
        $caseSenseBefore = Str\firstSubString('abc', STRINGS_BEFORE_NEEDLE);
410
        $caseSenseAfter = Str\firstSubString('abc');
411
        $caseInsenseBefore = Str\firstSubString('aBc', STRINGS_BEFORE_NEEDLE | STRINGS_CASE_INSENSITIVE);
412
        $caseInsenseAfter = Str\firstSubString('abC', STRINGS_CASE_INSENSITIVE);
413
414
        $this->assertEquals('abcefg', $caseSenseAfter('qwertabcefg'));
415
        $this->assertEquals('qwert', $caseSenseBefore('qwertabcefg'));
416
417
        $this->assertNotNull($caseSenseAfter('rutoiuerot')); // No match
418
        $this->assertNotNull($caseSenseAfter('QWERTABCEFG')); // Uppercase
419
        $this->assertEquals('', $caseSenseAfter('rutoiuerot'));// No match
420
        $this->assertEquals('', $caseSenseAfter('QWERTABCEFG'));// Uppercase
421
422
423
        $this->assertEquals('ABCEFG', $caseInsenseAfter('QWERTABCEFG'));
424
        $this->assertEquals('QWERT', $caseInsenseBefore('QWERTABCEFG'));
425
        $this->assertEquals('abcefg', $caseInsenseAfter('qwertabcefg'));
426
        $this->assertEquals('qwert', $caseInsenseBefore('qwertabcefg'));
427
    }
428
429
    public function testCanFindfirstChar()
430
    {
431
        $findAorB = Str\firstChar('aAbB');
432
        $this->assertEquals('banana', $findAorB('qweiuioubanana'));
433
        $this->assertEquals('a12345', $findAorB('eruweyriwyriwa12345'));
434
        $this->assertEquals('', $findAorB('zzzzzzzzzzzzzzzzzzz'));
435
    }
436
437
    public function testCanFindlastChar()
438
    {
439
        $findAorB = Str\lastChar('a');
440
        $this->assertEquals('a6', $findAorB('a1a2a3a4a5a6'));
441
        $this->assertEquals('abc', $findAorB('eruweyriwyriwa12345abc'));
442
        $this->assertEquals('', $findAorB('zzzzzzzzzzzzzzzz'));
443
    }
444
445
    public function testCanTranslateSubString()
446
    {
447
        $rosStone = Str\translateWith([
448
            'Hi' => 'Hello',
449
            'Yeah' => 'Yes',
450
            'Sod' => 'XXX',
451
        ]);
452
453
        $this->assertEquals('Hello you', $rosStone('Hi you'));
454
        $this->assertEquals('Hello Hello', $rosStone('Hi Hi'));
455
456
        $this->assertEquals('Yes we can do that', $rosStone('Yeah we can do that'));
457
458
        $this->assertEquals('XXX off', $rosStone('Sod off'));
459
    }
460
461
    public function testCanUseVSprintf()
462
    {
463
        $formatter = Str\vSprintf(['alpha', '12', '12.5']);
464
        $this->assertEquals('12alpha34-12-12.5-f', $formatter('12%s34-%s-%s-f'));
465
    }
466
467
    /** @testdox It should be possible to check if a value is a string and is blank */
468
    public function testIsBlank(): void
469
    {
470
        // With string values
471
        $this->assertTrue(call_user_func(Functions::IS_BLANK, ''));
472
        $this->assertFalse(call_user_func(Functions::IS_BLANK, 'a'));
473
        $this->assertFalse(call_user_func(Functions::IS_BLANK, ' '));
474
        $this->assertFalse(call_user_func(Functions::IS_BLANK, '  '));
475
476
        // With other types
477
        $this->assertFalse(call_user_func(Functions::IS_BLANK, array()));
478
479
        $this->assertFalse(call_user_func(Functions::IS_BLANK, null));
480
481
        $this->assertFalse(call_user_func(Functions::IS_BLANK, new \stdClass()));
482
483
        $this->assertFalse(call_user_func(Functions::IS_BLANK, 1));
484
        $this->assertFalse(call_user_func(Functions::IS_BLANK, 1.0));
485
        $this->assertFalse(call_user_func(Functions::IS_BLANK, 0));
486
        $this->assertFalse(call_user_func(Functions::IS_BLANK, 0.0));
487
488
        $this->assertFalse(call_user_func(Functions::IS_BLANK, true));
489
        $this->assertFalse(call_user_func(Functions::IS_BLANK, false));
490
    }
491
}
492