forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTextHelperTest.php
More file actions
455 lines (388 loc) · 18.3 KB
/
TextHelperTest.php
File metadata and controls
455 lines (388 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Helpers;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Test\CIUnitTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
/**
* @internal
*/
#[Group('Others')]
final class TextHelperTest extends CIUnitTestCase
{
private string $longString = 'Once upon a time, a framework had no tests. It sad. So some nice people began to write tests. The more time that went on, the happier it became. Everyone was happy.';
private string $mbLongString = 'Давным-давно во фреймворке не было тестов. Это печально. И вот несколько хороших людей начали писать тесты. Чем больше времени проходило, тем счастливее становилось. Все были счастливы.';
protected function setUp(): void
{
parent::setUp();
helper('text');
}
public function testStripSlashes(): void
{
$expected = [
"Is your name O'reilly?",
"No, my name is O'connor.",
];
$str = [
"Is your name O\\'reilly?",
"No, my name is O\\'connor.",
];
$this->assertSame($expected, strip_slashes($str));
}
public function testStripQuotes(): void
{
$strs = [
'"me oh my!"' => 'me oh my!',
"it's a winner!" => 'its a winner!',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, strip_quotes($str));
}
}
public function testQuotesToEntities(): void
{
$strs = [
'"me oh my!"' => '"me oh my!"',
"it's a winner!" => 'it's a winner!',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, quotes_to_entities($str));
}
}
public function testReduceDoubleSlashes(): void
{
$strs = [
'http://codeigniter.com' => 'http://codeigniter.com',
'//var/www/html/example.com/' => '/var/www/html/example.com/',
'/var/www/html//index.php' => '/var/www/html/index.php',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, reduce_double_slashes($str));
}
}
#[DataProvider('provideReduceMultiples')]
public function testReduceMultiples(string $str, string $expected): void
{
$this->assertSame($expected, reduce_multiples($str));
}
/**
* @return iterable<string, list<string>>
*/
public static function provideReduceMultiples(): iterable
{
yield from [
// string, expected
'double commas' => ['Fred, Bill,, Joe, Jimmy', 'Fred, Bill, Joe, Jimmy'],
'double commas at last' => ['Ringo, John, Paul,,', 'Ringo, John, Paul,'],
'commas at first and last' => [',Fred, Bill,, Joe, Jimmy,', ',Fred, Bill, Joe, Jimmy,'],
];
}
#[DataProvider('provideReduceMultiplesWithTrim')]
public function testReduceMultiplesWithTrim(string $str, string $expected): void
{
$this->assertSame($expected, reduce_multiples($str, ',', true));
}
/**
* @return iterable<string, list<string>>
*/
public static function provideReduceMultiplesWithTrim(): iterable
{
yield from [
// string, expected
'double commas' => ['Fred, Bill,, Joe, Jimmy', 'Fred, Bill, Joe, Jimmy'],
'double commas at last' => ['Ringo, John, Paul,,', 'Ringo, John, Paul'],
'commas at first and last' => [',Fred, Bill,, Joe, Jimmy,', 'Fred, Bill, Joe, Jimmy'],
];
}
public function testRandomString(): void
{
$this->assertSame(16, strlen(random_string('alnum', 16)));
$this->assertSame(16, strlen(random_string('alpha', 16)));
$this->assertSame(16, strlen(random_string('nozero', 16)));
$this->assertSame(16, strlen(random_string('numeric', 16)));
$this->assertSame(8, strlen(random_string('numeric')));
$this->assertSame(16, strlen($random = random_string('crypto', 16)));
$this->assertIsString($random);
}
/**
* @see https://github.com/codeigniter4/CodeIgniter4/issues/6330
*/
public function testRandomStringCryptoOddNumber(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'You must set an even number to the second parameter when you use `crypto`',
);
random_string('crypto', 9);
}
public function testRandomStringWithUnsupportedType(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Invalid type "basic". Accepted types: alpha, alnum, numeric, nozero, or crypto.',
);
random_string('basic');
}
public function testIncrementString(): void
{
$this->assertSame('my-test_1', increment_string('my-test'));
$this->assertSame('my-test-1', increment_string('my-test', '-'));
$this->assertSame('file_5', increment_string('file_4'));
$this->assertSame('file-5', increment_string('file-4', '-'));
$this->assertSame('file-5', increment_string('file-4', '-'));
$this->assertSame('file-1', increment_string('file', '-', 1));
$this->assertSame('124', increment_string('123', ''));
}
// Functions from text_helper_test.php
public function testWordLimiter(): void
{
$this->assertSame('Once upon a time,…', word_limiter($this->longString, 4));
$this->assertSame('Once upon a time,…', word_limiter($this->longString, 4, '…'));
$this->assertSame('', word_limiter('', 4));
$this->assertSame('Once upon a…', word_limiter($this->longString, 3, '…'));
$this->assertSame('Once upon a time', word_limiter('Once upon a time', 4, '…'));
$this->assertSame('Давным-давно во фреймворке не было тестов.…', word_limiter($this->mbLongString, 6));
$this->assertSame('Давным-давно во фреймворке не было тестов.…', word_limiter($this->mbLongString, 6, '…'));
$this->assertSame('Давным-давно во фреймворке…', word_limiter($this->mbLongString, 3, '…'));
$this->assertSame('Давным-давно во фреймворке не было тестов.', word_limiter('Давным-давно во фреймворке не было тестов.', 6, '…'));
}
public function testCharacterLimiter(): void
{
$this->assertSame('Once upon a time, a…', character_limiter($this->longString, 20));
$this->assertSame('Once upon a time, a…', character_limiter($this->longString, 20, '…'));
$this->assertSame('Short', character_limiter('Short', 20));
$this->assertSame('Short', character_limiter('Short', 5));
$this->assertSame('Давным-давно во фреймворке не было тестов.…', character_limiter($this->mbLongString, 41));
$this->assertSame('Давным-давно во фреймворке не было тестов.…', character_limiter($this->mbLongString, 41, '…'));
$this->assertSame('Короткий', character_limiter('Короткий', 20));
$this->assertSame('Короткий', character_limiter('Короткий', 8));
}
public function testAsciiToEntities(): void
{
$strs = [
'Œ' => 'Œ',
'Âé' => 'Âé',
'Â? ' => 'Â? ',
'“‘ “test” ' => '“‘ “test” ',
'†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, ascii_to_entities($str));
}
}
public function testEntitiesToAscii(): void
{
$strs = [
'Œ' => 'Œ',
'Âé' => 'Âé',
'Â? ' => 'Â? ',
'“‘ “test” ' => '“‘ “test” ',
'†¥¨ˆøåß∂ƒ©˙∆˚¬' => '†¥¨ˆøåß∂ƒ©˙∆˚¬',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, entities_to_ascii($str));
}
}
public function testEntitiesToAsciiUnsafe(): void
{
$str = '<>';
$this->assertSame('<>', entities_to_ascii($str, true));
$this->assertSame('<>', entities_to_ascii($str, false));
}
public function testEntitiesToAsciiSmallOrdinals(): void
{
$str = '';
$this->assertSame(pack('c', 7), entities_to_ascii($str));
}
public function testConvertAccentedCharacters(): void
{
$this->assertSame('AAAeEEEIIOOEUUUeY', convert_accented_characters('ÀÂÄÈÊËÎÏÔŒÙÛÜŸ'));
$this->assertSame('a e i o u n ue', convert_accented_characters('á é í ó ú ñ ü'));
}
public function testCensoredWords(): void
{
$this->assertSame('fuck', word_censor('fuck', []));
}
public function testCensoredWordsWithReplacement(): void
{
$censored = [
'boob',
'nerd',
'ass',
'asshole',
'fart',
'fuck',
'fucking',
];
$strs = [
'Ted bobbled the ball' => 'Ted bobbled the ball',
'Jake is a nerdo' => 'Jake is a nerdo',
'The borg will assimilate you' => 'The borg will assimilate you',
'Did Mary Fart?' => 'Did Mary $*#?',
'Jake is really a boob' => 'Jake is really a $*#',
'Jake is really a (boob)' => 'Jake is really a ($*#)',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, word_censor($str, $censored, '$*#'));
}
}
public function testCensoredWordsNonReplacement(): void
{
$censored = [
'boob',
'nerd',
'ass',
'asshole',
'fart',
'fuck',
'fucking',
];
$strs = [
'How are you today?' => 'How are you today?',
'I am fine, thankyou!' => 'I am fine, thankyou!',
'Are you fucking kidding me?' => 'Are you ####### kidding me?',
'Fucking asshole!' => '####### #######!',
];
foreach ($strs as $str => $expected) {
$this->assertSame($expected, word_censor($str, $censored));
}
}
public function testHighlightCode(): void
{
// PHP 8.3 changes the output.
if (PHP_VERSION_ID >= 80300) {
$expect = '<pre><code style="color: #000000"><span style="color: #0000BB"><?php var_dump</span><span style="color: #007700">(</span><span style="color: #0000BB">$this</span><span style="color: #007700">); </span><span style="color: #0000BB">?> ?></span></code></pre>';
} else {
$expect = "<code><span style=\"color: #000000\">\n<span style=\"color: #0000BB\"><?php var_dump</span><span style=\"color: #007700\">(</span><span style=\"color: #0000BB\">\$this</span><span style=\"color: #007700\">); </span><span style=\"color: #0000BB\">?> </span>\n</span>\n</code>";
}
$this->assertSame($expect, highlight_code('<?php var_dump($this); ?>'));
}
public function testHighlightPhrase(): void
{
$strs = [
'this is a phrase' => '<mark>this is</mark> a phrase',
'this is another' => '<mark>this is</mark> another',
'Gimme a test, Sally' => 'Gimme a test, Sally',
'Or tell me what this is' => 'Or tell me what <mark>this is</mark>',
'' => '',
];
foreach ($strs as $str => $expect) {
$this->assertSame($expect, highlight_phrase($str, 'this is'));
}
$this->assertSame('<strong>this is</strong> a strong test', highlight_phrase('this is a strong test', 'this is', '<strong>', '</strong>'));
}
public function testEllipsize(): void
{
$strs = [
'0' => [
'this is my string' => '… my string',
"here's another one" => '…nother one',
'this one is just a bit longer' => '…bit longer',
'short' => 'short',
],
'.5' => [
'this is my string' => 'this …tring',
"here's another one" => "here'…r one",
'this one is just a bit longer' => 'this …onger',
'short' => 'short',
],
'1' => [
'this is my string' => 'this is my…',
"here's another one" => "here's ano…",
'this one is just a bit longer' => 'this one i…',
'short' => 'short',
],
];
foreach ($strs as $pos => $s) {
foreach ($s as $str => $expect) {
$this->assertSame($expect, ellipsize($str, 10, $pos));
}
}
}
public function testWordWrap(): void
{
$string = 'Here is a simple string of text that will help us demonstrate this function.';
$expected = "Here is a simple string\nof text that will help us\ndemonstrate this\nfunction.";
$this->assertSame(3, substr_count(word_wrap($string, 25), "\n"));
$this->assertSame($expected, word_wrap($string, 25));
$string2 = "Here is a\nbroken up sentence\rspanning lines\r\nwoohoo!";
$expected2 = "Here is a\nbroken up sentence\nspanning lines\nwoohoo!";
$this->assertSame(3, substr_count(word_wrap($string2, 25), "\n"));
$this->assertSame($expected2, word_wrap($string2, 25));
$string3 = "Here is another slightly longer\nbroken up sentence\rspanning lines\r\nwoohoo!";
$expected3 = "Here is another slightly\nlonger\nbroken up sentence\nspanning lines\nwoohoo!";
$this->assertSame(4, substr_count(word_wrap($string3, 25), "\n"));
$this->assertSame($expected3, word_wrap($string3, 25));
}
public function testWordWrapUnwrap(): void
{
$string = 'Here is a {unwrap}simple string of text{/unwrap} that will help us demonstrate this function.';
$expected = "Here is a simple string of text\nthat will help us\ndemonstrate this\nfunction.";
$this->assertSame(3, substr_count(word_wrap($string, 25), "\n"));
$this->assertSame($expected, word_wrap($string, 25));
}
public function testWordWrapLongWords(): void
{
// the really really long word will be split
$string = 'Here is an unbelievable super-complicated and reallyreallyquiteextraordinarily sophisticated sentence.';
$expected = "Here is an unbelievable\nsuper-complicated and\nreallyreallyquiteextraor\ndinarily\nsophisticated sentence.";
$this->assertSame($expected, word_wrap($string, 25));
}
public function testWordWrapURL(): void
{
// the really really long word will be split
$string = 'Here is an unbelievable super-complicated and http://www.reallyreallyquiteextraordinarily.com sophisticated sentence.';
$expected = "Here is an unbelievable\nsuper-complicated and\nhttp://www.reallyreallyquiteextraordinarily.com\nsophisticated sentence.";
$this->assertSame($expected, word_wrap($string, 25));
}
public function testDefaultWordWrapCharlim(): void
{
$string = 'Here is a longer string of text that will help us demonstrate the default charlim of this function.';
$this->assertSame(73, strpos(word_wrap($string), "\n"));
}
public function testExcerpt(): void
{
$string = $this->longString;
$result = ' Once upon a time, a framework had no tests. It sad So some nice people began to write tests. The more time that went on, the happier it became. ...';
$this->assertSame($result, excerpt($string));
$multibyteResult = ' Давным-давно во фреймворке не было тестов. Это печ льно. И вот несколько хороших людей начали писать тесты. Чем больше времени проходило, тем ...';
$this->assertSame($multibyteResult, excerpt($this->mbLongString));
}
public function testExcerptRadius(): void
{
$string = $this->longString;
$phrase = 'began';
$result = '... people began to ...';
$this->assertSame(excerpt($string, $phrase, 10), $result);
$multibyteResult = '... Это печально . И вот ...';
$this->assertSame($multibyteResult, excerpt($this->mbLongString, 'печально', 10));
}
public function testAlternator(): void
{
$phrase = ' scream! ';
$result = '';
alternator();
for ($i = 0; $i < 4; $i++) {
$result .= alternator('I', 'you', 'we') . $phrase;
}
$this->assertSame('I scream! you scream! we scream! I scream! ', $result);
}
public function testEmptyAlternator(): void
{
$phrase = ' scream! ';
$result = '';
for ($i = 0; $i < 4; $i++) {
$result .= alternator() . $phrase;
}
$this->assertSame(' scream! scream! scream! scream! ', $result);
}
}