• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

voku / Stringy / 25975965267

16 May 2026 11:38PM UTC coverage: 97.951% (+0.06%) from 97.891%
25975965267

Pull #55

github

web-flow
Merge cee8ce7f9 into 3357517e5
Pull Request #55: Restore Stringy fast paths and remove mutation-only regressions

38 of 39 new or added lines in 1 file covered. (97.44%)

1 existing line in 1 file now uncovered.

1004 of 1025 relevant lines covered (97.95%)

71.11 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.92
/src/Stringy.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Stringy;
6

7
use Defuse\Crypto\Crypto;
8
use voku\helper\AntiXSS;
9
use voku\helper\ASCII;
10
use voku\helper\EmailCheck;
11
use voku\helper\URLify;
12
use voku\helper\UTF8;
13

14
/**
15
 * ## 🇷🇺 Русским гражданам
16
 * В Украине сейчас идет война. Силами РФ наносятся удары по гражданской инфраструктуре в [Харькове][1], [Киеве][2], [Чернигове][3], [Сумах][4], [Ирпене][5] и десятках других городов. Гибнут люди - и гражданское население, и военные, в том числе российские призывники, которых бросили воевать. Чтобы лишить собственный народ доступа к информации, правительство РФ запретило называть войну войной, закрыло независимые СМИ и принимает сейчас ряд диктаторских законов. Эти законы призваны заткнуть рот всем, кто против войны. За обычный призыв к миру сейчас можно получить несколько лет тюрьмы.
17
 * Не молчите! Молчание - знак вашего согласия с политикой российского правительства.
18
 *  **Вы можете сделать выбор НЕ МОЛЧАТЬ.**
19
 * ---
20
 * ## 🇺🇸 To people of Russia
21
 * There is a war in Ukraine right now. The forces of the Russian Federation are attacking civilian infrastructure in [Kharkiv][1], [Kyiv][2], [Chernihiv][3], [Sumy][4], [Irpin][5] and dozens of other cities. People are dying – both civilians and military servicemen, including Russian conscripts who were thrown into the fighting. In order to deprive its own people of access to information, the government of the Russian Federation has forbidden calling a war a war, shut down independent media and is passing a number of dictatorial laws. These laws are meant to silence all those who are against war. You can be jailed for multiple years for simply calling for peace.
22
 * Do not be silent! Silence is a sign that you accept the Russian government's policy.
23
 * **You can choose NOT TO BE SILENT.**
24
 * ---
25
 * - [1] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/P7K2MSZDGFMIJPDD7CI2GIROJI.jpg "Kharkiv under attack"
26
 * - [2] https://gdb.voanews.com/01bd0000-0aff-0242-fad0-08d9fc92c5b3_cx0_cy5_cw0_w1023_r1_s.jpg "Kyiv under attack"
27
 * - [3] https://ichef.bbci.co.uk/news/976/cpsprodpb/163DD/production/_123510119_hi074310744.jpg "Chernihiv under attack"
28
 * - [4] https://www.youtube.com/watch?v=8K-bkqKKf2A "Sumy under attack"
29
 * - [5] https://cloudfront-us-east-2.images.arcpublishing.com/reuters/K4MTMLEHTRKGFK3GSKAT4GR3NE.jpg "Irpin under attack"
30
 *
31
 * @template-implements \IteratorAggregate<string>
32
 * @template-implements \ArrayAccess<array-key,string>
33
 */
34
class Stringy implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
35
{
36
    use JsonSerializableReturnTypeTrait;
37

38
    /**
39
     * An instance's string.
40
     *
41
     * @var string
42
     */
43
    protected $str;
44

45
    /**
46
     * The string's encoding, which should be one of the mbstring module's
47
     * supported encodings.
48
     *
49
     * @var string
50
     */
51
    protected $encoding;
52

53
    /**
54
     * @var UTF8
55
     */
56
    private $utf8;
57

58
    /**
59
     * @var ASCII
60
     */
61
    private $ascii;
62

63
    /**
64
     * Initializes a Stringy object and assigns both str and encoding properties
65
     * the supplied values. $str is cast to a string prior to assignment, and if
66
     * $encoding is not specified, it defaults to mb_internal_encoding(). Throws
67
     * an InvalidArgumentException if the first argument is an array or object
68
     * without a __toString method.
69
     *
70
     * @param object|scalar $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
71
     * @param string        $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
72
     *
73
     * @throws \InvalidArgumentException
74
     *                                   <p>if an array or object without a
75
     *                                   __toString method is passed as the first argument</p>
76
     *
77
     * @psalm-mutation-free
78
     */
79
    public function __construct($str = '', ?string $encoding = null)
80
    {
81
        /* @phpstan-ignore-next-line | always false in theory */
82
        if (\is_array($str)) {
3,712✔
83
            throw new \InvalidArgumentException(
3✔
84
                'Passed value cannot be an array'
3✔
85
            );
3✔
86
        }
87

88
        if (
89
            \is_object($str)
3,709✔
90
            &&
91
            !\method_exists($str, '__toString')
3,709✔
92
        ) {
93
            throw new \InvalidArgumentException(
4✔
94
                'Passed object must have a __toString method'
4✔
95
            );
4✔
96
        }
97

98
        $this->str = (string) $str;
3,706✔
99

100
        static $ASCII = null;
3,706✔
101
        if ($ASCII === null) {
3,706✔
102
            $ASCII = new ASCII();
×
103
        }
104
        $this->ascii = $ASCII;
3,706✔
105

106
        static $UTF8 = null;
3,706✔
107
        if ($UTF8 === null) {
3,706✔
108
            $UTF8 = new UTF8();
×
109
        }
110
        $this->utf8 = $UTF8;
3,706✔
111

112
        if ($encoding !== 'UTF-8') {
3,706✔
113
            $this->encoding = $this->utf8::normalize_encoding($encoding, 'UTF-8');
2,522✔
114
        } else {
115
            $this->encoding = $encoding;
2,766✔
116
        }
117
    }
118

119
    /**
120
     * Returns the value in $str.
121
     *
122
     * EXAMPLE: <code>
123
     * </code>
124
     *
125
     * @psalm-mutation-free
126
     *
127
     * @return string
128
     *                <p>The current value of the $str property.</p>
129
     */
130
    public function __toString()
131
    {
132
        return $this->str;
1,167✔
133
    }
134

135
    /**
136
     * Return part of the string occurring after a specific string.
137
     *
138
     * EXAMPLE: <code>
139
     * s('宮本 茂')->after('本'); // ' 茂'
140
     * </code>
141
     *
142
     * @param string $string <p>The delimiting string.</p>
143
     *
144
     * @psalm-mutation-free
145
     *
146
     * @return static
147
     */
148
    public function after(string $string): self
149
    {
150
        $strArray = UTF8::str_split_pattern(
4✔
151
            $this->str,
4✔
152
            $string
4✔
153
        );
4✔
154

155
        unset($strArray[0]);
4✔
156

157
        return new static(
4✔
158
            \implode(' ', $strArray),
4✔
159
            $this->encoding
4✔
160
        );
4✔
161
    }
162

163
    /**
164
     * Gets the substring after the first occurrence of a separator.
165
     * If no match is found returns new empty Stringy object.
166
     *
167
     * EXAMPLE: <code>
168
     * s('</b></b>')->afterFirst('b'); // '></b>'
169
     * </code>
170
     *
171
     * @param string $separator
172
     *
173
     * @psalm-mutation-free
174
     *
175
     * @return static
176
     */
177
    public function afterFirst(string $separator): self
178
    {
179
        return static::create(
3✔
180
            $this->utf8::str_substr_after_first_separator(
3✔
181
                $this->str,
3✔
182
                $separator,
3✔
183
                $this->encoding
3✔
184
            )
3✔
185
        );
3✔
186
    }
187

188
    /**
189
     * Gets the substring after the first occurrence of a separator.
190
     * If no match is found returns new empty Stringy object.
191
     *
192
     * EXAMPLE: <code>
193
     * s('</B></B>')->afterFirstIgnoreCase('b'); // '></B>'
194
     * </code>
195
     *
196
     * @param string $separator
197
     *
198
     * @psalm-mutation-free
199
     *
200
     * @return static
201
     */
202
    public function afterFirstIgnoreCase(string $separator): self
203
    {
204
        return static::create(
2✔
205
            $this->utf8::str_isubstr_after_first_separator(
2✔
206
                $this->str,
2✔
207
                $separator,
2✔
208
                $this->encoding
2✔
209
            )
2✔
210
        );
2✔
211
    }
212

213
    /**
214
     * Gets the substring after the last occurrence of a separator.
215
     * If no match is found returns new empty Stringy object.
216
     *
217
     * EXAMPLE: <code>
218
     * s('</b></b>')->afterLast('b'); // '>'
219
     * </code>
220
     *
221
     * @param string $separator
222
     *
223
     * @psalm-mutation-free
224
     *
225
     * @return static
226
     */
227
    public function afterLast(string $separator): self
228
    {
229
        return static::create(
2✔
230
            $this->utf8::str_substr_after_last_separator(
2✔
231
                $this->str,
2✔
232
                $separator,
2✔
233
                $this->encoding
2✔
234
            )
2✔
235
        );
2✔
236
    }
237

238
    /**
239
     * Gets the substring after the last occurrence of a separator.
240
     * If no match is found returns new empty Stringy object.
241
     *
242
     * EXAMPLE: <code>
243
     * s('</B></B>')->afterLastIgnoreCase('b'); // '>'
244
     * </code>
245
     *
246
     * @param string $separator
247
     *
248
     * @psalm-mutation-free
249
     *
250
     * @return static
251
     */
252
    public function afterLastIgnoreCase(string $separator): self
253
    {
254
        return static::create(
2✔
255
            $this->utf8::str_isubstr_after_last_separator(
2✔
256
                $this->str,
2✔
257
                $separator,
2✔
258
                $this->encoding
2✔
259
            )
2✔
260
        );
2✔
261
    }
262

263
    /**
264
     * Returns a new string with $suffix appended.
265
     *
266
     * EXAMPLE: <code>
267
     * s('fòô')->append('bàř'); // 'fòôbàř'
268
     * </code>
269
     *
270
     * @param string ...$suffix <p>The string to append.</p>
271
     *
272
     * @psalm-mutation-free
273
     *
274
     * @return static
275
     *                <p>Object with appended $suffix.</p>
276
     */
277
    public function append(string ...$suffix): self
278
    {
279
        if (\count($suffix) <= 1) {
21✔
280
            $suffix = $suffix[0];
19✔
281
        } else {
282
            $suffix = \implode('', $suffix);
2✔
283
        }
284

285
        return static::create($this->str . $suffix, $this->encoding);
21✔
286
    }
287

288
    /**
289
     * Append an password (limited to chars that are good readable).
290
     *
291
     * EXAMPLE: <code>
292
     * s('')->appendPassword(8); // e.g.: '89bcdfgh'
293
     * </code>
294
     *
295
     * @param int $length <p>Length of the random string.</p>
296
     *
297
     * @return static
298
     *                <p>Object with appended password.</p>
299
     */
300
    public function appendPassword(int $length): self
301
    {
302
        return $this->appendRandomString(
2✔
303
            $length,
2✔
304
            '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ!?_#'
2✔
305
        );
2✔
306
    }
307

308
    /**
309
     * Append an random string.
310
     *
311
     * EXAMPLE: <code>
312
     * s('')->appendUniqueIdentifier(5, 'ABCDEFGHI'); // e.g.: 'CDEHI'
313
     * </code>
314
     *
315
     * @param int    $length        <p>Length of the random string.</p>
316
     * @param string $possibleChars [optional] <p>Characters string for the random selection.</p>
317
     *
318
     * @return static
319
     *                <p>Object with appended random string.</p>
320
     */
321
    public function appendRandomString(int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): self
322
    {
323
        if ($length <= 0 || $possibleChars === '') {
10✔
324
            return $this->append('');
6✔
325
        }
326

327
        $str = $this->utf8::get_random_string($length, $possibleChars);
6✔
328

329
        return $this->append($str);
6✔
330
    }
331

332
    /**
333
     * Returns a new string with $suffix appended.
334
     *
335
     * EXAMPLE: <code>
336
     * </code>
337
     *
338
     * @param CollectionStringy|static ...$suffix <p>The Stringy objects to append.</p>
339
     *
340
     * @phpstan-param CollectionStringy<int,static>|static ...$suffix
341
     *
342
     * @psalm-mutation-free
343
     *
344
     * @return static
345
     *                <p>Object with appended $suffix.</p>
346
     */
347
    public function appendStringy(...$suffix): self
348
    {
349
        $suffixStr = '';
8✔
350
        foreach ($suffix as $suffixTmp) {
8✔
351
            if ($suffixTmp instanceof CollectionStringy) {
8✔
352
                $suffixStr .= $suffixTmp->implode('');
1✔
353
            } else {
354
                $suffixStr .= $suffixTmp->toString();
8✔
355
            }
356
        }
357

358
        return static::create($this->str . $suffixStr, $this->encoding);
8✔
359
    }
360

361
    /**
362
     * Append an unique identifier.
363
     *
364
     * EXAMPLE: <code>
365
     * s('')->appendUniqueIdentifier(); // e.g.: '1f3870be274f6c49b3e31a0c6728957f'
366
     * </code>
367
     *
368
     * @param int|string $entropyExtra [optional] <p>Extra entropy via a string or int value.</p>
369
     * @param bool       $md5          [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
370
     *
371
     * @return static
372
     *                <p>Object with appended unique identifier as md5-hash.</p>
373
     */
374
    public function appendUniqueIdentifier($entropyExtra = '', bool $md5 = true): self
375
    {
376
        return $this->append(
2✔
377
            $this->utf8::get_unique_string($entropyExtra, $md5)
2✔
378
        );
2✔
379
    }
380

381
    /**
382
     * Returns the character at $index, with indexes starting at 0.
383
     *
384
     * EXAMPLE: <code>
385
     * s('fòôbàř')->at(3); // 'b'
386
     * </code>
387
     *
388
     * @param int $index <p>Position of the character.</p>
389
     *
390
     * @psalm-mutation-free
391
     *
392
     * @return static
393
     *                <p>The character at $index.</p>
394
     */
395
    public function at(int $index): self
396
    {
397
        return static::create(
32✔
398
            $this->utf8::substr($this->str, $index, 1, $this->encoding),
32✔
399
            $this->encoding
32✔
400
        );
32✔
401
    }
402

403
    /**
404
     * Decode the base64 encoded string.
405
     *
406
     * EXAMPLE: <code>
407
     * </code>
408
     *
409
     * @psalm-mutation-free
410
     *
411
     * @return self
412
     */
413
    public function base64Decode(): self
414
    {
415
        return static::create(
2✔
416
            \base64_decode($this->str, true),
2✔
417
            $this->encoding
2✔
418
        );
2✔
419
    }
420

421
    /**
422
     * Encode the string to base64.
423
     *
424
     * EXAMPLE: <code>
425
     * </code>
426
     *
427
     * @psalm-mutation-free
428
     *
429
     * @return self
430
     */
431
    public function base64Encode(): self
432
    {
433
        return static::create(
2✔
434
            \base64_encode($this->str),
2✔
435
            $this->encoding
2✔
436
        );
2✔
437
    }
438

439
    /**
440
     * Creates a hash from the string using the CRYPT_BLOWFISH algorithm.
441
     *
442
     * WARNING: Using this algorithm, will result in the ```$this->str```
443
     *          being truncated to a maximum length of 72 characters.
444
     *
445
     * EXAMPLE: <code>
446
     * </code>
447
     *
448
     * @param array<array-key, int|string> $options [optional] <p>An array of bcrypt hashing options.</p>
449
     *
450
     * @psalm-mutation-free
451
     *
452
     * @return static
453
     */
454
    public function bcrypt(array $options = []): self
455
    {
456
        return new static(
3✔
457
            \password_hash(
3✔
458
                $this->str,
3✔
459
                \PASSWORD_BCRYPT,
3✔
460
                $options
3✔
461
            ),
3✔
462
            $this->encoding
3✔
463
        );
3✔
464
    }
465

466
    /**
467
     * Return part of the string occurring before a specific string.
468
     *
469
     * EXAMPLE: <code>
470
     * </code>
471
     *
472
     * @param string $string <p>The delimiting string.</p>
473
     *
474
     * @psalm-mutation-free
475
     *
476
     * @return static
477
     */
478
    public function before(string $string): self
479
    {
480
        return $this->beforeFirst($string);
5✔
481
    }
482

483
    /**
484
     * Gets the substring before the first occurrence of a separator.
485
     * If no match is found returns new empty Stringy object.
486
     *
487
     * EXAMPLE: <code>
488
     * s('</b></b>')->beforeFirst('b'); // '</'
489
     * </code>
490
     *
491
     * @param string $separator
492
     *
493
     * @psalm-mutation-free
494
     *
495
     * @return static
496
     */
497
    public function beforeFirst(string $separator): self
498
    {
499
        return static::create(
7✔
500
            $this->utf8::str_substr_before_first_separator(
7✔
501
                $this->str,
7✔
502
                $separator,
7✔
503
                $this->encoding
7✔
504
            ),
7✔
505
            $this->encoding
7✔
506
        );
7✔
507
    }
508

509
    /**
510
     * Gets the substring before the first occurrence of a separator.
511
     * If no match is found returns new empty Stringy object.
512
     *
513
     * EXAMPLE: <code>
514
     * s('</B></B>')->beforeFirstIgnoreCase('b'); // '</'
515
     * </code>
516
     *
517
     * @param string $separator
518
     *
519
     * @psalm-mutation-free
520
     *
521
     * @return static
522
     */
523
    public function beforeFirstIgnoreCase(string $separator): self
524
    {
525
        return static::create(
2✔
526
            $this->utf8::str_isubstr_before_first_separator(
2✔
527
                $this->str,
2✔
528
                $separator,
2✔
529
                $this->encoding
2✔
530
            )
2✔
531
        );
2✔
532
    }
533

534
    /**
535
     * Gets the substring before the last occurrence of a separator.
536
     * If no match is found returns new empty Stringy object.
537
     *
538
     * EXAMPLE: <code>
539
     * s('</b></b>')->beforeLast('b'); // '</b></'
540
     * </code>
541
     *
542
     * @param string $separator
543
     *
544
     * @psalm-mutation-free
545
     *
546
     * @return static
547
     */
548
    public function beforeLast(string $separator): self
549
    {
550
        return static::create(
2✔
551
            $this->utf8::str_substr_before_last_separator(
2✔
552
                $this->str,
2✔
553
                $separator,
2✔
554
                $this->encoding
2✔
555
            )
2✔
556
        );
2✔
557
    }
558

559
    /**
560
     * Gets the substring before the last occurrence of a separator.
561
     * If no match is found returns new empty Stringy object.
562
     *
563
     * EXAMPLE: <code>
564
     * s('</B></B>')->beforeLastIgnoreCase('b'); // '</B></'
565
     * </code>
566
     *
567
     * @param string $separator
568
     *
569
     * @psalm-mutation-free
570
     *
571
     * @return static
572
     */
573
    public function beforeLastIgnoreCase(string $separator): self
574
    {
575
        return static::create(
2✔
576
            $this->utf8::str_isubstr_before_last_separator(
2✔
577
                $this->str,
2✔
578
                $separator,
2✔
579
                $this->encoding
2✔
580
            )
2✔
581
        );
2✔
582
    }
583

584
    /**
585
     * Returns the substring between $start and $end, if found, or an empty
586
     * string. An optional offset may be supplied from which to begin the
587
     * search for the start string.
588
     *
589
     * EXAMPLE: <code>
590
     * s('{foo} and {bar}')->between('{', '}'); // 'foo'
591
     * </code>
592
     *
593
     * @param string $start  <p>Delimiter marking the start of the substring.</p>
594
     * @param string $end    <p>Delimiter marking the end of the substring.</p>
595
     * @param int    $offset [optional] <p>Index from which to begin the search. Default: 0</p>
596
     *
597
     * @psalm-mutation-free
598
     *
599
     * @return static
600
     *                <p>Object whose $str is a substring between $start and $end.</p>
601
     */
602
    public function between(string $start, string $end, ?int $offset = null): self
603
    {
604
        $str = $this->utf8::between(
48✔
605
            $this->str,
48✔
606
            $start,
48✔
607
            $end,
48✔
608
            (int) $offset,
48✔
609
            $this->encoding
48✔
610
        );
48✔
611

612
        return static::create($str, $this->encoding);
48✔
613
    }
614

615
    /**
616
     * Call a user function.
617
     *
618
     * EXAMPLE: <code>
619
     * S::create('foo bar lall')->callUserFunction(static function ($str) {
620
     *     return UTF8::str_limit($str, 8);
621
     * })->toString(); // "foo bar…"
622
     * </code>
623
     *
624
     * @param callable $function
625
     * @param mixed    ...$parameter
626
     *
627
     * @psalm-mutation-free
628
     *
629
     * @return static
630
     *                <p>Object having a $str changed via $function.</p>
631
     */
632
    public function callUserFunction(callable $function, ...$parameter): self
633
    {
634
        $str = $function($this->str, ...$parameter);
2✔
635

636
        return static::create(
2✔
637
            $str,
2✔
638
            $this->encoding
2✔
639
        );
2✔
640
    }
641

642
    /**
643
     * Returns a camelCase version of the string. Trims surrounding spaces,
644
     * capitalizes letters following digits, spaces, dashes and underscores,
645
     * and removes spaces, dashes, as well as underscores.
646
     *
647
     * EXAMPLE: <code>
648
     * s('Camel-Case')->camelize(); // 'camelCase'
649
     * </code>
650
     *
651
     * @psalm-mutation-free
652
     *
653
     * @return static
654
     *                <p>Object with $str in camelCase.</p>
655
     */
656
    public function camelize(): self
657
    {
658
        return static::create(
67✔
659
            $this->utf8::str_camelize($this->str, $this->encoding),
67✔
660
            $this->encoding
67✔
661
        );
67✔
662
    }
663

664
    /**
665
     * Returns the string with the first letter of each word capitalized,
666
     * except for when the word is a name which shouldn't be capitalized.
667
     *
668
     * EXAMPLE: <code>
669
     * s('jaap de hoop scheffer')->capitalizePersonName(); // 'Jaap de Hoop Scheffer'
670
     * </code>
671
     *
672
     * @psalm-mutation-free
673
     *
674
     * @return static
675
     *                <p>Object with $str capitalized.</p>
676
     */
677
    public function capitalizePersonalName(): self
678
    {
679
        return static::create(
78✔
680
            $this->utf8::str_capitalize_name($this->str),
78✔
681
            $this->encoding
78✔
682
        );
78✔
683
    }
684

685
    /**
686
     * Returns an array consisting of the characters in the string.
687
     *
688
     * EXAMPLE: <code>
689
     * s('fòôbàř')->chars(); // ['f', 'ò', 'ô', 'b', 'à', 'ř']
690
     * </code>
691
     *
692
     * @psalm-mutation-free
693
     *
694
     * @return string[]
695
     *                  <p>An array of string chars.</p>
696
     */
697
    public function chars(): array
698
    {
699
        /** @var string[] */
700
        return $this->utf8::str_split($this->str);
14✔
701
    }
702

703
    /**
704
     * Splits the string into chunks of Stringy objects.
705
     *
706
     * EXAMPLE: <code>
707
     * s('foobar')->chunk(3); // ['foo', 'bar']
708
     * </code>
709
     *
710
     * @param int $length [optional] <p>Max character length of each array element.</p>
711
     *
712
     * @psalm-mutation-free
713
     *
714
     * @return static[]
715
     *                  <p>An array of Stringy objects.</p>
716
     *
717
     * @phpstan-return array<int,static>
718
     */
719
    public function chunk(int $length = 1): array
720
    {
721
        if ($length < 1) {
15✔
722
            throw new \InvalidArgumentException('The chunk length must be greater than zero.');
×
723
        }
724

725
        $chunks = $this->utf8::str_split($this->str, $length);
15✔
726

727
        foreach ($chunks as &$value) {
15✔
728
            $value = static::create($value, $this->encoding);
13✔
729
        }
730

731
        /** @noinspection PhpSillyAssignmentInspection */
732
        /** @var static[] $chunks */
733
        $chunks = $chunks;
15✔
734

735
        return $chunks;
15✔
736
    }
737

738
    /**
739
     * Splits the string into chunks of Stringy objects collection.
740
     *
741
     * EXAMPLE: <code>
742
     * </code>
743
     *
744
     * @param int $length [optional] <p>Max character length of each array element.</p>
745
     *
746
     * @psalm-mutation-free
747
     *
748
     * @return CollectionStringy|static[]
749
     *                                    <p>An collection of Stringy objects.</p>
750
     *
751
     * @phpstan-return CollectionStringy<int,static>
752
     */
753
    public function chunkCollection(int $length = 1): CollectionStringy
754
    {
755
        /**
756
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
757
         */
758
        return CollectionStringy::create(
8✔
759
            $this->chunk($length)
8✔
760
        );
8✔
761
    }
762

763
    /**
764
     * Trims the string and replaces consecutive whitespace characters with a
765
     * single space. This includes tabs and newline characters, as well as
766
     * multibyte whitespace such as the thin space and ideographic space.
767
     *
768
     * EXAMPLE: <code>
769
     * s('   Ο     συγγραφέας  ')->collapseWhitespace(); // 'Ο συγγραφέας'
770
     * </code>
771
     *
772
     * @psalm-mutation-free
773
     *
774
     * @return static
775
     *                <p>Object with a trimmed $str and condensed whitespace.</p>
776
     */
777
    public function collapseWhitespace(): self
778
    {
779
        return static::create(
39✔
780
            $this->utf8::collapse_whitespace($this->str),
39✔
781
            $this->encoding
39✔
782
        );
39✔
783
    }
784

785
    /**
786
     * Returns true if the string contains $needle, false otherwise. By default
787
     * the comparison is case-sensitive, but can be made insensitive by setting
788
     * $caseSensitive to false.
789
     *
790
     * EXAMPLE: <code>
791
     * s('Ο συγγραφέας είπε')->contains('συγγραφέας'); // true
792
     * </code>
793
     *
794
     * @param string $needle        <p>Substring to look for.</p>
795
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
796
     *
797
     * @psalm-mutation-free
798
     *
799
     * @return bool
800
     *              <p>Whether or not $str contains $needle.</p>
801
     */
802
    public function contains(string $needle, bool $caseSensitive = true): bool
803
    {
804
        return $this->utf8::str_contains(
64✔
805
            $this->str,
64✔
806
            $needle,
64✔
807
            $caseSensitive
64✔
808
        );
64✔
809
    }
810

811
    /**
812
     * Returns true if the string contains all $needles, false otherwise. By
813
     * default the comparison is case-sensitive, but can be made insensitive by
814
     * setting $caseSensitive to false.
815
     *
816
     * EXAMPLE: <code>
817
     * s('foo & bar')->containsAll(['foo', 'bar']); // true
818
     * </code>
819
     *
820
     * @param string[] $needles       <p>SubStrings to look for.</p>
821
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
822
     *
823
     * @psalm-mutation-free
824
     *
825
     * @return bool
826
     *              <p>Whether or not $str contains $needle.</p>
827
     */
828
    public function containsAll(array $needles, bool $caseSensitive = true): bool
829
    {
830
        return $this->utf8::str_contains_all(
132✔
831
            $this->str,
132✔
832
            $needles,
132✔
833
            $caseSensitive
132✔
834
        );
132✔
835
    }
836

837
    /**
838
     * Returns true if the string contains any $needles, false otherwise. By
839
     * default the comparison is case-sensitive, but can be made insensitive by
840
     * setting $caseSensitive to false.
841
     *
842
     * EXAMPLE: <code>
843
     * s('str contains foo')->containsAny(['foo', 'bar']); // true
844
     * </code>
845
     *
846
     * @param string[] $needles       <p>SubStrings to look for.</p>
847
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
848
     *
849
     * @psalm-mutation-free
850
     *
851
     * @return bool
852
     *              <p>Whether or not $str contains $needle.</p>
853
     */
854
    public function containsAny(array $needles, bool $caseSensitive = true): bool
855
    {
856
        return $this->utf8::str_contains_any(
130✔
857
            $this->str,
130✔
858
            $needles,
130✔
859
            $caseSensitive
130✔
860
        );
130✔
861
    }
862

863
    /**
864
     * Checks if string starts with "BOM" (Byte Order Mark Character) character.
865
     *
866
     * EXAMPLE: <code>s("\xef\xbb\xbf foobar")->containsBom(); // true</code>
867
     *
868
     * @psalm-mutation-free
869
     *
870
     * @return bool
871
     *              <strong>true</strong> if the string has BOM at the start,<br>
872
     *              <strong>false</strong> otherwise
873
     */
874
    public function containsBom(): bool
875
    {
876
        return $this->utf8::string_has_bom($this->str);
×
877
    }
878

879
    /**
880
     * Returns the length of the string, implementing the countable interface.
881
     *
882
     * EXAMPLE: <code>
883
     * </code>
884
     *
885
     * @psalm-mutation-free
886
     *
887
     * @return int
888
     *             <p>The number of characters in the string, given the encoding.</p>
889
     */
890
    public function count(): int
891
    {
892
        return $this->length();
3✔
893
    }
894

895
    /**
896
     * Returns the number of occurrences of $substring in the given string.
897
     * By default, the comparison is case-sensitive, but can be made insensitive
898
     * by setting $caseSensitive to false.
899
     *
900
     * EXAMPLE: <code>
901
     * s('Ο συγγραφέας είπε')->countSubstr('α'); // 2
902
     * </code>
903
     *
904
     * @param string $substring     <p>The substring to search for.</p>
905
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
906
     *
907
     * @psalm-mutation-free
908
     *
909
     * @return int
910
     */
911
    public function countSubstr(string $substring, bool $caseSensitive = true): int
912
    {
913
        return $this->utf8::substr_count_simple(
46✔
914
            $this->str,
46✔
915
            $substring,
46✔
916
            $caseSensitive,
46✔
917
            $this->encoding
46✔
918
        );
46✔
919
    }
920

921
    /**
922
     * Calculates the crc32 polynomial of a string.
923
     *
924
     * EXAMPLE: <code>
925
     * </code>
926
     *
927
     * @psalm-mutation-free
928
     *
929
     * @return int
930
     */
931
    public function crc32(): int
932
    {
933
        return \crc32($this->str);
2✔
934
    }
935

936
    /**
937
     * Creates a Stringy object and assigns both str and encoding properties
938
     * the supplied values. $str is cast to a string prior to assignment, and if
939
     * $encoding is not specified, it defaults to mb_internal_encoding(). It
940
     * then returns the initialized object. Throws an InvalidArgumentException
941
     * if the first argument is an array or object without a __toString method.
942
     *
943
     * @param mixed  $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
944
     * @param string $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
945
     *
946
     * @throws \InvalidArgumentException
947
     *                                   <p>if an array or object without a
948
     *                                   __toString method is passed as the first argument</p>
949
     *
950
     * @return static
951
     *                <p>A Stringy object.</p>
952
     */
953
    public static function create($str = '', ?string $encoding = null): self
954
    {
955
        return new static($str, $encoding);
3,641✔
956
    }
957

958
    /**
959
     * One-way string encryption (hashing).
960
     *
961
     * Hash the string using the standard Unix DES-based algorithm or an
962
     * alternative algorithm that may be available on the system.
963
     *
964
     * PS: if you need encrypt / decrypt, please use ```static::encrypt($password)```
965
     *     and ```static::decrypt($password)```
966
     *
967
     * EXAMPLE: <code>
968
     * </code>
969
     *
970
     * @param string $salt <p>A salt string to base the hashing on.</p>
971
     *
972
     * @psalm-mutation-free
973
     *
974
     * @return static
975
     */
976
    public function crypt(string $salt): self
977
    {
978
        return new static(
3✔
979
            \crypt(
3✔
980
                $this->str,
3✔
981
                $salt
3✔
982
            ),
3✔
983
            $this->encoding
3✔
984
        );
3✔
985
    }
986

987
    /**
988
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
989
     * inserted before uppercase characters (with the exception of the first
990
     * character of the string), and in place of spaces as well as underscores.
991
     *
992
     * EXAMPLE: <code>
993
     * s('fooBar')->dasherize(); // 'foo-bar'
994
     * </code>
995
     *
996
     * @psalm-mutation-free
997
     *
998
     * @return static
999
     *                <p>Object with a dasherized $str</p>
1000
     */
1001
    public function dasherize(): self
1002
    {
1003
        return static::create(
57✔
1004
            $this->utf8::str_dasherize($this->str),
57✔
1005
            $this->encoding
57✔
1006
        );
57✔
1007
    }
1008

1009
    /**
1010
     * Decrypt the string.
1011
     *
1012
     * EXAMPLE: <code>
1013
     * </code>
1014
     *
1015
     * @param string $password The key for decrypting
1016
     *
1017
     * @psalm-mutation-free
1018
     *
1019
     * @return static
1020
     */
1021
    public function decrypt(string $password): self
1022
    {
1023
        /**
1024
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff
1025
         */
1026
        return new static(
5✔
1027
            Crypto::decryptWithPassword($this->str, $password),
5✔
1028
            $this->encoding
5✔
1029
        );
5✔
1030
    }
1031

1032
    /**
1033
     * Returns a lowercase and trimmed string separated by the given delimiter.
1034
     * Delimiters are inserted before uppercase characters (with the exception
1035
     * of the first character of the string), and in place of spaces, dashes,
1036
     * and underscores. Alpha delimiters are not converted to lowercase.
1037
     *
1038
     * EXAMPLE: <code>
1039
     * s('fooBar')->delimit('::'); // 'foo::bar'
1040
     * </code>
1041
     *
1042
     * @param string $delimiter <p>Sequence used to separate parts of the string.</p>
1043
     *
1044
     * @psalm-mutation-free
1045
     *
1046
     * @return static
1047
     *                <p>Object with a delimited $str.</p>
1048
     */
1049
    public function delimit(string $delimiter): self
1050
    {
1051
        return static::create(
90✔
1052
            $this->utf8::str_delimit($this->str, $delimiter),
90✔
1053
            $this->encoding
90✔
1054
        );
90✔
1055
    }
1056

1057
    /**
1058
     * Encode the given string into the given $encoding + set the internal character encoding.
1059
     *
1060
     * EXAMPLE: <code>
1061
     * </code>
1062
     *
1063
     * @param string $new_encoding         <p>The desired character encoding.</p>
1064
     * @param bool   $auto_detect_encoding [optional] <p>Auto-detect the current string-encoding</p>
1065
     *
1066
     * @psalm-mutation-free
1067
     *
1068
     * @return static
1069
     */
1070
    public function encode(string $new_encoding, bool $auto_detect_encoding = false): self
1071
    {
1072
        $str = $this->utf8::encode(
3✔
1073
            $new_encoding,
3✔
1074
            $this->str,
3✔
1075
            $auto_detect_encoding,
3✔
1076
            $auto_detect_encoding ? '' : $this->encoding
3✔
1077
        );
3✔
1078

1079
        return new static($str, $new_encoding);
3✔
1080
    }
1081

1082
    /**
1083
     * Encrypt the string.
1084
     *
1085
     * EXAMPLE: <code>
1086
     * </code>
1087
     *
1088
     * @param string $password <p>The key for encrypting</p>
1089
     *
1090
     * @psalm-mutation-free
1091
     *
1092
     * @return static
1093
     */
1094
    public function encrypt(string $password): self
1095
    {
1096
        /**
1097
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff
1098
         */
1099
        return new static(
4✔
1100
            Crypto::encryptWithPassword($this->str, $password),
4✔
1101
            $this->encoding
4✔
1102
        );
4✔
1103
    }
1104

1105
    /**
1106
     * Returns true if the string ends with $substring, false otherwise. By
1107
     * default, the comparison is case-sensitive, but can be made insensitive
1108
     * by setting $caseSensitive to false.
1109
     *
1110
     * EXAMPLE: <code>
1111
     * s('fòôbàř')->endsWith('bàř', true); // true
1112
     * </code>
1113
     *
1114
     * @param string $substring     <p>The substring to look for.</p>
1115
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1116
     *
1117
     * @psalm-mutation-free
1118
     *
1119
     * @return bool
1120
     *              <p>Whether or not $str ends with $substring.</p>
1121
     */
1122
    public function endsWith(string $substring, bool $caseSensitive = true): bool
1123
    {
1124
        if ($caseSensitive) {
97✔
1125
            return $this->utf8::str_ends_with($this->str, $substring);
53✔
1126
        }
1127

1128
        return $this->utf8::str_iends_with($this->str, $substring);
44✔
1129
    }
1130

1131
    /**
1132
     * Returns true if the string ends with any of $substrings, false otherwise.
1133
     * By default, the comparison is case-sensitive, but can be made insensitive
1134
     * by setting $caseSensitive to false.
1135
     *
1136
     * EXAMPLE: <code>
1137
     * s('fòôbàř')->endsWithAny(['bàř', 'baz'], true); // true
1138
     * </code>
1139
     *
1140
     * @param string[] $substrings    <p>Substrings to look for.</p>
1141
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1142
     *
1143
     * @psalm-mutation-free
1144
     *
1145
     * @return bool
1146
     *              <p>Whether or not $str ends with $substring.</p>
1147
     */
1148
    public function endsWithAny(array $substrings, bool $caseSensitive = true): bool
1149
    {
1150
        if ($caseSensitive) {
34✔
1151
            return $this->utf8::str_ends_with_any($this->str, $substrings);
22✔
1152
        }
1153

1154
        return $this->utf8::str_iends_with_any($this->str, $substrings);
12✔
1155
    }
1156

1157
    /**
1158
     * Ensures that the string begins with $substring. If it doesn't, it's
1159
     * prepended.
1160
     *
1161
     * EXAMPLE: <code>
1162
     * s('foobar')->ensureLeft('http://'); // 'http://foobar'
1163
     * </code>
1164
     *
1165
     * @param string $substring <p>The substring to add if not present.</p>
1166
     *
1167
     * @psalm-mutation-free
1168
     *
1169
     * @return static
1170
     *                <p>Object with its $str prefixed by the $substring.</p>
1171
     */
1172
    public function ensureLeft(string $substring): self
1173
    {
1174
        return static::create(
30✔
1175
            $this->utf8::str_ensure_left($this->str, $substring),
30✔
1176
            $this->encoding
30✔
1177
        );
30✔
1178
    }
1179

1180
    /**
1181
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
1182
     *
1183
     * EXAMPLE: <code>
1184
     * s('foobar')->ensureRight('.com'); // 'foobar.com'
1185
     * </code>
1186
     *
1187
     * @param string $substring <p>The substring to add if not present.</p>
1188
     *
1189
     * @psalm-mutation-free
1190
     *
1191
     * @return static
1192
     *                <p>Object with its $str suffixed by the $substring.</p>
1193
     */
1194
    public function ensureRight(string $substring): self
1195
    {
1196
        return static::create(
30✔
1197
            $this->utf8::str_ensure_right($this->str, $substring),
30✔
1198
            $this->encoding
30✔
1199
        );
30✔
1200
    }
1201

1202
    /**
1203
     * Create a escape html version of the string via "htmlspecialchars()".
1204
     *
1205
     * EXAMPLE: <code>
1206
     * s('<∂∆ onerror="alert(xss)">')->escape(); // '&lt;∂∆ onerror=&quot;alert(xss)&quot;&gt;'
1207
     * </code>
1208
     *
1209
     * @psalm-mutation-free
1210
     *
1211
     * @return static
1212
     */
1213
    public function escape(): self
1214
    {
1215
        return static::create(
12✔
1216
            $this->utf8::htmlspecialchars(
12✔
1217
                $this->str,
12✔
1218
                \ENT_QUOTES | \ENT_SUBSTITUTE,
12✔
1219
                $this->encoding
12✔
1220
            ),
12✔
1221
            $this->encoding
12✔
1222
        );
12✔
1223
    }
1224

1225
    /**
1226
     * Split a string by a string.
1227
     *
1228
     * EXAMPLE: <code>
1229
     * </code>
1230
     *
1231
     * @param string $delimiter <p>The boundary string</p>
1232
     * @param int    $limit     [optional] <p>The maximum number of elements in the exploded
1233
     *                          collection.</p>
1234
     *
1235
     *   - If limit is set and positive, the returned collection will contain a maximum of limit elements with the last
1236
     *   element containing the rest of string.
1237
     *   - If the limit parameter is negative, all components except the last -limit are returned.
1238
     *   - If the limit parameter is zero, then this is treated as 1
1239
     *
1240
     * @psalm-mutation-free
1241
     *
1242
     * @return array<int,static>
1243
     */
1244
    public function explode(string $delimiter, int $limit = \PHP_INT_MAX): array
1245
    {
1246
        if ($this->str === '') {
3✔
1247
            return [];
×
1248
        }
1249

1250
        /** @phpstan-ignore-next-line - FP -> non-empty-string is already checked */
1251
        $strings = \explode($delimiter, $this->str, $limit);
3✔
1252
        /** @phpstan-ignore-next-line - if "$delimiter" is an empty string, then "explode()" will return "false" */
1253
        if ($strings === false) {
3✔
1254
            $strings = [];
×
1255
        }
1256

1257
        return \array_map(
3✔
1258
            function ($str) {
3✔
1259
                return new static($str, $this->encoding);
3✔
1260
            },
3✔
1261
            $strings
3✔
1262
        );
3✔
1263
    }
1264

1265
    /**
1266
     * Split a string by a string.
1267
     *
1268
     * EXAMPLE: <code>
1269
     * </code>
1270
     *
1271
     * @param string $delimiter <p>The boundary string</p>
1272
     * @param int    $limit     [optional] <p>The maximum number of elements in the exploded
1273
     *                          collection.</p>
1274
     *
1275
     *   - If limit is set and positive, the returned collection will contain a maximum of limit elements with the last
1276
     *   element containing the rest of string.
1277
     *   - If the limit parameter is negative, all components except the last -limit are returned.
1278
     *   - If the limit parameter is zero, then this is treated as 1
1279
     *
1280
     * @psalm-mutation-free
1281
     *
1282
     * @return CollectionStringy|static[]
1283
     *                                    <p>An collection of Stringy objects.</p>
1284
     *
1285
     * @phpstan-return CollectionStringy<int,static>
1286
     */
1287
    public function explodeCollection(string $delimiter, int $limit = \PHP_INT_MAX): CollectionStringy
1288
    {
1289
        /**
1290
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
1291
         */
1292
        return CollectionStringy::create(
1✔
1293
            $this->explode($delimiter, $limit)
1✔
1294
        );
1✔
1295
    }
1296

1297
    /**
1298
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1299
     *
1300
     * EXAMPLE: <code>
1301
     * $sentence = 'This is only a Fork of Stringy, take a look at the new features.';
1302
     * s($sentence)->extractText('Stringy'); // '...Fork of Stringy...'
1303
     * </code>
1304
     *
1305
     * @param string   $search
1306
     * @param int|null $length                 [optional] <p>Default: null === text->length / 2</p>
1307
     * @param string   $replacerForSkippedText [optional] <p>Default: …</p>
1308
     *
1309
     * @psalm-mutation-free
1310
     *
1311
     * @return static
1312
     */
1313
    public function extractText(string $search = '', ?int $length = null, string $replacerForSkippedText = '…'): self
1314
    {
1315
        return static::create(
2✔
1316
            $this->utf8::extract_text(
2✔
1317
                $this->str,
2✔
1318
                $search,
2✔
1319
                $length,
2✔
1320
                $replacerForSkippedText,
2✔
1321
                $this->encoding
2✔
1322
            ),
2✔
1323
            $this->encoding
2✔
1324
        );
2✔
1325
    }
1326

1327
    /**
1328
     * Returns the first $n characters of the string.
1329
     *
1330
     * EXAMPLE: <code>
1331
     * s('fòôbàř')->first(3); // 'fòô'
1332
     * </code>
1333
     *
1334
     * @param int $n <p>Number of characters to retrieve from the start.</p>
1335
     *
1336
     * @psalm-mutation-free
1337
     *
1338
     * @return static
1339
     *                <p>Object with its $str being the first $n chars.</p>
1340
     */
1341
    public function first(int $n): self
1342
    {
1343
        if ($n <= 0) {
37✔
1344
            return static::create('', $this->encoding);
12✔
1345
        }
1346

1347
        return static::create(
25✔
1348
            $this->utf8::first_char($this->str, $n, $this->encoding),
25✔
1349
            $this->encoding
25✔
1350
        );
25✔
1351
    }
1352

1353
    /**
1354
     * Return a formatted string via sprintf + named parameters via array syntax.
1355
     *
1356
     * <p>
1357
     * <br>
1358
     * It will use "sprintf()" so you can use e.g.:
1359
     * <br>
1360
     * <br><pre>s('There are %d monkeys in the %s')->format(5, 'tree');</pre>
1361
     * <br>
1362
     * <br><pre>s('There are %2$d monkeys in the %1$s')->format('tree', 5);</pre>
1363
     * <br>
1364
     * <br>
1365
     * But you can also use named parameter via array syntax e.g.:
1366
     * <br>
1367
     * <br><pre>s('There are %:count monkeys in the %:location')->format(['count' => 5, 'location' => 'tree');</pre>
1368
     * </p>
1369
     *
1370
     * EXAMPLE: <code>
1371
     * $input = 'one: %2$d, %1$s: 2, %:text_three: %3$d';
1372
     * s($input)->format(['text_three' => '%4$s'], 'two', 1, 3, 'three'); // 'One: 1, two: 2, three: 3'
1373
     * </code>
1374
     *
1375
     * @param mixed ...$args [optional]
1376
     *
1377
     * @psalm-mutation-free
1378
     *
1379
     * @return static
1380
     *                <p>A Stringy object produced according to the formatting string
1381
     *                format.</p>
1382
     */
1383
    public function format(...$args): self
1384
    {
1385
        // init
1386
        $str = $this->str;
13✔
1387

1388
        if (\strpos($this->str, '%:') !== false) {
13✔
1389
            $namedArgs = [];
11✔
1390
            /** @noinspection AlterInForeachInspection */
1391
            foreach ($args as $key => &$arg) {
11✔
1392
                if (!\is_array($arg)) {
11✔
1393
                    continue;
4✔
1394
                }
1395

1396
                foreach ($arg as $name => $param) {
11✔
1397
                    $name = (string) $name;
11✔
1398

1399
                    if (\strpos($name, '%:') === 0) {
11✔
NEW
1400
                        $name = (string) \substr($name, 2);
×
1401
                    }
1402

1403
                    if (\array_key_exists($name, $namedArgs)) {
11✔
UNCOV
1404
                        continue;
×
1405
                    }
1406

1407
                    $namedArgs[$name] = (string) $param;
11✔
1408
                }
1409

1410
                unset($args[$key]);
11✔
1411
            }
1412

1413
            if ($namedArgs !== []) {
11✔
1414
                $usedNames = [];
11✔
1415
                $formattedStr = \preg_replace_callback(
11✔
1416
                    '/%:([0-9A-Za-z_]+)/',
11✔
1417
                    static function (array $matches) use (&$namedArgs, &$usedNames): string {
11✔
1418
                        $name = $matches[1];
11✔
1419
                        if (($usedNames[$name] ?? false) === true || !\array_key_exists($name, $namedArgs)) {
11✔
1420
                            return $matches[0];
6✔
1421
                        }
1422

1423
                        $usedNames[$name] = true;
11✔
1424

1425
                        return $namedArgs[$name];
11✔
1426
                    },
11✔
1427
                    $str
11✔
1428
                );
11✔
1429
                if ($formattedStr !== null) {
11✔
1430
                    $str = $formattedStr;
11✔
1431
                }
1432
            }
1433
        }
1434

1435
        $str = \str_replace('%:', '%%:', $str);
13✔
1436

1437
        return static::create(
13✔
1438
            \sprintf($str, ...$args),
13✔
1439
            $this->encoding
13✔
1440
        );
13✔
1441
    }
1442

1443
    /**
1444
     * Returns the encoding used by the Stringy object.
1445
     *
1446
     * EXAMPLE: <code>
1447
     * s('fòôbàř', 'UTF-8')->getEncoding(); // 'UTF-8'
1448
     * </code>
1449
     *
1450
     * @psalm-mutation-free
1451
     *
1452
     * @return string
1453
     *                <p>The current value of the $encoding property.</p>
1454
     */
1455
    public function getEncoding(): string
1456
    {
1457
        return $this->encoding;
25✔
1458
    }
1459

1460
    /**
1461
     * Returns a new ArrayIterator, thus implementing the IteratorAggregate
1462
     * interface. The ArrayIterator's constructor is passed an array of chars
1463
     * in the multibyte string. This enables the use of foreach with instances
1464
     * of Stringy\Stringy.
1465
     *
1466
     * EXAMPLE: <code>
1467
     * </code>
1468
     *
1469
     * @psalm-mutation-free
1470
     *
1471
     * @return \ArrayIterator
1472
     *                        <p>An iterator for the characters in the string.</p>
1473
     *
1474
     * @phpstan-return \ArrayIterator<array-key,string>
1475
     */
1476
    public function getIterator(): \ArrayIterator
1477
    {
1478
        return new \ArrayIterator($this->chars());
3✔
1479
    }
1480

1481
    /**
1482
     * Wrap the string after an exact number of characters.
1483
     *
1484
     * EXAMPLE: <code>
1485
     * </code>
1486
     *
1487
     * @param int    $width <p>Number of characters at which to wrap.</p>
1488
     * @param string $break [optional] <p>Character used to break the string. | Default: "\n"</p>
1489
     *
1490
     * @psalm-mutation-free
1491
     *
1492
     * @return static
1493
     */
1494
    public function hardWrap($width, $break = "\n"): self
1495
    {
1496
        return $this->lineWrap($width, $break, false);
2✔
1497
    }
1498

1499
    /**
1500
     * Returns true if the string contains a lower case char, false otherwise
1501
     *
1502
     * EXAMPLE: <code>
1503
     * s('fòôbàř')->hasLowerCase(); // true
1504
     * </code>
1505
     *
1506
     * @psalm-mutation-free
1507
     *
1508
     * @return bool
1509
     *              <p>Whether or not the string contains a lower case character.</p>
1510
     */
1511
    public function hasLowerCase(): bool
1512
    {
1513
        return $this->utf8::has_lowercase($this->str);
36✔
1514
    }
1515

1516
    /**
1517
     * Returns true if the string contains an upper case char, false otherwise.
1518
     *
1519
     * EXAMPLE: <code>
1520
     * s('fòôbàř')->hasUpperCase(); // false
1521
     * </code>
1522
     *
1523
     * @psalm-mutation-free
1524
     *
1525
     * @return bool
1526
     *              <p>Whether or not the string contains an upper case character.</p>
1527
     */
1528
    public function hasUpperCase(): bool
1529
    {
1530
        return $this->utf8::has_uppercase($this->str);
36✔
1531
    }
1532

1533
    /**
1534
     * Generate a hash value (message digest).
1535
     *
1536
     * EXAMPLE: <code>
1537
     * </code>
1538
     *
1539
     * @see https://php.net/manual/en/function.hash.php
1540
     *
1541
     * @param string $algorithm
1542
     *                          <p>Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)</p>
1543
     *
1544
     * @psalm-mutation-free
1545
     *
1546
     * @return static
1547
     */
1548
    public function hash($algorithm): self
1549
    {
1550
        return static::create(\hash($algorithm, $this->str), $this->encoding);
8✔
1551
    }
1552

1553
    /**
1554
     * Decode the string from hex.
1555
     *
1556
     * EXAMPLE: <code>
1557
     * </code>
1558
     *
1559
     * @psalm-mutation-free
1560
     *
1561
     * @return static
1562
     */
1563
    public function hexDecode(): self
1564
    {
1565
        $string = \preg_replace_callback(
3✔
1566
            '/\\\\x(?<hex>[0-9A-Fa-f]+)/',
3✔
1567
            function (array $matched) {
3✔
1568
                return $this->utf8::hex_to_chr($matched['hex']);
3✔
1569
            },
3✔
1570
            $this->str
3✔
1571
        );
3✔
1572

1573
        return static::create(
3✔
1574
            $string,
3✔
1575
            $this->encoding
3✔
1576
        );
3✔
1577
    }
1578

1579
    /**
1580
     * Encode string to hex.
1581
     *
1582
     * EXAMPLE: <code>
1583
     * </code>
1584
     *
1585
     * @psalm-mutation-free
1586
     *
1587
     * @return static
1588
     */
1589
    public function hexEncode(): self
1590
    {
1591
        $string = \array_reduce(
2✔
1592
            $this->chars(),
2✔
1593
            function (string $str, string $char) {
2✔
1594
                return $str . $this->utf8::chr_to_hex($char);
2✔
1595
            },
2✔
1596
            ''
2✔
1597
        );
2✔
1598

1599
        return static::create(
2✔
1600
            $string,
2✔
1601
            $this->encoding
2✔
1602
        );
2✔
1603
    }
1604

1605
    /**
1606
     * Convert all HTML entities to their applicable characters.
1607
     *
1608
     * EXAMPLE: <code>
1609
     * s('&amp;')->htmlDecode(); // '&'
1610
     * </code>
1611
     *
1612
     * @param int $flags [optional] <p>
1613
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
1614
     *                   which document type to use. The default is ENT_COMPAT.
1615
     *                   <table>
1616
     *                   Available <i>flags</i> constants
1617
     *                   <tr valign="top">
1618
     *                   <td>Constant Name</td>
1619
     *                   <td>Description</td>
1620
     *                   </tr>
1621
     *                   <tr valign="top">
1622
     *                   <td><b>ENT_COMPAT</b></td>
1623
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
1624
     *                   </tr>
1625
     *                   <tr valign="top">
1626
     *                   <td><b>ENT_QUOTES</b></td>
1627
     *                   <td>Will convert both double and single quotes.</td>
1628
     *                   </tr>
1629
     *                   <tr valign="top">
1630
     *                   <td><b>ENT_NOQUOTES</b></td>
1631
     *                   <td>Will leave both double and single quotes unconverted.</td>
1632
     *                   </tr>
1633
     *                   <tr valign="top">
1634
     *                   <td><b>ENT_HTML401</b></td>
1635
     *                   <td>
1636
     *                   Handle code as HTML 4.01.
1637
     *                   </td>
1638
     *                   </tr>
1639
     *                   <tr valign="top">
1640
     *                   <td><b>ENT_XML1</b></td>
1641
     *                   <td>
1642
     *                   Handle code as XML 1.
1643
     *                   </td>
1644
     *                   </tr>
1645
     *                   <tr valign="top">
1646
     *                   <td><b>ENT_XHTML</b></td>
1647
     *                   <td>
1648
     *                   Handle code as XHTML.
1649
     *                   </td>
1650
     *                   </tr>
1651
     *                   <tr valign="top">
1652
     *                   <td><b>ENT_HTML5</b></td>
1653
     *                   <td>
1654
     *                   Handle code as HTML 5.
1655
     *                   </td>
1656
     *                   </tr>
1657
     *                   </table>
1658
     *                   </p>
1659
     *
1660
     * @psalm-mutation-free
1661
     *
1662
     * @return static
1663
     *                <p>Object with the resulting $str after being html decoded.</p>
1664
     */
1665
    public function htmlDecode(int $flags = \ENT_COMPAT): self
1666
    {
1667
        return static::create(
15✔
1668
            $this->utf8::html_entity_decode(
15✔
1669
                $this->str,
15✔
1670
                $flags,
15✔
1671
                $this->encoding
15✔
1672
            ),
15✔
1673
            $this->encoding
15✔
1674
        );
15✔
1675
    }
1676

1677
    /**
1678
     * Convert all applicable characters to HTML entities.
1679
     *
1680
     * EXAMPLE: <code>
1681
     * s('&')->htmlEncode(); // '&amp;'
1682
     * </code>
1683
     *
1684
     * @param int $flags [optional] <p>
1685
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
1686
     *                   which document type to use. The default is ENT_COMPAT.
1687
     *                   <table>
1688
     *                   Available <i>flags</i> constants
1689
     *                   <tr valign="top">
1690
     *                   <td>Constant Name</td>
1691
     *                   <td>Description</td>
1692
     *                   </tr>
1693
     *                   <tr valign="top">
1694
     *                   <td><b>ENT_COMPAT</b></td>
1695
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
1696
     *                   </tr>
1697
     *                   <tr valign="top">
1698
     *                   <td><b>ENT_QUOTES</b></td>
1699
     *                   <td>Will convert both double and single quotes.</td>
1700
     *                   </tr>
1701
     *                   <tr valign="top">
1702
     *                   <td><b>ENT_NOQUOTES</b></td>
1703
     *                   <td>Will leave both double and single quotes unconverted.</td>
1704
     *                   </tr>
1705
     *                   <tr valign="top">
1706
     *                   <td><b>ENT_HTML401</b></td>
1707
     *                   <td>
1708
     *                   Handle code as HTML 4.01.
1709
     *                   </td>
1710
     *                   </tr>
1711
     *                   <tr valign="top">
1712
     *                   <td><b>ENT_XML1</b></td>
1713
     *                   <td>
1714
     *                   Handle code as XML 1.
1715
     *                   </td>
1716
     *                   </tr>
1717
     *                   <tr valign="top">
1718
     *                   <td><b>ENT_XHTML</b></td>
1719
     *                   <td>
1720
     *                   Handle code as XHTML.
1721
     *                   </td>
1722
     *                   </tr>
1723
     *                   <tr valign="top">
1724
     *                   <td><b>ENT_HTML5</b></td>
1725
     *                   <td>
1726
     *                   Handle code as HTML 5.
1727
     *                   </td>
1728
     *                   </tr>
1729
     *                   </table>
1730
     *                   </p>
1731
     *
1732
     * @psalm-mutation-free
1733
     *
1734
     * @return static
1735
     *                <p>Object with the resulting $str after being html encoded.</p>
1736
     */
1737
    public function htmlEncode(int $flags = \ENT_COMPAT): self
1738
    {
1739
        return static::create(
15✔
1740
            $this->utf8::htmlentities(
15✔
1741
                $this->str,
15✔
1742
                $flags,
15✔
1743
                $this->encoding
15✔
1744
            ),
15✔
1745
            $this->encoding
15✔
1746
        );
15✔
1747
    }
1748

1749
    /**
1750
     * Capitalizes the first word of the string, replaces underscores with
1751
     * spaces, and strips '_id'.
1752
     *
1753
     * EXAMPLE: <code>
1754
     * s('author_id')->humanize(); // 'Author'
1755
     * </code>
1756
     *
1757
     * @psalm-mutation-free
1758
     *
1759
     * @return static
1760
     *                <p>Object with a humanized $str.</p>
1761
     */
1762
    public function humanize(): self
1763
    {
1764
        return static::create(
9✔
1765
            $this->utf8::str_humanize($this->str),
9✔
1766
            $this->encoding
9✔
1767
        );
9✔
1768
    }
1769

1770
    /**
1771
     * Determine if the current string exists in another string. By
1772
     * default, the comparison is case-sensitive, but can be made insensitive
1773
     * by setting $caseSensitive to false.
1774
     *
1775
     * EXAMPLE: <code>
1776
     * </code>
1777
     *
1778
     * @param string $str           <p>The string to compare against.</p>
1779
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1780
     *
1781
     * @psalm-mutation-free
1782
     *
1783
     * @return bool
1784
     */
1785
    public function in(string $str, bool $caseSensitive = true): bool
1786
    {
1787
        if ($caseSensitive) {
4✔
1788
            return \strpos($str, $this->str) !== false;
3✔
1789
        }
1790

1791
        return \stripos($str, $this->str) !== false;
1✔
1792
    }
1793

1794
    /**
1795
     * Returns the index of the first occurrence of $needle in the string,
1796
     * and false if not found. Accepts an optional offset from which to begin
1797
     * the search.
1798
     *
1799
     * EXAMPLE: <code>
1800
     * s('string')->indexOf('ing'); // 3
1801
     * </code>
1802
     *
1803
     * @param string $needle <p>Substring to look for.</p>
1804
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1805
     *
1806
     * @psalm-mutation-free
1807
     *
1808
     * @return false|int
1809
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1810
     */
1811
    public function indexOf(string $needle, int $offset = 0)
1812
    {
1813
        return $this->utf8::strpos(
32✔
1814
            $this->str,
32✔
1815
            $needle,
32✔
1816
            $offset,
32✔
1817
            $this->encoding
32✔
1818
        );
32✔
1819
    }
1820

1821
    /**
1822
     * Returns the index of the first occurrence of $needle in the string,
1823
     * and false if not found. Accepts an optional offset from which to begin
1824
     * the search.
1825
     *
1826
     * EXAMPLE: <code>
1827
     * s('string')->indexOfIgnoreCase('ING'); // 3
1828
     * </code>
1829
     *
1830
     * @param string $needle <p>Substring to look for.</p>
1831
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1832
     *
1833
     * @psalm-mutation-free
1834
     *
1835
     * @return false|int
1836
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1837
     */
1838
    public function indexOfIgnoreCase(string $needle, int $offset = 0)
1839
    {
1840
        return $this->utf8::stripos(
21✔
1841
            $this->str,
21✔
1842
            $needle,
21✔
1843
            $offset,
21✔
1844
            $this->encoding
21✔
1845
        );
21✔
1846
    }
1847

1848
    /**
1849
     * Returns the index of the last occurrence of $needle in the string,
1850
     * and false if not found. Accepts an optional offset from which to begin
1851
     * the search. Offsets may be negative to count from the last character
1852
     * in the string.
1853
     *
1854
     * EXAMPLE: <code>
1855
     * s('foobarfoo')->indexOfLast('foo'); // 10
1856
     * </code>
1857
     *
1858
     * @param string $needle <p>Substring to look for.</p>
1859
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1860
     *
1861
     * @psalm-mutation-free
1862
     *
1863
     * @return false|int
1864
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1865
     */
1866
    public function indexOfLast(string $needle, int $offset = 0)
1867
    {
1868
        return $this->utf8::strrpos(
32✔
1869
            $this->str,
32✔
1870
            $needle,
32✔
1871
            $offset,
32✔
1872
            $this->encoding
32✔
1873
        );
32✔
1874
    }
1875

1876
    /**
1877
     * Returns the index of the last occurrence of $needle in the string,
1878
     * and false if not found. Accepts an optional offset from which to begin
1879
     * the search. Offsets may be negative to count from the last character
1880
     * in the string.
1881
     *
1882
     * EXAMPLE: <code>
1883
     * s('fooBarFoo')->indexOfLastIgnoreCase('foo'); // 10
1884
     * </code>
1885
     *
1886
     * @param string $needle <p>Substring to look for.</p>
1887
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1888
     *
1889
     * @psalm-mutation-free
1890
     *
1891
     * @return false|int
1892
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1893
     */
1894
    public function indexOfLastIgnoreCase(string $needle, int $offset = 0)
1895
    {
1896
        return $this->utf8::strripos(
21✔
1897
            $this->str,
21✔
1898
            $needle,
21✔
1899
            $offset,
21✔
1900
            $this->encoding
21✔
1901
        );
21✔
1902
    }
1903

1904
    /**
1905
     * Inserts $substring into the string at the $index provided.
1906
     *
1907
     * EXAMPLE: <code>
1908
     * s('fòôbř')->insert('à', 4); // 'fòôbàř'
1909
     * </code>
1910
     *
1911
     * @param string $substring <p>String to be inserted.</p>
1912
     * @param int    $index     <p>The index at which to insert the substring.</p>
1913
     *
1914
     * @psalm-mutation-free
1915
     *
1916
     * @return static
1917
     *                <p>Object with the resulting $str after the insertion.</p>
1918
     */
1919
    public function insert(string $substring, int $index): self
1920
    {
1921
        return static::create(
24✔
1922
            $this->utf8::str_insert(
24✔
1923
                $this->str,
24✔
1924
                $substring,
24✔
1925
                $index,
24✔
1926
                $this->encoding
24✔
1927
            ),
24✔
1928
            $this->encoding
24✔
1929
        );
24✔
1930
    }
1931

1932
    /**
1933
     * Returns true if the string contains the $pattern, otherwise false.
1934
     *
1935
     * WARNING: Asterisks ("*") are translated into (".*") zero-or-more regular
1936
     * expression wildcards.
1937
     *
1938
     * EXAMPLE: <code>
1939
     * s('Foo\\Bar\\Lall')->is('*\\Bar\\*'); // true
1940
     * </code>
1941
     *
1942
     * @credit Originally from Laravel, thanks Taylor.
1943
     *
1944
     * @param string $pattern <p>The string or pattern to match against.</p>
1945
     *
1946
     * @psalm-mutation-free
1947
     *
1948
     * @return bool
1949
     *              <p>Whether or not we match the provided pattern.</p>
1950
     */
1951
    public function is(string $pattern): bool
1952
    {
1953
        $quotedPattern = \preg_quote($pattern, '/');
27✔
1954
        $replaceWildCards = \str_replace('\*', '.*', $quotedPattern);
27✔
1955

1956
        return $this->matchesPattern('^' . $replaceWildCards . '\z');
27✔
1957
    }
1958

1959
    /**
1960
     * Returns true if the string contains only alphabetic chars, false otherwise.
1961
     *
1962
     * EXAMPLE: <code>
1963
     * s('丹尼爾')->isAlpha(); // true
1964
     * </code>
1965
     *
1966
     * @psalm-mutation-free
1967
     *
1968
     * @return bool
1969
     *              <p>Whether or not $str contains only alphabetic chars.</p>
1970
     */
1971
    public function isAlpha(): bool
1972
    {
1973
        return $this->utf8::is_alpha($this->str);
30✔
1974
    }
1975

1976
    /**
1977
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
1978
     *
1979
     * EXAMPLE: <code>
1980
     * s('دانيال1')->isAlphanumeric(); // true
1981
     * </code>
1982
     *
1983
     * @psalm-mutation-free
1984
     *
1985
     * @return bool
1986
     *              <p>Whether or not $str contains only alphanumeric chars.</p>
1987
     */
1988
    public function isAlphanumeric(): bool
1989
    {
1990
        return $this->utf8::is_alphanumeric($this->str);
39✔
1991
    }
1992

1993
    /**
1994
     * Checks if a string is 7 bit ASCII.
1995
     *
1996
     * EXAMPLE: <code>s('白')->isAscii; // false</code>
1997
     *
1998
     * @psalm-mutation-free
1999
     *
2000
     * @return bool
2001
     *              <p>
2002
     *              <strong>true</strong> if it is ASCII<br>
2003
     *              <strong>false</strong> otherwise
2004
     *              </p>
2005
     *
2006
     * @noinspection GetSetMethodCorrectnessInspection
2007
     */
2008
    public function isAscii(): bool
2009
    {
2010
        return $this->utf8::is_ascii($this->str);
×
2011
    }
2012

2013
    /**
2014
     * Returns true if the string is base64 encoded, false otherwise.
2015
     *
2016
     * EXAMPLE: <code>
2017
     * s('Zm9vYmFy')->isBase64(); // true
2018
     * </code>
2019
     *
2020
     * @param bool $emptyStringIsValid
2021
     *
2022
     * @psalm-mutation-free
2023
     *
2024
     * @return bool
2025
     *              <p>Whether or not $str is base64 encoded.</p>
2026
     */
2027
    public function isBase64($emptyStringIsValid = true): bool
2028
    {
2029
        return $this->utf8::is_base64($this->str, $emptyStringIsValid);
21✔
2030
    }
2031

2032
    /**
2033
     * Check if the input is binary... (is look like a hack).
2034
     *
2035
     * EXAMPLE: <code>s(01)->isBinary(); // true</code>
2036
     *
2037
     * @psalm-mutation-free
2038
     *
2039
     * @return bool
2040
     */
2041
    public function isBinary(): bool
2042
    {
2043
        return $this->utf8::is_binary($this->str);
1✔
2044
    }
2045

2046
    /**
2047
     * Returns true if the string contains only whitespace chars, false otherwise.
2048
     *
2049
     * EXAMPLE: <code>
2050
     * s("\n\t  \v\f")->isBlank(); // true
2051
     * </code>
2052
     *
2053
     * @psalm-mutation-free
2054
     *
2055
     * @return bool
2056
     *              <p>Whether or not $str contains only whitespace characters.</p>
2057
     */
2058
    public function isBlank(): bool
2059
    {
2060
        return $this->utf8::is_blank($this->str);
45✔
2061
    }
2062

2063
    /**
2064
     * Checks if the given string is equal to any "Byte Order Mark".
2065
     *
2066
     * WARNING: Use "s::string_has_bom()" if you will check BOM in a string.
2067
     *
2068
     * EXAMPLE: <code>s->("\xef\xbb\xbf")->isBom(); // true</code>
2069
     *
2070
     * @psalm-mutation-free
2071
     *
2072
     * @return bool
2073
     *              <p><strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.</p>
2074
     */
2075
    public function isBom(): bool
2076
    {
2077
        return $this->utf8::is_bom($this->str);
×
2078
    }
2079

2080
    /**
2081
     * Returns true if the string contains a valid E-Mail address, false otherwise.
2082
     *
2083
     * EXAMPLE: <code>
2084
     * s('lars@moelleken.org')->isEmail(); // true
2085
     * </code>
2086
     *
2087
     * @param bool $useExampleDomainCheck   [optional] <p>Default: false</p>
2088
     * @param bool $useTypoInDomainCheck    [optional] <p>Default: false</p>
2089
     * @param bool $useTemporaryDomainCheck [optional] <p>Default: false</p>
2090
     * @param bool $useDnsCheck             [optional] <p>Default: false</p>
2091
     *
2092
     * @psalm-mutation-free
2093
     *
2094
     * @return bool
2095
     *              <p>Whether or not $str contains a valid E-Mail address.</p>
2096
     */
2097
    public function isEmail(
2098
        bool $useExampleDomainCheck = false,
2099
        bool $useTypoInDomainCheck = false,
2100
        bool $useTemporaryDomainCheck = false,
2101
        bool $useDnsCheck = false
2102
    ): bool {
2103
        /**
2104
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the email-check class
2105
         */
2106
        return EmailCheck::isValid($this->str, $useExampleDomainCheck, $useTypoInDomainCheck, $useTemporaryDomainCheck, $useDnsCheck);
2✔
2107
    }
2108

2109
    /**
2110
     * Determine whether the string is considered to be empty.
2111
     *
2112
     * A variable is considered empty if it does not exist or if its value equals FALSE.
2113
     *
2114
     * EXAMPLE: <code>
2115
     * s('')->isEmpty(); // true
2116
     * </code>
2117
     *
2118
     * @psalm-mutation-free
2119
     *
2120
     * @return bool
2121
     *              <p>Whether or not $str is empty().</p>
2122
     */
2123
    public function isEmpty(): bool
2124
    {
2125
        return $this->utf8::is_empty($this->str);
10✔
2126
    }
2127

2128
    /**
2129
     * Determine whether the string is equals to $str.
2130
     * Alias for isEqualsCaseSensitive()
2131
     *
2132
     * EXAMPLE: <code>
2133
     * s('foo')->isEquals('foo'); // true
2134
     * </code>
2135
     *
2136
     * @param string|Stringy ...$str
2137
     *
2138
     * @psalm-mutation-free
2139
     *
2140
     * @return bool
2141
     */
2142
    public function isEquals(...$str): bool
2143
    {
2144
        return $this->isEqualsCaseSensitive(...$str);
13✔
2145
    }
2146

2147
    /**
2148
     * Determine whether the string is equals to $str.
2149
     *
2150
     * EXAMPLE: <code>
2151
     * </code>
2152
     *
2153
     * @param float|int|string|Stringy ...$str <p>The string to compare.</p>
2154
     *
2155
     * @psalm-mutation-free
2156
     *
2157
     * @return bool
2158
     *              <p>Whether or not $str is equals.</p>
2159
     */
2160
    public function isEqualsCaseInsensitive(...$str): bool
2161
    {
2162
        $strUpper = $this->toUpperCase()->str;
4✔
2163

2164
        foreach ($str as $strTmp) {
4✔
2165
            /**
2166
             * @psalm-suppress RedundantConditionGivenDocblockType - wait for union-types :)
2167
             */
2168
            if ($strTmp instanceof self) {
4✔
2169
                if ($strUpper !== $strTmp->toUpperCase()->str) {
×
2170
                    return false;
×
2171
                }
2172
            } elseif (\is_scalar($strTmp)) {
4✔
2173
                if ($strUpper !== $this->utf8::strtoupper((string) $strTmp, $this->encoding)) {
4✔
2174
                    return false;
3✔
2175
                }
2176
            } else {
2177
                throw new \InvalidArgumentException('expected: int|float|string|Stringy -> given: ' . \print_r($strTmp, true) . ' [' . \gettype($strTmp) . ']');
×
2178
            }
2179
        }
2180

2181
        return true;
4✔
2182
    }
2183

2184
    /**
2185
     * Determine whether the string is equals to $str.
2186
     *
2187
     * EXAMPLE: <code>
2188
     * </code>
2189
     *
2190
     * @param float|int|string|Stringy ...$str <p>The string to compare.</p>
2191
     *
2192
     * @psalm-mutation-free
2193
     *
2194
     * @return bool
2195
     *              <p>Whether or not $str is equals.</p>
2196
     */
2197
    public function isEqualsCaseSensitive(...$str): bool
2198
    {
2199
        foreach ($str as $strTmp) {
15✔
2200
            /**
2201
             * @psalm-suppress RedundantConditionGivenDocblockType - wait for union-types :)
2202
             */
2203
            if ($strTmp instanceof self) {
15✔
2204
                if ($this->str !== $strTmp->str) {
2✔
2205
                    return false;
1✔
2206
                }
2207
            } elseif (\is_scalar($strTmp)) {
13✔
2208
                if ($this->str !== (string) $strTmp) {
13✔
2209
                    return false;
10✔
2210
                }
2211
            } else {
2212
                throw new \InvalidArgumentException('expected: int|float|string|Stringy -> given: ' . \print_r($strTmp, true) . ' [' . \gettype($strTmp) . ']');
×
2213
            }
2214
        }
2215

2216
        return true;
4✔
2217
    }
2218

2219
    /**
2220
     * Returns true if the string contains only hexadecimal chars, false otherwise.
2221
     *
2222
     * EXAMPLE: <code>
2223
     * s('A102F')->isHexadecimal(); // true
2224
     * </code>
2225
     *
2226
     * @psalm-mutation-free
2227
     *
2228
     * @return bool
2229
     *              <p>Whether or not $str contains only hexadecimal chars.</p>
2230
     */
2231
    public function isHexadecimal(): bool
2232
    {
2233
        return $this->utf8::is_hexadecimal($this->str);
39✔
2234
    }
2235

2236
    /**
2237
     * Returns true if the string contains HTML-Tags, false otherwise.
2238
     *
2239
     * EXAMPLE: <code>
2240
     * s('<h1>foo</h1>')->isHtml(); // true
2241
     * </code>
2242
     *
2243
     * @psalm-mutation-free
2244
     *
2245
     * @return bool
2246
     *              <p>Whether or not $str contains HTML-Tags.</p>
2247
     */
2248
    public function isHtml(): bool
2249
    {
2250
        return $this->utf8::is_html($this->str);
2✔
2251
    }
2252

2253
    /**
2254
     * Returns true if the string is JSON, false otherwise. Unlike json_decode
2255
     * in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers,
2256
     * in that an empty string is not considered valid JSON.
2257
     *
2258
     * EXAMPLE: <code>
2259
     * s('{"foo":"bar"}')->isJson(); // true
2260
     * </code>
2261
     *
2262
     * @param bool $onlyArrayOrObjectResultsAreValid
2263
     *
2264
     * @psalm-mutation-free
2265
     *
2266
     * @return bool
2267
     *              <p>Whether or not $str is JSON.</p>
2268
     */
2269
    public function isJson($onlyArrayOrObjectResultsAreValid = false): bool
2270
    {
2271
        /**
2272
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to vendor stuff?
2273
         */
2274
        return $this->utf8::is_json(
60✔
2275
            $this->str,
60✔
2276
            $onlyArrayOrObjectResultsAreValid
60✔
2277
        );
60✔
2278
    }
2279

2280
    /**
2281
     * Returns true if the string contains only lower case chars, false otherwise.
2282
     *
2283
     * EXAMPLE: <code>
2284
     * s('fòôbàř')->isLowerCase(); // true
2285
     * </code>
2286
     *
2287
     * @psalm-mutation-free
2288
     *
2289
     * @return bool
2290
     *              <p>Whether or not $str contains only lower case characters.</p>
2291
     */
2292
    public function isLowerCase(): bool
2293
    {
2294
        return $this->utf8::is_lowercase($this->str);
24✔
2295
    }
2296

2297
    /**
2298
     * Determine whether the string is considered to be NOT empty.
2299
     *
2300
     * A variable is considered NOT empty if it does exist or if its value equals TRUE.
2301
     *
2302
     * EXAMPLE: <code>
2303
     * s('')->isNotEmpty(); // false
2304
     * </code>
2305
     *
2306
     * @psalm-mutation-free
2307
     *
2308
     * @return bool
2309
     *              <p>Whether or not $str is empty().</p>
2310
     */
2311
    public function isNotEmpty(): bool
2312
    {
2313
        return !$this->utf8::is_empty($this->str);
10✔
2314
    }
2315

2316
    /**
2317
     * Determine if the string is composed of numeric characters.
2318
     *
2319
     * EXAMPLE: <code>
2320
     * </code>
2321
     *
2322
     * @psalm-mutation-free
2323
     *
2324
     * @return bool
2325
     */
2326
    public function isNumeric(): bool
2327
    {
2328
        return \is_numeric($this->str);
4✔
2329
    }
2330

2331
    /**
2332
     * Determine if the string is composed of printable (non-invisible) characters.
2333
     *
2334
     * EXAMPLE: <code>
2335
     * </code>
2336
     *
2337
     * @psalm-mutation-free
2338
     *
2339
     * @return bool
2340
     */
2341
    public function isPrintable(): bool
2342
    {
2343
        return $this->utf8::is_printable($this->str);
3✔
2344
    }
2345

2346
    /**
2347
     * Determine if the string is composed of punctuation characters.
2348
     *
2349
     * EXAMPLE: <code>
2350
     * </code>
2351
     *
2352
     * @psalm-mutation-free
2353
     *
2354
     * @return bool
2355
     */
2356
    public function isPunctuation(): bool
2357
    {
2358
        return $this->utf8::is_punctuation($this->str);
3✔
2359
    }
2360

2361
    /**
2362
     * Returns true if the string is serialized, false otherwise.
2363
     *
2364
     * EXAMPLE: <code>
2365
     * s('a:1:{s:3:"foo";s:3:"bar";}')->isSerialized(); // true
2366
     * </code>
2367
     *
2368
     * @psalm-mutation-free
2369
     *
2370
     * @return bool
2371
     *              <p>Whether or not $str is serialized.</p>
2372
     */
2373
    public function isSerialized(): bool
2374
    {
2375
        return $this->utf8::is_serialized($this->str);
21✔
2376
    }
2377

2378
    /**
2379
     * Check if two strings are similar.
2380
     *
2381
     * EXAMPLE: <code>
2382
     * </code>
2383
     *
2384
     * @param string $str                     <p>The string to compare against.</p>
2385
     * @param float  $minPercentForSimilarity [optional] <p>The percentage of needed similarity. | Default: 80%</p>
2386
     *
2387
     * @psalm-mutation-free
2388
     *
2389
     * @return bool
2390
     */
2391
    public function isSimilar(string $str, float $minPercentForSimilarity = 80.0): bool
2392
    {
2393
        return $this->similarity($str) >= $minPercentForSimilarity;
3✔
2394
    }
2395

2396
    /**
2397
     * Returns true if the string contains only lower case chars, false
2398
     * otherwise.
2399
     *
2400
     * EXAMPLE: <code>
2401
     * s('FÒÔBÀŘ')->isUpperCase(); // true
2402
     * </code>
2403
     *
2404
     * @psalm-mutation-free
2405
     *
2406
     * @return bool
2407
     *              <p>Whether or not $str contains only lower case characters.</p>
2408
     */
2409
    public function isUpperCase(): bool
2410
    {
2411
        return $this->utf8::is_uppercase($this->str);
24✔
2412
    }
2413

2414
    /**
2415
     * /**
2416
     * Check if $url is an correct url.
2417
     *
2418
     * @param bool $disallow_localhost
2419
     *
2420
     * @psalm-mutation-free
2421
     *
2422
     * @return bool
2423
     */
2424
    public function isUrl(bool $disallow_localhost = false): bool
2425
    {
2426
        return $this->utf8::is_url($this->str, $disallow_localhost);
×
2427
    }
2428

2429
    /**
2430
     * Check if the string is UTF-16.
2431
     *
2432
     * @psalm-mutation-free
2433
     *
2434
     * @return false|int
2435
     *                   <strong>false</strong> if is't not UTF-16,<br>
2436
     *                   <strong>1</strong> for UTF-16LE,<br>
2437
     *                   <strong>2</strong> for UTF-16BE
2438
     */
2439
    public function isUtf16()
2440
    {
2441
        return $this->utf8::is_utf16($this->str);
×
2442
    }
2443

2444
    /**
2445
     * Check if the string is UTF-32.
2446
     *
2447
     * @psalm-mutation-free
2448
     *
2449
     * @return false|int
2450
     *                   <strong>false</strong> if is't not UTF-32,<br>
2451
     *                   <strong>1</strong> for UTF-32LE,<br>
2452
     *                   <strong>2</strong> for UTF-32BE
2453
     */
2454
    public function isUtf32()
2455
    {
2456
        return $this->utf8::is_utf32($this->str);
×
2457
    }
2458

2459
    /**
2460
     * Checks whether the passed input contains only byte sequences that appear valid UTF-8.
2461
     *
2462
     * EXAMPLE: <code>
2463
     * s('Iñtërnâtiônàlizætiøn')->isUtf8(); // true
2464
     * //
2465
     * s("Iñtërnâtiônàlizætiøn\xA0\xA1")->isUtf8(); // false
2466
     * </code>
2467
     *
2468
     * @param bool $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
2469
     *
2470
     * @psalm-mutation-free
2471
     *
2472
     * @return bool
2473
     */
2474
    public function isUtf8(bool $strict = false): bool
2475
    {
2476
        return $this->utf8::is_utf8($this->str, $strict);
×
2477
    }
2478

2479
    /**
2480
     * Returns true if the string contains only whitespace chars, false otherwise.
2481
     *
2482
     * EXAMPLE: <code>
2483
     * </code>
2484
     *
2485
     * @psalm-mutation-free
2486
     *
2487
     * @return bool
2488
     *              <p>Whether or not $str contains only whitespace characters.</p>
2489
     */
2490
    public function isWhitespace(): bool
2491
    {
2492
        return $this->isBlank();
30✔
2493
    }
2494

2495
    /**
2496
     * Convert the string to kebab-case.
2497
     *
2498
     * EXAMPLE: <code>
2499
     * </code>
2500
     *
2501
     * @psalm-mutation-free
2502
     *
2503
     * @return static
2504
     */
2505
    public function kebabCase(): self
2506
    {
2507
        $words = \array_map(
4✔
2508
            static function (self $word) {
4✔
2509
                return $word->toLowerCase();
4✔
2510
            },
4✔
2511
            $this->words('', true)
4✔
2512
        );
4✔
2513

2514
        return new static(\implode('-', $words), $this->encoding);
4✔
2515
    }
2516

2517
    /**
2518
     * Returns the last $n characters of the string.
2519
     *
2520
     * EXAMPLE: <code>
2521
     * s('fòôbàř')->last(3); // 'bàř'
2522
     * </code>
2523
     *
2524
     * @param int $n <p>Number of characters to retrieve from the end.</p>
2525
     *
2526
     * @psalm-mutation-free
2527
     *
2528
     * @return static
2529
     *                <p>Object with its $str being the last $n chars.</p>
2530
     */
2531
    public function last(int $n): self
2532
    {
2533
        return static::create(
36✔
2534
            $this->utf8::str_last_char(
36✔
2535
                $this->str,
36✔
2536
                $n,
36✔
2537
                $this->encoding
36✔
2538
            ),
36✔
2539
            $this->encoding
36✔
2540
        );
36✔
2541
    }
2542

2543
    /**
2544
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
2545
     * If no match is found returns new empty Stringy object.
2546
     *
2547
     * EXAMPLE: <code>
2548
     * </code>
2549
     *
2550
     * @param string $needle       <p>The string to look for.</p>
2551
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2552
     *
2553
     * @psalm-mutation-free
2554
     *
2555
     * @return static
2556
     */
2557
    public function lastSubstringOf(string $needle, bool $beforeNeedle = false): self
2558
    {
2559
        return static::create(
5✔
2560
            $this->utf8::str_substr_last(
5✔
2561
                $this->str,
5✔
2562
                $needle,
5✔
2563
                $beforeNeedle,
5✔
2564
                $this->encoding
5✔
2565
            ),
5✔
2566
            $this->encoding
5✔
2567
        );
5✔
2568
    }
2569

2570
    /**
2571
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
2572
     * If no match is found returns new empty Stringy object.
2573
     *
2574
     * EXAMPLE: <code>
2575
     * </code>
2576
     *
2577
     * @param string $needle       <p>The string to look for.</p>
2578
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2579
     *
2580
     * @psalm-mutation-free
2581
     *
2582
     * @return static
2583
     */
2584
    public function lastSubstringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
2585
    {
2586
        return static::create(
3✔
2587
            $this->utf8::str_isubstr_last(
3✔
2588
                $this->str,
3✔
2589
                $needle,
3✔
2590
                $beforeNeedle,
3✔
2591
                $this->encoding
3✔
2592
            ),
3✔
2593
            $this->encoding
3✔
2594
        );
3✔
2595
    }
2596

2597
    /**
2598
     * Returns the length of the string.
2599
     *
2600
     * EXAMPLE: <code>
2601
     * s('fòôbàř')->length(); // 6
2602
     * </code>
2603
     *
2604
     * @psalm-mutation-free
2605
     *
2606
     * @return int
2607
     *             <p>The number of characters in $str given the encoding.</p>
2608
     */
2609
    public function length(): int
2610
    {
2611
        return (int) $this->utf8::strlen($this->str, $this->encoding);
30✔
2612
    }
2613

2614
    /**
2615
     * Line-Wrap the string after $limit, but also after the next word.
2616
     *
2617
     * EXAMPLE: <code>
2618
     * </code>
2619
     *
2620
     * @param int         $limit           [optional] <p>The column width.</p>
2621
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
2622
     * @param bool        $add_final_break [optional] <p>
2623
     *                                     If this flag is true, then the method will add a $break at the end
2624
     *                                     of the result string.
2625
     *                                     </p>
2626
     * @param string|null $delimiter       [optional] <p>
2627
     *                                     You can change the default behavior, where we split the string by newline.
2628
     *                                     </p>
2629
     *
2630
     * @psalm-mutation-free
2631
     *
2632
     * @return static
2633
     */
2634
    public function lineWrap(
2635
        int $limit,
2636
        string $break = "\n",
2637
        bool $add_final_break = true,
2638
        ?string $delimiter = null
2639
    ): self {
2640
        if ($limit <= 0) {
5✔
2641
            return static::create('', $this->encoding);
1✔
2642
        }
2643

2644
        $delimiter = $delimiter === '' ? null : $delimiter;
4✔
2645

2646
        return static::create(
4✔
2647
            $this->utf8::wordwrap_per_line(
4✔
2648
                $this->str,
4✔
2649
                $limit,
4✔
2650
                $break,
4✔
2651
                true,
4✔
2652
                $add_final_break,
4✔
2653
                $delimiter
4✔
2654
            ),
4✔
2655
            $this->encoding
4✔
2656
        );
4✔
2657
    }
2658

2659
    /**
2660
     * Line-Wrap the string after $limit, but also after the next word.
2661
     *
2662
     * EXAMPLE: <code>
2663
     * </code>
2664
     *
2665
     * @param int         $limit           [optional] <p>The column width.</p>
2666
     * @param string      $break           [optional] <p>The line is broken using the optional break parameter.</p>
2667
     * @param bool        $add_final_break [optional] <p>
2668
     *                                     If this flag is true, then the method will add a $break at the end
2669
     *                                     of the result string.
2670
     *                                     </p>
2671
     * @param string|null $delimiter       [optional] <p>
2672
     *                                     You can change the default behavior, where we split the string by newline.
2673
     *                                     </p>
2674
     *
2675
     * @psalm-mutation-free
2676
     *
2677
     * @return static
2678
     */
2679
    public function lineWrapAfterWord(
2680
        int $limit,
2681
        string $break = "\n",
2682
        bool $add_final_break = true,
2683
        ?string $delimiter = null
2684
    ): self {
2685
        if ($limit <= 0) {
8✔
2686
            return static::create('', $this->encoding);
2✔
2687
        }
2688

2689
        $delimiter = $delimiter === '' ? null : $delimiter;
6✔
2690

2691
        return static::create(
6✔
2692
            $this->utf8::wordwrap_per_line(
6✔
2693
                $this->str,
6✔
2694
                $limit,
6✔
2695
                $break,
6✔
2696
                false,
6✔
2697
                $add_final_break,
6✔
2698
                $delimiter
6✔
2699
            ),
6✔
2700
            $this->encoding
6✔
2701
        );
6✔
2702
    }
2703

2704
    /**
2705
     * Splits on newlines and carriage returns, returning an array of Stringy
2706
     * objects corresponding to the lines in the string.
2707
     *
2708
     * EXAMPLE: <code>
2709
     * s("fòô\r\nbàř\n")->lines(); // ['fòô', 'bàř', '']
2710
     * </code>
2711
     *
2712
     * @psalm-mutation-free
2713
     *
2714
     * @return static[]
2715
     *                  <p>An array of Stringy objects.</p>
2716
     *
2717
     * @phpstan-return array<int,static>
2718
     */
2719
    public function lines(): array
2720
    {
2721
        $strings = $this->utf8::str_to_lines($this->str);
52✔
2722
        /** @noinspection AlterInForeachInspection */
2723
        foreach ($strings as &$str) {
52✔
2724
            $str = static::create($str, $this->encoding);
52✔
2725
        }
2726

2727
        /** @noinspection PhpSillyAssignmentInspection */
2728
        /** @var static[] $strings */
2729
        $strings = $strings;
52✔
2730

2731
        return $strings;
52✔
2732
    }
2733

2734
    /**
2735
     * Splits on newlines and carriage returns, returning an array of Stringy
2736
     * objects corresponding to the lines in the string.
2737
     *
2738
     * EXAMPLE: <code>
2739
     * </code>
2740
     *
2741
     * @psalm-mutation-free
2742
     *
2743
     * @return CollectionStringy|static[]
2744
     *                                    <p>An collection of Stringy objects.</p>
2745
     *
2746
     * @phpstan-return CollectionStringy<int,static>
2747
     */
2748
    public function linesCollection(): CollectionStringy
2749
    {
2750
        /**
2751
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
2752
         */
2753
        return CollectionStringy::create(
34✔
2754
            $this->lines()
34✔
2755
        );
34✔
2756
    }
2757

2758
    /**
2759
     * Returns the longest common prefix between the string and $otherStr.
2760
     *
2761
     * EXAMPLE: <code>
2762
     * s('foobar')->longestCommonPrefix('foobaz'); // 'fooba'
2763
     * </code>
2764
     *
2765
     * @param string $otherStr <p>Second string for comparison.</p>
2766
     *
2767
     * @psalm-mutation-free
2768
     *
2769
     * @return static
2770
     *                <p>Object with its $str being the longest common prefix.</p>
2771
     */
2772
    public function longestCommonPrefix(string $otherStr): self
2773
    {
2774
        return static::create(
30✔
2775
            $this->utf8::str_longest_common_prefix(
30✔
2776
                $this->str,
30✔
2777
                $otherStr,
30✔
2778
                $this->encoding
30✔
2779
            ),
30✔
2780
            $this->encoding
30✔
2781
        );
30✔
2782
    }
2783

2784
    /**
2785
     * Returns the longest common substring between the string and $otherStr.
2786
     * In the case of ties, it returns that which occurs first.
2787
     *
2788
     * EXAMPLE: <code>
2789
     * s('foobar')->longestCommonSubstring('boofar'); // 'oo'
2790
     * </code>
2791
     *
2792
     * @param string $otherStr <p>Second string for comparison.</p>
2793
     *
2794
     * @psalm-mutation-free
2795
     *
2796
     * @return static
2797
     *                <p>Object with its $str being the longest common substring.</p>
2798
     */
2799
    public function longestCommonSubstring(string $otherStr): self
2800
    {
2801
        return static::create(
30✔
2802
            $this->utf8::str_longest_common_substring(
30✔
2803
                $this->str,
30✔
2804
                $otherStr,
30✔
2805
                $this->encoding
30✔
2806
            ),
30✔
2807
            $this->encoding
30✔
2808
        );
30✔
2809
    }
2810

2811
    /**
2812
     * Returns the longest common suffix between the string and $otherStr.
2813
     *
2814
     * EXAMPLE: <code>
2815
     * s('fòôbàř')->longestCommonSuffix('fòrbàř'); // 'bàř'
2816
     * </code>
2817
     *
2818
     * @param string $otherStr <p>Second string for comparison.</p>
2819
     *
2820
     * @psalm-mutation-free
2821
     *
2822
     * @return static
2823
     *                <p>Object with its $str being the longest common suffix.</p>
2824
     */
2825
    public function longestCommonSuffix(string $otherStr): self
2826
    {
2827
        return static::create(
30✔
2828
            $this->utf8::str_longest_common_suffix(
30✔
2829
                $this->str,
30✔
2830
                $otherStr,
30✔
2831
                $this->encoding
30✔
2832
            ),
30✔
2833
            $this->encoding
30✔
2834
        );
30✔
2835
    }
2836

2837
    /**
2838
     * Converts the first character of the string to lower case.
2839
     *
2840
     * EXAMPLE: <code>
2841
     * s('Σ Foo')->lowerCaseFirst(); // 'σ Foo'
2842
     * </code>
2843
     *
2844
     * @psalm-mutation-free
2845
     *
2846
     * @return static
2847
     *                <p>Object with the first character of $str being lower case.</p>
2848
     */
2849
    public function lowerCaseFirst(): self
2850
    {
2851
        return static::create(
16✔
2852
            $this->utf8::lcfirst($this->str, $this->encoding),
16✔
2853
            $this->encoding
16✔
2854
        );
16✔
2855
    }
2856

2857
    /**
2858
     * Determine if the string matches another string regardless of case.
2859
     * Alias for isEqualsCaseInsensitive()
2860
     *
2861
     * EXAMPLE: <code>
2862
     * </code>
2863
     *
2864
     * @psalm-mutation-free
2865
     *
2866
     * @param string|Stringy ...$str
2867
     *                               <p>The string to compare against.</p>
2868
     *
2869
     * @psalm-mutation-free
2870
     *
2871
     * @return bool
2872
     */
2873
    public function matchCaseInsensitive(...$str): bool
2874
    {
2875
        return $this->isEqualsCaseInsensitive(...$str);
3✔
2876
    }
2877

2878
    /**
2879
     * Determine if the string matches another string.
2880
     * Alias for isEqualsCaseSensitive()
2881
     *
2882
     * EXAMPLE: <code>
2883
     * </code>
2884
     *
2885
     * @psalm-mutation-free
2886
     *
2887
     * @param string|Stringy ...$str
2888
     *                               <p>The string to compare against.</p>
2889
     *
2890
     * @psalm-mutation-free
2891
     *
2892
     * @return bool
2893
     */
2894
    public function matchCaseSensitive(...$str): bool
2895
    {
2896
        return $this->isEqualsCaseSensitive(...$str);
7✔
2897
    }
2898

2899
    /**
2900
     * Create a md5 hash from the current string.
2901
     *
2902
     * @psalm-mutation-free
2903
     *
2904
     * @return static
2905
     */
2906
    public function md5(): self
2907
    {
2908
        return static::create($this->hash('md5'), $this->encoding);
2✔
2909
    }
2910

2911
    /**
2912
     * Replace all breaks [<br> | \r\n | \r | \n | ...] into "<br>".
2913
     *
2914
     * EXAMPLE: <code>
2915
     * </code>
2916
     *
2917
     * @return static
2918
     */
2919
    public function newLineToHtmlBreak(): self
2920
    {
2921
        return $this->removeHtmlBreak('<br>');
1✔
2922
    }
2923

2924
    /**
2925
     * Get every nth character of the string.
2926
     *
2927
     * EXAMPLE: <code>
2928
     * </code>
2929
     *
2930
     * @param int $step   <p>The number of characters to step.</p>
2931
     * @param int $offset [optional] <p>The string offset to start at.</p>
2932
     *
2933
     * @psalm-mutation-free
2934
     *
2935
     * @return static
2936
     */
2937
    public function nth(int $step, int $offset = 0): self
2938
    {
2939
        $length = $step - 1;
4✔
2940
        $substring = $this->substr($offset)->toString();
4✔
2941

2942
        if ($substring === '') {
4✔
2943
            return new static('', $this->encoding);
×
2944
        }
2945

2946
        \preg_match_all(
4✔
2947
            "/(?:^|(?:.|\p{L}|\w){" . $length . "})(.|\p{L}|\w)/u",
4✔
2948
            $substring,
4✔
2949
            $matches
4✔
2950
        );
4✔
2951

2952
        return new static(\implode('', $matches[1] ?? []), $this->encoding);
4✔
2953
    }
2954

2955
    /**
2956
     * Returns the integer value of the current string.
2957
     *
2958
     * EXAMPLE: <code>
2959
     * s('foo1 ba2r')->extractIntegers(); // '12'
2960
     * </code>
2961
     *
2962
     * @psalm-mutation-free
2963
     *
2964
     * @return static
2965
     */
2966
    public function extractIntegers(): self
2967
    {
2968
        \preg_match_all('/(?<integers>\d+)/', $this->str, $matches);
1✔
2969

2970
        return static::create(
1✔
2971
            \implode('', $matches['integers']),
1✔
2972
            $this->encoding
1✔
2973
        );
1✔
2974
    }
2975

2976
    /**
2977
     * Returns the special chars of the current string.
2978
     *
2979
     * EXAMPLE: <code>
2980
     * s('foo1 ba2!r')->extractSpecialCharacters(); // '!'
2981
     * </code>
2982
     *
2983
     * @psalm-mutation-free
2984
     *
2985
     * @return static
2986
     */
2987
    public function extractSpecialCharacters(): self
2988
    {
2989
        // no letter, no digit, no space
2990
        \preg_match_all('/[^\p{L}0-9\s]/u', $this->str, $matches);
1✔
2991

2992
        return static::create(
1✔
2993
            \implode('', $matches[0]),
1✔
2994
            $this->encoding
1✔
2995
        );
1✔
2996
    }
2997

2998
    /**
2999
     * Returns whether or not a character exists at an index. Offsets may be
3000
     * negative to count from the last character in the string. Implements
3001
     * part of the ArrayAccess interface.
3002
     *
3003
     * EXAMPLE: <code>
3004
     * </code>
3005
     *
3006
     * @param int $offset <p>The index to check.</p>
3007
     *
3008
     * @psalm-mutation-free
3009
     *
3010
     * @return bool
3011
     *              <p>Whether or not the index exists.</p>
3012
     */
3013
    public function offsetExists($offset): bool
3014
    {
3015
        return $this->utf8::str_offset_exists(
18✔
3016
            $this->str,
18✔
3017
            $offset,
18✔
3018
            $this->encoding
18✔
3019
        );
18✔
3020
    }
3021

3022
    /**
3023
     * Returns the character at the given index. Offsets may be negative to
3024
     * count from the last character in the string. Implements part of the
3025
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
3026
     * does not exist.
3027
     *
3028
     * EXAMPLE: <code>
3029
     * </code>
3030
     *
3031
     * @param int $offset <p>The <strong>index</strong> from which to retrieve the char.</p>
3032
     *
3033
     * @throws \OutOfBoundsException
3034
     *                               <p>If the positive or negative offset does not exist.</p>
3035
     *
3036
     * @return string
3037
     *                <p>The character at the specified index.</p>
3038
     *
3039
     * @psalm-mutation-free
3040
     */
3041
    public function offsetGet($offset): string
3042
    {
3043
        $length = $this->length();
11✔
3044

3045
        if (
3046
            ($offset >= 0 && $length <= $offset)
11✔
3047
            ||
3048
            $length < \abs($offset)
11✔
3049
        ) {
3050
            throw new \OutOfBoundsException('No character exists at the index');
6✔
3051
        }
3052

3053
        return (string) $this->utf8::substr($this->str, $offset, 1, $this->encoding);
5✔
3054
    }
3055

3056
    /**
3057
     * Implements part of the ArrayAccess interface, but throws an exception
3058
     * when called. This maintains the immutability of Stringy objects.
3059
     *
3060
     * EXAMPLE: <code>
3061
     * </code>
3062
     *
3063
     * @param int   $offset <p>The index of the character.</p>
3064
     * @param mixed $value  <p>Value to set.</p>
3065
     *
3066
     * @throws \Exception
3067
     *                    <p>When called.</p>
3068
     *
3069
     * @return void
3070
     */
3071
    public function offsetSet($offset, $value): void
3072
    {
3073
        // Stringy is immutable, cannot directly set char
3074
        throw new \Exception('Stringy object is immutable, cannot modify char');
3✔
3075
    }
3076

3077
    /**
3078
     * Implements part of the ArrayAccess interface, but throws an exception
3079
     * when called. This maintains the immutability of Stringy objects.
3080
     *
3081
     * EXAMPLE: <code>
3082
     * </code>
3083
     *
3084
     * @param int $offset <p>The index of the character.</p>
3085
     *
3086
     * @throws \Exception
3087
     *                    <p>When called.</p>
3088
     *
3089
     * @return void
3090
     */
3091
    public function offsetUnset($offset): void
3092
    {
3093
        // Don't allow directly modifying the string
3094
        throw new \Exception('Stringy object is immutable, cannot unset char');
3✔
3095
    }
3096

3097
    /**
3098
     * Pads the string to a given length with $padStr. If length is less than
3099
     * or equal to the length of the string, no padding takes places. The
3100
     * default string used for padding is a space, and the default type (one of
3101
     * 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
3102
     * if $padType isn't one of those 3 values.
3103
     *
3104
     * EXAMPLE: <code>
3105
     * s('fòôbàř')->pad(9, '-/', 'left'); // '-/-fòôbàř'
3106
     * </code>
3107
     *
3108
     * @param int    $length  <p>Desired string length after padding.</p>
3109
     * @param string $padStr  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3110
     * @param string $padType [optional] <p>One of 'left', 'right', 'both'. Default: 'right'</p>
3111
     *
3112
     * @throws \InvalidArgumentException
3113
     *                                   <p>If $padType isn't one of 'right', 'left' or 'both'.</p>
3114
     *
3115
     * @return static
3116
     *                <p>Object with a padded $str.</p>
3117
     *
3118
     * @psalm-mutation-free
3119
     */
3120
    public function pad(int $length, string $padStr = ' ', string $padType = 'right'): self
3121
    {
3122
        return static::create(
39✔
3123
            $this->utf8::str_pad(
39✔
3124
                $this->str,
39✔
3125
                $length,
39✔
3126
                $padStr,
39✔
3127
                $padType,
39✔
3128
                $this->encoding
39✔
3129
            )
39✔
3130
        );
39✔
3131
    }
3132

3133
    /**
3134
     * Returns a new string of a given length such that both sides of the
3135
     * string are padded. Alias for pad() with a $padType of 'both'.
3136
     *
3137
     * EXAMPLE: <code>
3138
     * s('foo bar')->padBoth(9, ' '); // ' foo bar '
3139
     * </code>
3140
     *
3141
     * @param int    $length <p>Desired string length after padding.</p>
3142
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3143
     *
3144
     * @psalm-mutation-free
3145
     *
3146
     * @return static
3147
     *                <p>String with padding applied.</p>
3148
     */
3149
    public function padBoth(int $length, string $padStr = ' '): self
3150
    {
3151
        return static::create(
33✔
3152
            $this->utf8::str_pad_both(
33✔
3153
                $this->str,
33✔
3154
                $length,
33✔
3155
                $padStr,
33✔
3156
                $this->encoding
33✔
3157
            )
33✔
3158
        );
33✔
3159
    }
3160

3161
    /**
3162
     * Returns a new string of a given length such that the beginning of the
3163
     * string is padded. Alias for pad() with a $padType of 'left'.
3164
     *
3165
     * EXAMPLE: <code>
3166
     * s('foo bar')->padLeft(9, ' '); // '  foo bar'
3167
     * </code>
3168
     *
3169
     * @param int    $length <p>Desired string length after padding.</p>
3170
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3171
     *
3172
     * @psalm-mutation-free
3173
     *
3174
     * @return static
3175
     *                <p>String with left padding.</p>
3176
     */
3177
    public function padLeft(int $length, string $padStr = ' '): self
3178
    {
3179
        return static::create(
21✔
3180
            $this->utf8::str_pad_left(
21✔
3181
                $this->str,
21✔
3182
                $length,
21✔
3183
                $padStr,
21✔
3184
                $this->encoding
21✔
3185
            )
21✔
3186
        );
21✔
3187
    }
3188

3189
    /**
3190
     * Returns a new string of a given length such that the end of the string
3191
     * is padded. Alias for pad() with a $padType of 'right'.
3192
     *
3193
     * EXAMPLE: <code>
3194
     * s('foo bar')->padRight(10, '_*'); // 'foo bar_*_'
3195
     * </code>
3196
     *
3197
     * @param int    $length <p>Desired string length after padding.</p>
3198
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
3199
     *
3200
     * @psalm-mutation-free
3201
     *
3202
     * @return static
3203
     *                <p>String with right padding.</p>
3204
     */
3205
    public function padRight(int $length, string $padStr = ' '): self
3206
    {
3207
        return static::create(
21✔
3208
            $this->utf8::str_pad_right(
21✔
3209
                $this->str,
21✔
3210
                $length,
21✔
3211
                $padStr,
21✔
3212
                $this->encoding
21✔
3213
            )
21✔
3214
        );
21✔
3215
    }
3216

3217
    /**
3218
     * Convert the string to PascalCase.
3219
     * Alias for studlyCase()
3220
     *
3221
     * EXAMPLE: <code>
3222
     * </code>
3223
     *
3224
     * @psalm-mutation-free
3225
     *
3226
     * @return static
3227
     */
3228
    public function pascalCase(): self
3229
    {
3230
        return $this->studlyCase();
3✔
3231
    }
3232

3233
    /**
3234
     * Returns a new string starting with $prefix.
3235
     *
3236
     * EXAMPLE: <code>
3237
     * s('bàř')->prepend('fòô'); // 'fòôbàř'
3238
     * </code>
3239
     *
3240
     * @param string ...$prefix <p>The string to append.</p>
3241
     *
3242
     * @psalm-mutation-free
3243
     *
3244
     * @return static
3245
     *                <p>Object with appended $prefix.</p>
3246
     */
3247
    public function prepend(string ...$prefix): self
3248
    {
3249
        if (\count($prefix) <= 1) {
8✔
3250
            $prefix = $prefix[0];
6✔
3251
        } else {
3252
            $prefix = \implode('', $prefix);
2✔
3253
        }
3254

3255
        return static::create($prefix . $this->str, $this->encoding);
8✔
3256
    }
3257

3258
    /**
3259
     * Returns a new string starting with $prefix.
3260
     *
3261
     * EXAMPLE: <code>
3262
     * </code>
3263
     *
3264
     * @param CollectionStringy|static ...$prefix <p>The Stringy objects to append.</p>
3265
     *
3266
     * @phpstan-param CollectionStringy<int,static>|static ...$prefix
3267
     *
3268
     * @psalm-mutation-free
3269
     *
3270
     * @return static
3271
     *                <p>Object with appended $prefix.</p>
3272
     */
3273
    public function prependStringy(...$prefix): self
3274
    {
3275
        $prefixStr = '';
2✔
3276
        foreach ($prefix as $prefixTmp) {
2✔
3277
            if ($prefixTmp instanceof CollectionStringy) {
2✔
3278
                $prefixStr .= $prefixTmp->implode('');
2✔
3279
            } else {
3280
                $prefixStr .= $prefixTmp->toString();
2✔
3281
            }
3282
        }
3283

3284
        return static::create($prefixStr . $this->str, $this->encoding);
2✔
3285
    }
3286

3287
    /**
3288
     * Replaces all occurrences of $pattern in $str by $replacement.
3289
     *
3290
     * EXAMPLE: <code>
3291
     * s('fòô ')->regexReplace('f[òô]+\s', 'bàř'); // 'bàř'
3292
     * s('fò')->regexReplace('(ò)', '\\1ô'); // 'fòô'
3293
     * </code>
3294
     *
3295
     * @param string $pattern     <p>The regular expression pattern.</p>
3296
     * @param string $replacement <p>The string to replace with.</p>
3297
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
3298
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
3299
     *
3300
     * @psalm-mutation-free
3301
     *
3302
     * @return static
3303
     *                <p>Object with the result2ing $str after the replacements.</p>
3304
     */
3305
    public function regexReplace(
3306
        string $pattern,
3307
        string $replacement,
3308
        string $options = '',
3309
        string $delimiter = '/'
3310
    ): self {
3311
        return static::create(
29✔
3312
            $this->utf8::regex_replace(
29✔
3313
                $this->str,
29✔
3314
                $pattern,
29✔
3315
                $replacement,
29✔
3316
                $options,
29✔
3317
                $delimiter
29✔
3318
            ),
29✔
3319
            $this->encoding
29✔
3320
        );
29✔
3321
    }
3322

3323
    /**
3324
     * Remove html via "strip_tags()" from the string.
3325
     *
3326
     * EXAMPLE: <code>
3327
     * s('řàb <ô>òf\', ô<br/>foo <a href="#">lall</a>')->removeHtml('<br><br/>'); // 'řàb òf\', ô<br/>foo lall'
3328
     * </code>
3329
     *
3330
     * @param string $allowableTags [optional] <p>You can use the optional second parameter to specify tags which should
3331
     *                              not be stripped. Default: null
3332
     *                              </p>
3333
     *
3334
     * @psalm-mutation-free
3335
     *
3336
     * @return static
3337
     */
3338
    public function removeHtml(string $allowableTags = ''): self
3339
    {
3340
        return static::create(
12✔
3341
            $this->utf8::remove_html($this->str, $allowableTags),
12✔
3342
            $this->encoding
12✔
3343
        );
12✔
3344
    }
3345

3346
    /**
3347
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
3348
     *
3349
     * EXAMPLE: <code>
3350
     * s('řàb <ô>òf\', ô<br/>foo <a href="#">lall</a>')->removeHtmlBreak(''); // 'řàb <ô>òf\', ô< foo <a href="#">lall</a>'
3351
     * </code>
3352
     *
3353
     * @param string $replacement [optional] <p>Default is a empty string.</p>
3354
     *
3355
     * @psalm-mutation-free
3356
     *
3357
     * @return static
3358
     */
3359
    public function removeHtmlBreak(string $replacement = ''): self
3360
    {
3361
        return static::create(
13✔
3362
            $this->utf8::remove_html_breaks($this->str, $replacement),
13✔
3363
            $this->encoding
13✔
3364
        );
13✔
3365
    }
3366

3367
    /**
3368
     * Returns a new string with the prefix $substring removed, if present.
3369
     *
3370
     * EXAMPLE: <code>
3371
     * s('fòôbàř')->removeLeft('fòô'); // 'bàř'
3372
     * </code>
3373
     *
3374
     * @param string $substring <p>The prefix to remove.</p>
3375
     *
3376
     * @psalm-mutation-free
3377
     *
3378
     * @return static
3379
     *                <p>Object having a $str without the prefix $substring.</p>
3380
     */
3381
    public function removeLeft(string $substring): self
3382
    {
3383
        return static::create(
36✔
3384
            $this->utf8::remove_left($this->str, $substring, $this->encoding),
36✔
3385
            $this->encoding
36✔
3386
        );
36✔
3387
    }
3388

3389
    /**
3390
     * Returns a new string with the suffix $substring removed, if present.
3391
     *
3392
     * EXAMPLE: <code>
3393
     * s('fòôbàř')->removeRight('bàř'); // 'fòô'
3394
     * </code>
3395
     *
3396
     * @param string $substring <p>The suffix to remove.</p>
3397
     *
3398
     * @psalm-mutation-free
3399
     *
3400
     * @return static
3401
     *                <p>Object having a $str without the suffix $substring.</p>
3402
     */
3403
    public function removeRight(string $substring): self
3404
    {
3405
        return static::create(
36✔
3406
            $this->utf8::remove_right($this->str, $substring, $this->encoding),
36✔
3407
            $this->encoding
36✔
3408
        );
36✔
3409
    }
3410

3411
    /**
3412
     * Try to remove all XSS-attacks from the string.
3413
     *
3414
     * EXAMPLE: <code>
3415
     * s('<IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29>')->removeXss(); // '<IMG >'
3416
     * </code>
3417
     *
3418
     * @psalm-mutation-free
3419
     *
3420
     * @return static
3421
     */
3422
    public function removeXss(): self
3423
    {
3424
        /**
3425
         * @var AntiXSS|null
3426
         *
3427
         * @psalm-suppress ImpureStaticVariable
3428
         */
3429
        static $antiXss = null;
12✔
3430

3431
        if ($antiXss === null) {
12✔
3432
            $antiXss = new AntiXSS();
1✔
3433
        }
3434

3435
        /**
3436
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the anti-xss class
3437
         */
3438
        $str = $antiXss->xss_clean($this->str);
12✔
3439

3440
        return static::create($str, $this->encoding);
12✔
3441
    }
3442

3443
    /**
3444
     * Returns a repeated string given a multiplier.
3445
     *
3446
     * EXAMPLE: <code>
3447
     * s('α')->repeat(3); // 'ααα'
3448
     * </code>
3449
     *
3450
     * @param int $multiplier <p>The number of times to repeat the string.</p>
3451
     *
3452
     * @psalm-mutation-free
3453
     *
3454
     * @return static
3455
     *                <p>Object with a repeated str.</p>
3456
     */
3457
    public function repeat(int $multiplier): self
3458
    {
3459
        return static::create(
21✔
3460
            \str_repeat($this->str, $multiplier),
21✔
3461
            $this->encoding
21✔
3462
        );
21✔
3463
    }
3464

3465
    /**
3466
     * Replaces all occurrences of $search in $str by $replacement.
3467
     *
3468
     * EXAMPLE: <code>
3469
     * s('fòô bàř fòô bàř')->replace('fòô ', ''); // 'bàř bàř'
3470
     * </code>
3471
     *
3472
     * @param string $search        <p>The needle to search for.</p>
3473
     * @param string $replacement   <p>The string to replace with.</p>
3474
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
3475
     *
3476
     * @psalm-mutation-free
3477
     *
3478
     * @return static
3479
     *                <p>Object with the resulting $str after the replacements.</p>
3480
     */
3481
    public function replace(string $search, string $replacement, bool $caseSensitive = true): self
3482
    {
3483
        if ($this->str === '' && $search === '') {
77✔
3484
            return static::create($replacement, $this->encoding);
10✔
3485
        }
3486

3487
        if ($caseSensitive) {
67✔
3488
            return static::create(
55✔
3489
                \str_replace($search, $replacement, $this->str),
55✔
3490
                $this->encoding
55✔
3491
            );
55✔
3492
        }
3493

3494
        return static::create(
12✔
3495
            $this->utf8::str_ireplace($search, $replacement, $this->str),
12✔
3496
            $this->encoding
12✔
3497
        );
12✔
3498
    }
3499

3500
    /**
3501
     * Replaces all occurrences of $search in $str by $replacement.
3502
     *
3503
     * EXAMPLE: <code>
3504
     * s('fòô bàř lall bàř')->replaceAll(['fòÔ ', 'lall'], '', false); // 'bàř bàř'
3505
     * </code>
3506
     *
3507
     * @param string[]        $search        <p>The elements to search for.</p>
3508
     * @param string|string[] $replacement   <p>The string to replace with.</p>
3509
     * @param bool            $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
3510
     *
3511
     * @psalm-mutation-free
3512
     *
3513
     * @return static
3514
     *                <p>Object with the resulting $str after the replacements.</p>
3515
     */
3516
    public function replaceAll(array $search, $replacement, bool $caseSensitive = true): self
3517
    {
3518
        if ($caseSensitive) {
62✔
3519
            return static::create(
48✔
3520
                \str_replace($search, $replacement, $this->str),
48✔
3521
                $this->encoding
48✔
3522
            );
48✔
3523
        }
3524

3525
        return static::create(
14✔
3526
            $this->utf8::str_ireplace($search, $replacement, $this->str),
14✔
3527
            $this->encoding
14✔
3528
        );
14✔
3529
    }
3530

3531
    /**
3532
     * Replaces all occurrences of $search from the beginning of string with $replacement.
3533
     *
3534
     * EXAMPLE: <code>
3535
     * s('fòô bàř fòô bàř')->replaceBeginning('fòô', ''); // ' bàř bàř'
3536
     * </code>
3537
     *
3538
     * @param string $search      <p>The string to search for.</p>
3539
     * @param string $replacement <p>The replacement.</p>
3540
     *
3541
     * @psalm-mutation-free
3542
     *
3543
     * @return static
3544
     *                <p>Object with the resulting $str after the replacements.</p>
3545
     */
3546
    public function replaceBeginning(string $search, string $replacement): self
3547
    {
3548
        return static::create(
32✔
3549
            $this->utf8::str_replace_beginning($this->str, $search, $replacement),
32✔
3550
            $this->encoding
32✔
3551
        );
32✔
3552
    }
3553

3554
    /**
3555
     * Replaces all occurrences of $search from the ending of string with $replacement.
3556
     *
3557
     * EXAMPLE: <code>
3558
     * s('fòô bàř fòô bàř')->replaceEnding('bàř', ''); // 'fòô bàř fòô '
3559
     * </code>
3560
     *
3561
     * @param string $search      <p>The string to search for.</p>
3562
     * @param string $replacement <p>The replacement.</p>
3563
     *
3564
     * @psalm-mutation-free
3565
     *
3566
     * @return static
3567
     *                <p>Object with the resulting $str after the replacements.</p>
3568
     */
3569
    public function replaceEnding(string $search, string $replacement): self
3570
    {
3571
        return static::create(
32✔
3572
            $this->utf8::str_replace_ending($this->str, $search, $replacement),
32✔
3573
            $this->encoding
32✔
3574
        );
32✔
3575
    }
3576

3577
    /**
3578
     * Replaces first occurrences of $search from the beginning of string with $replacement.
3579
     *
3580
     * EXAMPLE: <code>
3581
     * </code>
3582
     *
3583
     * @param string $search      <p>The string to search for.</p>
3584
     * @param string $replacement <p>The replacement.</p>
3585
     *
3586
     * @psalm-mutation-free
3587
     *
3588
     * @return static
3589
     *                <p>Object with the resulting $str after the replacements.</p>
3590
     */
3591
    public function replaceFirst(string $search, string $replacement): self
3592
    {
3593
        return static::create(
32✔
3594
            $this->utf8::str_replace_first($search, $replacement, $this->str),
32✔
3595
            $this->encoding
32✔
3596
        );
32✔
3597
    }
3598

3599
    /**
3600
     * Replaces last occurrences of $search from the ending of string with $replacement.
3601
     *
3602
     * EXAMPLE: <code>
3603
     * </code>
3604
     *
3605
     * @param string $search      <p>The string to search for.</p>
3606
     * @param string $replacement <p>The replacement.</p>
3607
     *
3608
     * @psalm-mutation-free
3609
     *
3610
     * @return static
3611
     *                <p>Object with the resulting $str after the replacements.</p>
3612
     */
3613
    public function replaceLast(string $search, string $replacement): self
3614
    {
3615
        return static::create(
30✔
3616
            $this->utf8::str_replace_last($search, $replacement, $this->str),
30✔
3617
            $this->encoding
30✔
3618
        );
30✔
3619
    }
3620

3621
    /**
3622
     * Returns a reversed string. A multibyte version of strrev().
3623
     *
3624
     * EXAMPLE: <code>
3625
     * s('fòôbàř')->reverse(); // 'řàbôòf'
3626
     * </code>
3627
     *
3628
     * @psalm-mutation-free
3629
     *
3630
     * @return static
3631
     *                <p>Object with a reversed $str.</p>
3632
     */
3633
    public function reverse(): self
3634
    {
3635
        return static::create($this->utf8::strrev($this->str), $this->encoding);
15✔
3636
    }
3637

3638
    /**
3639
     * Truncates the string to a given length, while ensuring that it does not
3640
     * split words. If $substring is provided, and truncating occurs, the
3641
     * string is further truncated so that the substring may be appended without
3642
     * exceeding the desired length.
3643
     *
3644
     * EXAMPLE: <code>
3645
     * s('What are your plans today?')->safeTruncate(22, '...'); // 'What are your plans...'
3646
     * </code>
3647
     *
3648
     * @param int    $length                          <p>Desired length of the truncated string.</p>
3649
     * @param string $substring                       [optional] <p>The substring to append if it can fit. Default: ''</p>
3650
     * @param bool   $ignoreDoNotSplitWordsForOneWord
3651
     *
3652
     * @psalm-mutation-free
3653
     *
3654
     * @return static
3655
     *                <p>Object with the resulting $str after truncating.</p>
3656
     */
3657
    public function safeTruncate(
3658
        int $length,
3659
        string $substring = '',
3660
        bool $ignoreDoNotSplitWordsForOneWord = true
3661
    ): self {
3662
        return static::create(
68✔
3663
            $this->utf8::str_truncate_safe(
68✔
3664
                $this->str,
68✔
3665
                $length,
68✔
3666
                $substring,
68✔
3667
                $this->encoding,
68✔
3668
                $ignoreDoNotSplitWordsForOneWord
68✔
3669
            ),
68✔
3670
            $this->encoding
68✔
3671
        );
68✔
3672
    }
3673

3674
    /**
3675
     * Set the internal character encoding.
3676
     *
3677
     * EXAMPLE: <code>
3678
     * </code>
3679
     *
3680
     * @param string $new_encoding <p>The desired character encoding.</p>
3681
     *
3682
     * @psalm-mutation-free
3683
     *
3684
     * @return static
3685
     */
3686
    public function setInternalEncoding(string $new_encoding): self
3687
    {
3688
        return new static($this->str, $new_encoding);
1✔
3689
    }
3690

3691
    /**
3692
     * Create a sha1 hash from the current string.
3693
     *
3694
     * EXAMPLE: <code>
3695
     * </code>
3696
     *
3697
     * @psalm-mutation-free
3698
     *
3699
     * @return static
3700
     */
3701
    public function sha1(): self
3702
    {
3703
        return static::create($this->hash('sha1'), $this->encoding);
2✔
3704
    }
3705

3706
    /**
3707
     * Create a sha256 hash from the current string.
3708
     *
3709
     * EXAMPLE: <code>
3710
     * </code>
3711
     *
3712
     * @psalm-mutation-free
3713
     *
3714
     * @return static
3715
     */
3716
    public function sha256(): self
3717
    {
3718
        return static::create($this->hash('sha256'), $this->encoding);
2✔
3719
    }
3720

3721
    /**
3722
     * Create a sha512 hash from the current string.
3723
     *
3724
     * EXAMPLE: <code>
3725
     * </code>
3726
     *
3727
     * @psalm-mutation-free
3728
     *
3729
     * @return static
3730
     */
3731
    public function sha512(): self
3732
    {
3733
        return static::create($this->hash('sha512'), $this->encoding);
2✔
3734
    }
3735

3736
    /**
3737
     * Shorten the string after $length, but also after the next word.
3738
     *
3739
     * EXAMPLE: <code>
3740
     * s('this is a test')->shortenAfterWord(2, '...'); // 'this...'
3741
     * </code>
3742
     *
3743
     * @param int    $length   <p>The given length.</p>
3744
     * @param string $strAddOn [optional] <p>Default: '…'</p>
3745
     *
3746
     * @psalm-mutation-free
3747
     *
3748
     * @return static
3749
     */
3750
    public function shortenAfterWord(int $length, string $strAddOn = '…'): self
3751
    {
3752
        if ($length <= 0) {
12✔
3753
            return static::create('', $this->encoding);
4✔
3754
        }
3755

3756
        return static::create(
8✔
3757
            $this->utf8::str_limit_after_word($this->str, $length, $strAddOn),
8✔
3758
            $this->encoding
8✔
3759
        );
8✔
3760
    }
3761

3762
    /**
3763
     * A multibyte string shuffle function. It returns a string with its
3764
     * characters in random order.
3765
     *
3766
     * EXAMPLE: <code>
3767
     * s('fòôbàř')->shuffle(); // 'àôřbòf'
3768
     * </code>
3769
     *
3770
     * @return static
3771
     *                <p>Object with a shuffled $str.</p>
3772
     */
3773
    public function shuffle(): self
3774
    {
3775
        return static::create($this->utf8::str_shuffle($this->str), $this->encoding);
9✔
3776
    }
3777

3778
    /**
3779
     * Calculate the similarity between two strings.
3780
     *
3781
     * EXAMPLE: <code>
3782
     * </code>
3783
     *
3784
     * @param string $str <p>The delimiting string.</p>
3785
     *
3786
     * @psalm-mutation-free
3787
     *
3788
     * @return float
3789
     */
3790
    public function similarity(string $str): float
3791
    {
3792
        \similar_text($this->str, $str, $percent);
3✔
3793

3794
        return $percent;
3✔
3795
    }
3796

3797
    /**
3798
     * Returns the substring beginning at $start, and up to, but not including
3799
     * the index specified by $end. If $end is omitted, the function extracts
3800
     * the remaining string. If $end is negative, it is computed from the end
3801
     * of the string.
3802
     *
3803
     * EXAMPLE: <code>
3804
     * s('fòôbàř')->slice(3, -1); // 'bà'
3805
     * </code>
3806
     *
3807
     * @param int $start <p>Initial index from which to begin extraction.</p>
3808
     * @param int $end   [optional] <p>Index at which to end extraction. Default: null</p>
3809
     *
3810
     * @psalm-mutation-free
3811
     *
3812
     * @return static
3813
     *                <p>Object with its $str being the extracted substring.</p>
3814
     */
3815
    public function slice(int $start, ?int $end = null): self
3816
    {
3817
        return static::create(
51✔
3818
            $this->utf8::str_slice($this->str, $start, $end, $this->encoding),
51✔
3819
            $this->encoding
51✔
3820
        );
51✔
3821
    }
3822

3823
    /**
3824
     * Converts the string into an URL slug. This includes replacing non-ASCII
3825
     * characters with their closest ASCII equivalents, removing remaining
3826
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
3827
     * $separator. The separator defaults to a single dash, and the string
3828
     * is also converted to lowercase. The language of the source string can
3829
     * also be supplied for language-specific transliteration.
3830
     *
3831
     * EXAMPLE: <code>
3832
     * s('Using strings like fòô bàř')->slugify(); // 'using-strings-like-foo-bar'
3833
     * </code>
3834
     *
3835
     * @param string                $separator             [optional] <p>The string used to replace whitespace.</p>
3836
     * @param string                $language              [optional] <p>Language of the source string.</p>
3837
     * @param array<string, string> $replacements          [optional] <p>A map of replaceable strings.</p>
3838
     * @param bool                  $replace_extra_symbols [optional]  <p>Add some more replacements e.g. "£" with "
3839
     *                                                     pound ".</p>
3840
     * @param bool                  $use_str_to_lower      [optional] <p>Use "string to lower" for the input.</p>
3841
     * @param bool                  $use_transliterate     [optional]  <p>Use ASCII::to_transliterate() for unknown
3842
     *                                                     chars.</p>
3843
     *
3844
     * @psalm-mutation-free
3845
     *
3846
     * @return static
3847
     *                <p>Object whose $str has been converted to an URL slug.</p>
3848
     *
3849
     * @phpstan-param ASCII::*_LANGUAGE_CODE $language
3850
     *
3851
     * @noinspection PhpTooManyParametersInspection
3852
     */
3853
    public function slugify(
3854
        string $separator = '-',
3855
        string $language = 'en',
3856
        array $replacements = [],
3857
        bool $replace_extra_symbols = true,
3858
        bool $use_str_to_lower = true,
3859
        bool $use_transliterate = false
3860
    ): self {
3861
        return static::create(
18✔
3862
            $this->ascii::to_slugify(
18✔
3863
                $this->str,
18✔
3864
                $separator,
18✔
3865
                $language,
18✔
3866
                $replacements,
18✔
3867
                $replace_extra_symbols,
18✔
3868
                $use_str_to_lower,
18✔
3869
                $use_transliterate
18✔
3870
            ),
18✔
3871
            $this->encoding
18✔
3872
        );
18✔
3873
    }
3874

3875
    /**
3876
     * Convert the string to snake_case.
3877
     *
3878
     * EXAMPLE: <code>
3879
     * </code>
3880
     *
3881
     * @psalm-mutation-free
3882
     *
3883
     * @return static
3884
     */
3885
    public function snakeCase(): self
3886
    {
3887
        $words = \array_map(
4✔
3888
            static function (self $word) {
4✔
3889
                return $word->toLowerCase();
4✔
3890
            },
4✔
3891
            $this->words('', true)
4✔
3892
        );
4✔
3893

3894
        return new static(\implode('_', $words), $this->encoding);
4✔
3895
    }
3896

3897
    /**
3898
     * Convert a string to snake_case.
3899
     *
3900
     * EXAMPLE: <code>
3901
     * s('foo1 Bar')->snakeize(); // 'foo_1_bar'
3902
     * </code>
3903
     *
3904
     * @psalm-mutation-free
3905
     *
3906
     * @return static
3907
     *                <p>Object with $str in snake_case.</p>
3908
     */
3909
    public function snakeize(): self
3910
    {
3911
        return static::create(
40✔
3912
            $this->utf8::str_snakeize($this->str, $this->encoding),
40✔
3913
            $this->encoding
40✔
3914
        );
40✔
3915
    }
3916

3917
    /**
3918
     * Wrap the string after the first whitespace character after a given number
3919
     * of characters.
3920
     *
3921
     * EXAMPLE: <code>
3922
     * </code>
3923
     *
3924
     * @param int    $width <p>Number of characters at which to wrap.</p>
3925
     * @param string $break [optional] <p>Character used to break the string. | Default "\n"</p>
3926
     *
3927
     * @psalm-mutation-free
3928
     *
3929
     * @return static
3930
     */
3931
    public function softWrap(int $width, string $break = "\n"): self
3932
    {
3933
        return $this->lineWrapAfterWord($width, $break, false);
2✔
3934
    }
3935

3936
    /**
3937
     * Splits the string with the provided regular expression, returning an
3938
     * array of Stringy objects. An optional integer $limit will truncate the
3939
     * results.
3940
     *
3941
     * EXAMPLE: <code>
3942
     * s('foo,bar,baz')->split(',', 2); // ['foo', 'bar']
3943
     * </code>
3944
     *
3945
     * @param string $pattern <p>The regex with which to split the string.</p>
3946
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no
3947
     *                        limit</p>
3948
     *
3949
     * @psalm-mutation-free
3950
     *
3951
     * @return static[]
3952
     *                  <p>An array of Stringy objects.</p>
3953
     *
3954
     * @phpstan-return array<int,static>
3955
     */
3956
    public function split(string $pattern, ?int $limit = null): array
3957
    {
3958
        if ($this->str === '') {
53✔
3959
            return [];
×
3960
        }
3961

3962
        if ($limit === null) {
53✔
3963
            $array = $this->utf8::str_split_pattern($this->str, $pattern);
9✔
3964
        } else {
3965
            $array = $this->utf8::str_split_pattern($this->str, $pattern, $limit);
44✔
3966
        }
3967

3968
        foreach ($array as &$value) {
53✔
3969
            $value = static::create($value, $this->encoding);
47✔
3970
        }
3971

3972
        /** @noinspection PhpSillyAssignmentInspection */
3973
        /** @var static[] $array */
3974
        $array = $array;
53✔
3975

3976
        return $array;
53✔
3977
    }
3978

3979
    /**
3980
     * Splits the string with the provided regular expression, returning an
3981
     * collection of Stringy objects. An optional integer $limit will truncate the
3982
     * results.
3983
     *
3984
     * EXAMPLE: <code>
3985
     * </code>
3986
     *
3987
     * @param string $pattern <p>The regex with which to split the string.</p>
3988
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no
3989
     *                        limit</p>
3990
     *
3991
     * @psalm-mutation-free
3992
     *
3993
     * @return CollectionStringy|static[]
3994
     *                                    <p>An collection of Stringy objects.</p>
3995
     *
3996
     * @phpstan-return CollectionStringy<int,static>
3997
     */
3998
    public function splitCollection(string $pattern, ?int $limit = null): CollectionStringy
3999
    {
4000
        /**
4001
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
4002
         */
4003
        return CollectionStringy::create(
35✔
4004
            $this->split($pattern, $limit)
35✔
4005
        );
35✔
4006
    }
4007

4008
    /**
4009
     * Returns true if the string begins with $substring, false otherwise. By
4010
     * default, the comparison is case-sensitive, but can be made insensitive
4011
     * by setting $caseSensitive to false.
4012
     *
4013
     * EXAMPLE: <code>
4014
     * s('FÒÔbàřbaz')->startsWith('fòôbàř', false); // true
4015
     * </code>
4016
     *
4017
     * @param string $substring     <p>The substring to look for.</p>
4018
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4019
     *
4020
     * @psalm-mutation-free
4021
     *
4022
     * @return bool
4023
     *              <p>Whether or not $str starts with $substring.</p>
4024
     */
4025
    public function startsWith(string $substring, bool $caseSensitive = true): bool
4026
    {
4027
        if ($caseSensitive) {
99✔
4028
            return $this->utf8::str_starts_with($this->str, $substring);
53✔
4029
        }
4030

4031
        return $this->utf8::str_istarts_with($this->str, $substring);
46✔
4032
    }
4033

4034
    /**
4035
     * Returns true if the string begins with any of $substrings, false otherwise.
4036
     * By default the comparison is case-sensitive, but can be made insensitive by
4037
     * setting $caseSensitive to false.
4038
     *
4039
     * EXAMPLE: <code>
4040
     * s('FÒÔbàřbaz')->startsWithAny(['fòô', 'bàř'], false); // true
4041
     * </code>
4042
     *
4043
     * @param string[] $substrings    <p>Substrings to look for.</p>
4044
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4045
     *
4046
     * @psalm-mutation-free
4047
     *
4048
     * @return bool
4049
     *              <p>Whether or not $str starts with $substring.</p>
4050
     */
4051
    public function startsWithAny(array $substrings, bool $caseSensitive = true): bool
4052
    {
4053
        if ($caseSensitive) {
36✔
4054
            return $this->utf8::str_starts_with_any($this->str, $substrings);
24✔
4055
        }
4056

4057
        return $this->utf8::str_istarts_with_any($this->str, $substrings);
12✔
4058
    }
4059

4060
    /**
4061
     * Remove one or more strings from the string.
4062
     *
4063
     * EXAMPLE: <code>
4064
     * </code>
4065
     *
4066
     * @param string|string[] $search One or more strings to be removed
4067
     *
4068
     * @psalm-mutation-free
4069
     *
4070
     * @return static
4071
     */
4072
    public function strip($search): self
4073
    {
4074
        if (\is_array($search)) {
3✔
4075
            return $this->replaceAll($search, '');
1✔
4076
        }
4077

4078
        return $this->replace($search, '');
2✔
4079
    }
4080

4081
    /**
4082
     * Strip all whitespace characters. This includes tabs and newline characters,
4083
     * as well as multibyte whitespace such as the thin space and ideographic space.
4084
     *
4085
     * EXAMPLE: <code>
4086
     * s('   Ο     συγγραφέας  ')->stripWhitespace(); // 'Οσυγγραφέας'
4087
     * </code>
4088
     *
4089
     * @psalm-mutation-free
4090
     *
4091
     * @return static
4092
     */
4093
    public function stripWhitespace(): self
4094
    {
4095
        return static::create(
36✔
4096
            $this->utf8::strip_whitespace($this->str),
36✔
4097
            $this->encoding
36✔
4098
        );
36✔
4099
    }
4100

4101
    /**
4102
     * Remove css media-queries.
4103
     *
4104
     * EXAMPLE: <code>
4105
     * s('test @media (min-width:660px){ .des-cla #mv-tiles{width:480px} } test ')->stripeCssMediaQueries(); // 'test  test '
4106
     * </code>
4107
     *
4108
     * @psalm-mutation-free
4109
     *
4110
     * @return static
4111
     */
4112
    public function stripeCssMediaQueries(): self
4113
    {
4114
        return static::create(
2✔
4115
            $this->utf8::css_stripe_media_queries($this->str),
2✔
4116
            $this->encoding
2✔
4117
        );
2✔
4118
    }
4119

4120
    /**
4121
     * Remove empty html-tag.
4122
     *
4123
     * EXAMPLE: <code>
4124
     * s('foo<h1></h1>bar')->stripeEmptyHtmlTags(); // 'foobar'
4125
     * </code>
4126
     *
4127
     * @psalm-mutation-free
4128
     *
4129
     * @return static
4130
     */
4131
    public function stripeEmptyHtmlTags(): self
4132
    {
4133
        return static::create(
2✔
4134
            $this->utf8::html_stripe_empty_tags($this->str),
2✔
4135
            $this->encoding
2✔
4136
        );
2✔
4137
    }
4138

4139
    /**
4140
     * Convert the string to StudlyCase.
4141
     *
4142
     * EXAMPLE: <code>
4143
     * </code>
4144
     *
4145
     * @psalm-mutation-free
4146
     *
4147
     * @return static
4148
     */
4149
    public function studlyCase(): self
4150
    {
4151
        $words = \array_map(
6✔
4152
            static function (self $word) {
6✔
4153
                return $word->substr(0, 1)
6✔
4154
                    ->toUpperCase()
6✔
4155
                    ->appendStringy($word->substr(1));
6✔
4156
            },
6✔
4157
            $this->words('', true)
6✔
4158
        );
6✔
4159

4160
        return new static(\implode('', $words), $this->encoding);
6✔
4161
    }
4162

4163
    /**
4164
     * Returns the substring beginning at $start with the specified $length.
4165
     * It differs from the $this->utf8::substr() function in that providing a $length of
4166
     * null will return the rest of the string, rather than an empty string.
4167
     *
4168
     * EXAMPLE: <code>
4169
     * </code>
4170
     *
4171
     * @param int $start  <p>Position of the first character to use.</p>
4172
     * @param int $length [optional] <p>Maximum number of characters used. Default: null</p>
4173
     *
4174
     * @psalm-mutation-free
4175
     *
4176
     * @return static
4177
     *                <p>Object with its $str being the substring.</p>
4178
     */
4179
    public function substr(int $start, ?int $length = null): self
4180
    {
4181
        return static::create(
41✔
4182
            $this->utf8::substr(
41✔
4183
                $this->str,
41✔
4184
                $start,
41✔
4185
                $length,
41✔
4186
                $this->encoding
41✔
4187
            ),
41✔
4188
            $this->encoding
41✔
4189
        );
41✔
4190
    }
4191

4192
    /**
4193
     * Return part of the string.
4194
     * Alias for substr()
4195
     *
4196
     * EXAMPLE: <code>
4197
     * s('fòôbàř')->substring(2, 3); // 'ôbà'
4198
     * </code>
4199
     *
4200
     * @param int $start  <p>Starting position of the substring.</p>
4201
     * @param int $length [optional] <p>Length of substring.</p>
4202
     *
4203
     * @psalm-mutation-free
4204
     *
4205
     * @return static
4206
     */
4207
    public function substring(int $start, ?int $length = null): self
4208
    {
4209
        return $this->substr($start, $length);
4✔
4210
    }
4211

4212
    /**
4213
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
4214
     * If no match is found returns new empty Stringy object.
4215
     *
4216
     * EXAMPLE: <code>
4217
     * </code>
4218
     *
4219
     * @param string $needle       <p>The string to look for.</p>
4220
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
4221
     *
4222
     * @psalm-mutation-free
4223
     *
4224
     * @return static
4225
     */
4226
    public function substringOf(string $needle, bool $beforeNeedle = false): self
4227
    {
4228
        return static::create(
5✔
4229
            $this->utf8::str_substr_first(
5✔
4230
                $this->str,
5✔
4231
                $needle,
5✔
4232
                $beforeNeedle,
5✔
4233
                $this->encoding
5✔
4234
            ),
5✔
4235
            $this->encoding
5✔
4236
        );
5✔
4237
    }
4238

4239
    /**
4240
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
4241
     * If no match is found returns new empty Stringy object.
4242
     *
4243
     * EXAMPLE: <code>
4244
     * </code>
4245
     *
4246
     * @param string $needle       <p>The string to look for.</p>
4247
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
4248
     *
4249
     * @psalm-mutation-free
4250
     *
4251
     * @return static
4252
     */
4253
    public function substringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
4254
    {
4255
        return static::create(
5✔
4256
            $this->utf8::str_isubstr_first(
5✔
4257
                $this->str,
5✔
4258
                $needle,
5✔
4259
                $beforeNeedle,
5✔
4260
                $this->encoding
5✔
4261
            ),
5✔
4262
            $this->encoding
5✔
4263
        );
5✔
4264
    }
4265

4266
    /**
4267
     * Surrounds $str with the given substring.
4268
     *
4269
     * EXAMPLE: <code>
4270
     * s(' ͜ ')->surround('ʘ'); // 'ʘ ͜ ʘ'
4271
     * </code>
4272
     *
4273
     * @param string $substring <p>The substring to add to both sides.</P>
4274
     *
4275
     * @psalm-mutation-free
4276
     *
4277
     * @return static
4278
     *                <p>Object whose $str had the substring both prepended and appended.</p>
4279
     */
4280
    public function surround(string $substring): self
4281
    {
4282
        return static::create(
15✔
4283
            $substring . $this->str . $substring,
15✔
4284
            $this->encoding
15✔
4285
        );
15✔
4286
    }
4287

4288
    /**
4289
     * Returns a case swapped version of the string.
4290
     *
4291
     * EXAMPLE: <code>
4292
     * s('Ντανιλ')->swapCase(); // 'νΤΑΝΙΛ'
4293
     * </code>
4294
     *
4295
     * @psalm-mutation-free
4296
     *
4297
     * @return static
4298
     *                <p>Object whose $str has each character's case swapped.</P>
4299
     */
4300
    public function swapCase(): self
4301
    {
4302
        return static::create(
15✔
4303
            $this->utf8::swapCase($this->str, $this->encoding),
15✔
4304
            $this->encoding
15✔
4305
        );
15✔
4306
    }
4307

4308
    /**
4309
     * Returns a string with smart quotes, ellipsis characters, and dashes from
4310
     * Windows-1252 (commonly used in Word documents) replaced by their ASCII
4311
     * equivalents.
4312
     *
4313
     * EXAMPLE: <code>
4314
     * s('“I see…”')->tidy(); // '"I see..."'
4315
     * </code>
4316
     *
4317
     * @psalm-mutation-free
4318
     *
4319
     * @return static
4320
     *                <p>Object whose $str has those characters removed.</p>
4321
     */
4322
    public function tidy(): self
4323
    {
4324
        return static::create(
12✔
4325
            $this->ascii::normalize_msword($this->str),
12✔
4326
            $this->encoding
12✔
4327
        );
12✔
4328
    }
4329

4330
    /**
4331
     * Returns a trimmed string with the first letter of each word capitalized.
4332
     * Also accepts an array, $ignore, allowing you to list words not to be
4333
     * capitalized.
4334
     *
4335
     * EXAMPLE: <code>
4336
     * $ignore = ['at', 'by', 'for', 'in', 'of', 'on', 'out', 'to', 'the'];
4337
     * s('i like to watch television')->titleize($ignore); // 'I Like to Watch Television'
4338
     * </code>
4339
     *
4340
     * @param string[]|null $ignore            [optional] <p>An array of words not to capitalize or null.
4341
     *                                         Default: null</p>
4342
     * @param string|null   $word_define_chars [optional] <p>An string of chars that will be used as whitespace
4343
     *                                         separator === words.</p>
4344
     * @param string|null   $language          [optional] <p>Language of the source string.</p>
4345
     *
4346
     * @psalm-mutation-free
4347
     *
4348
     * @return static
4349
     *                <p>Object with a titleized $str.</p>
4350
     */
4351
    public function titleize(
4352
        ?array $ignore = null,
4353
        ?string $word_define_chars = null,
4354
        ?string $language = null
4355
    ): self {
4356
        return static::create(
25✔
4357
            $this->utf8::str_titleize(
25✔
4358
                $this->str,
25✔
4359
                $ignore,
25✔
4360
                $this->encoding,
25✔
4361
                false,
25✔
4362
                $language,
25✔
4363
                false,
25✔
4364
                true,
25✔
4365
                $word_define_chars
25✔
4366
            ),
25✔
4367
            $this->encoding
25✔
4368
        );
25✔
4369
    }
4370

4371
    /**
4372
     * Returns a trimmed string in proper title case: Also accepts an array, $ignore, allowing you to list words not to
4373
     * be capitalized.
4374
     *
4375
     * EXAMPLE: <code>
4376
     * </code>
4377
     *
4378
     * Adapted from John Gruber's script.
4379
     *
4380
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
4381
     *
4382
     * @param string[] $ignore <p>An array of words not to capitalize.</p>
4383
     *
4384
     * @psalm-mutation-free
4385
     *
4386
     * @return static
4387
     *                <p>Object with a titleized $str</p>
4388
     */
4389
    public function titleizeForHumans(array $ignore = []): self
4390
    {
4391
        return static::create(
70✔
4392
            $this->utf8::str_titleize_for_humans(
70✔
4393
                $this->str,
70✔
4394
                $ignore,
70✔
4395
                $this->encoding
70✔
4396
            ),
70✔
4397
            $this->encoding
70✔
4398
        );
70✔
4399
    }
4400

4401
    /**
4402
     * Returns an ASCII version of the string. A set of non-ASCII characters are
4403
     * replaced with their closest ASCII counterparts, and the rest are removed
4404
     * by default. The language or locale of the source string can be supplied
4405
     * for language-specific transliteration in any of the following formats:
4406
     * en, en_GB, or en-GB. For example, passing "de" results in "äöü" mapping
4407
     * to "aeoeue" rather than "aou" as in other languages.
4408
     *
4409
     * EXAMPLE: <code>
4410
     * s('fòôbàř')->toAscii(); // 'foobar'
4411
     * </code>
4412
     *
4413
     * @param string $language          [optional] <p>Language of the source string.</p>
4414
     * @param bool   $removeUnsupported [optional] <p>Whether or not to remove the
4415
     *                                  unsupported characters.</p>
4416
     *
4417
     * @psalm-mutation-free
4418
     *
4419
     * @return static
4420
     *                <p>Object whose $str contains only ASCII characters.</p>
4421
     *
4422
     * @phpstan-param ASCII::*_LANGUAGE_CODE $language
4423
     */
4424
    public function toAscii(string $language = 'en', bool $removeUnsupported = true): self
4425
    {
4426
        return static::create(
24✔
4427
            $this->ascii::to_ascii(
24✔
4428
                $this->str,
24✔
4429
                $language,
24✔
4430
                $removeUnsupported
24✔
4431
            ),
24✔
4432
            $this->encoding
24✔
4433
        );
24✔
4434
    }
4435

4436
    /**
4437
     * Returns a boolean representation of the given logical string value.
4438
     * For example, <strong>'true', '1', 'on' and 'yes'</strong> will return true. <strong>'false', '0',
4439
     * 'off', and 'no'</strong> will return false. In all instances, case is ignored.
4440
     * For other numeric strings, their sign will determine the return value.
4441
     * In addition, blank strings consisting of only whitespace will return
4442
     * false. For all other strings, the return value is a result of a
4443
     * boolean cast.
4444
     *
4445
     * EXAMPLE: <code>
4446
     * s('OFF')->toBoolean(); // false
4447
     * </code>
4448
     *
4449
     * @psalm-mutation-free
4450
     *
4451
     * @return bool
4452
     *              <p>A boolean value for the string.</p>
4453
     */
4454
    public function toBoolean(): bool
4455
    {
4456
        /**
4457
         * @psalm-suppress ArgumentTypeCoercion -> maybe the string looks like an int ;)
4458
         * @phpstan-ignore-next-line
4459
         */
4460
        return $this->utf8::to_boolean($this->str);
45✔
4461
    }
4462

4463
    /**
4464
     * Converts all characters in the string to lowercase.
4465
     *
4466
     * EXAMPLE: <code>
4467
     * s('FÒÔBÀŘ')->toLowerCase(); // 'fòôbàř'
4468
     * </code>
4469
     *
4470
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
4471
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
4472
     *
4473
     * @psalm-mutation-free
4474
     *
4475
     * @return static
4476
     *                <p>Object with all characters of $str being lowercase.</p>
4477
     */
4478
    public function toLowerCase($tryToKeepStringLength = false, $lang = null): self
4479
    {
4480
        return static::create(
24✔
4481
            $this->utf8::strtolower(
24✔
4482
                $this->str,
24✔
4483
                $this->encoding,
24✔
4484
                false,
24✔
4485
                $lang,
24✔
4486
                $tryToKeepStringLength
24✔
4487
            ),
24✔
4488
            $this->encoding
24✔
4489
        );
24✔
4490
    }
4491

4492
    /**
4493
     * Converts each tab in the string to some number of spaces, as defined by
4494
     * $tabLength. By default, each tab is converted to 4 consecutive spaces.
4495
     *
4496
     * EXAMPLE: <code>
4497
     * s(' String speech = "Hi"')->toSpaces(); // '    String speech = "Hi"'
4498
     * </code>
4499
     *
4500
     * @param int $tabLength [optional] <p>Number of spaces to replace each tab with. Default: 4</p>
4501
     *
4502
     * @psalm-mutation-free
4503
     *
4504
     * @return static
4505
     *                <p>Object whose $str has had tabs switched to spaces.</p>
4506
     */
4507
    public function toSpaces(int $tabLength = 4): self
4508
    {
4509
        if ($tabLength === 4) {
19✔
4510
            $tab = '    ';
10✔
4511
        } elseif ($tabLength === 2) {
10✔
4512
            $tab = '  ';
4✔
4513
        } else {
4514
            $tab = \str_repeat(' ', $tabLength);
7✔
4515
        }
4516

4517
        return static::create(
19✔
4518
            \str_replace("\t", $tab, $this->str),
19✔
4519
            $this->encoding
19✔
4520
        );
19✔
4521
    }
4522

4523
    /**
4524
     * Return Stringy object as string, but you can also use (string) for automatically casting the object into a
4525
     * string.
4526
     *
4527
     * EXAMPLE: <code>
4528
     * s('fòôbàř')->toString(); // 'fòôbàř'
4529
     * </code>
4530
     *
4531
     * @psalm-mutation-free
4532
     *
4533
     * @return string
4534
     */
4535
    public function toString(): string
4536
    {
4537
        return (string) $this->str;
2,216✔
4538
    }
4539

4540
    /**
4541
     * Converts each occurrence of some consecutive number of spaces, as
4542
     * defined by $tabLength, to a tab. By default, each 4 consecutive spaces
4543
     * are converted to a tab.
4544
     *
4545
     * EXAMPLE: <code>
4546
     * s('    fòô    bàř')->toTabs(); // '   fòô bàř'
4547
     * </code>
4548
     *
4549
     * @param int $tabLength [optional] <p>Number of spaces to replace with a tab. Default: 4</p>
4550
     *
4551
     * @psalm-mutation-free
4552
     *
4553
     * @return static
4554
     *                <p>Object whose $str has had spaces switched to tabs.</p>
4555
     */
4556
    public function toTabs(int $tabLength = 4): self
4557
    {
4558
        if ($tabLength === 4) {
16✔
4559
            $tab = '    ';
10✔
4560
        } elseif ($tabLength === 2) {
7✔
4561
            $tab = '  ';
4✔
4562
        } else {
4563
            $tab = \str_repeat(' ', $tabLength);
4✔
4564
        }
4565

4566
        return static::create(
16✔
4567
            \str_replace($tab, "\t", $this->str),
16✔
4568
            $this->encoding
16✔
4569
        );
16✔
4570
    }
4571

4572
    /**
4573
     * Converts the first character of each word in the string to uppercase
4574
     * and all other chars to lowercase.
4575
     *
4576
     * EXAMPLE: <code>
4577
     * s('fòô bàř')->toTitleCase(); // 'Fòô Bàř'
4578
     * </code>
4579
     *
4580
     * @psalm-mutation-free
4581
     *
4582
     * @return static
4583
     *                <p>Object with all characters of $str being title-cased.</p>
4584
     */
4585
    public function toTitleCase(): self
4586
    {
4587
        return static::create(
15✔
4588
            $this->utf8::titlecase($this->str, $this->encoding),
15✔
4589
            $this->encoding
15✔
4590
        );
15✔
4591
    }
4592

4593
    /**
4594
     * Returns an ASCII version of the string. A set of non-ASCII characters are
4595
     * replaced with their closest ASCII counterparts, and the rest are removed
4596
     * unless instructed otherwise.
4597
     *
4598
     * EXAMPLE: <code>
4599
     * </code>
4600
     *
4601
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
4602
     *                        performance | Default: false</p>
4603
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
4604
     *
4605
     * @psalm-mutation-free
4606
     *
4607
     * @return static
4608
     *                <p>Object whose $str contains only ASCII characters.</p>
4609
     */
4610
    public function toTransliterate(bool $strict = false, string $unknown = '?'): self
4611
    {
4612
        return static::create(
34✔
4613
            $this->ascii::to_transliterate($this->str, $unknown, $strict),
34✔
4614
            $this->encoding
34✔
4615
        );
34✔
4616
    }
4617

4618
    /**
4619
     * Converts all characters in the string to uppercase.
4620
     *
4621
     * EXAMPLE: <code>
4622
     * s('fòôbàř')->toUpperCase(); // 'FÒÔBÀŘ'
4623
     * </code>
4624
     *
4625
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
4626
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
4627
     *
4628
     * @psalm-mutation-free
4629
     *
4630
     * @return static
4631
     *                <p>Object with all characters of $str being uppercase.</p>
4632
     */
4633
    public function toUpperCase($tryToKeepStringLength = false, $lang = null): self
4634
    {
4635
        return static::create(
28✔
4636
            $this->utf8::strtoupper($this->str, $this->encoding, false, $lang, $tryToKeepStringLength),
28✔
4637
            $this->encoding
28✔
4638
        );
28✔
4639
    }
4640

4641
    /**
4642
     * Returns a string with whitespace removed from the start and end of the
4643
     * string. Supports the removal of unicode whitespace. Accepts an optional
4644
     * string of characters to strip instead of the defaults.
4645
     *
4646
     * EXAMPLE: <code>
4647
     * s('  fòôbàř  ')->trim(); // 'fòôbàř'
4648
     * </code>
4649
     *
4650
     * @param string $chars [optional] <p>String of characters to strip. Default: null</p>
4651
     *
4652
     * @psalm-mutation-free
4653
     *
4654
     * @return static
4655
     *                <p>Object with a trimmed $str.</p>
4656
     */
4657
    public function trim(?string $chars = null): self
4658
    {
4659
        return static::create(
36✔
4660
            $this->utf8::trim($this->str, $chars),
36✔
4661
            $this->encoding
36✔
4662
        );
36✔
4663
    }
4664

4665
    /**
4666
     * Returns a string with whitespace removed from the start of the string.
4667
     * Supports the removal of unicode whitespace. Accepts an optional
4668
     * string of characters to strip instead of the defaults.
4669
     *
4670
     * EXAMPLE: <code>
4671
     * s('  fòôbàř  ')->trimLeft(); // 'fòôbàř  '
4672
     * </code>
4673
     *
4674
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
4675
     *
4676
     * @psalm-mutation-free
4677
     *
4678
     * @return static
4679
     *                <p>Object with a trimmed $str.</p>
4680
     */
4681
    public function trimLeft(?string $chars = null): self
4682
    {
4683
        return static::create(
39✔
4684
            $this->utf8::ltrim($this->str, $chars),
39✔
4685
            $this->encoding
39✔
4686
        );
39✔
4687
    }
4688

4689
    /**
4690
     * Returns a string with whitespace removed from the end of the string.
4691
     * Supports the removal of unicode whitespace. Accepts an optional
4692
     * string of characters to strip instead of the defaults.
4693
     *
4694
     * EXAMPLE: <code>
4695
     * s('  fòôbàř  ')->trimRight(); // '  fòôbàř'
4696
     * </code>
4697
     *
4698
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
4699
     *
4700
     * @psalm-mutation-free
4701
     *
4702
     * @return static
4703
     *                <p>Object with a trimmed $str.</p>
4704
     */
4705
    public function trimRight(?string $chars = null): self
4706
    {
4707
        return static::create(
39✔
4708
            $this->utf8::rtrim($this->str, $chars),
39✔
4709
            $this->encoding
39✔
4710
        );
39✔
4711
    }
4712

4713
    /**
4714
     * Truncates the string to a given length. If $substring is provided, and
4715
     * truncating occurs, the string is further truncated so that the substring
4716
     * may be appended without exceeding the desired length.
4717
     *
4718
     * EXAMPLE: <code>
4719
     * s('What are your plans today?')->truncate(19, '...'); // 'What are your pl...'
4720
     * </code>
4721
     *
4722
     * @param int    $length    <p>Desired length of the truncated string.</p>
4723
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
4724
     *
4725
     * @psalm-mutation-free
4726
     *
4727
     * @return static
4728
     *                <p>Object with the resulting $str after truncating.</p>
4729
     */
4730
    public function truncate(int $length, string $substring = ''): self
4731
    {
4732
        return static::create(
66✔
4733
            $this->utf8::str_truncate($this->str, $length, $substring, $this->encoding),
66✔
4734
            $this->encoding
66✔
4735
        );
66✔
4736
    }
4737

4738
    /**
4739
     * Returns a lowercase and trimmed string separated by underscores.
4740
     * Underscores are inserted before uppercase characters (with the exception
4741
     * of the first character of the string), and in place of spaces as well as
4742
     * dashes.
4743
     *
4744
     * EXAMPLE: <code>
4745
     * s('TestUCase')->underscored(); // 'test_u_case'
4746
     * </code>
4747
     *
4748
     * @psalm-mutation-free
4749
     *
4750
     * @return static
4751
     *                <p>Object with an underscored $str.</p>
4752
     */
4753
    public function underscored(): self
4754
    {
4755
        return $this->delimit('_');
48✔
4756
    }
4757

4758
    /**
4759
     * Returns an UpperCamelCase version of the supplied string. It trims
4760
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
4761
     * and underscores, and removes spaces, dashes, underscores.
4762
     *
4763
     * EXAMPLE: <code>
4764
     * s('Upper Camel-Case')->upperCamelize(); // 'UpperCamelCase'
4765
     * </code>
4766
     *
4767
     * @psalm-mutation-free
4768
     *
4769
     * @return static
4770
     *                <p>Object with $str in UpperCamelCase.</p>
4771
     */
4772
    public function upperCamelize(): self
4773
    {
4774
        return static::create(
49✔
4775
            $this->utf8::str_upper_camelize($this->str, $this->encoding),
49✔
4776
            $this->encoding
49✔
4777
        );
49✔
4778
    }
4779

4780
    /**
4781
     * Converts the first character of the supplied string to upper case.
4782
     *
4783
     * EXAMPLE: <code>
4784
     * s('σ foo')->upperCaseFirst(); // 'Σ foo'
4785
     * </code>
4786
     *
4787
     * @psalm-mutation-free
4788
     *
4789
     * @return static
4790
     *                <p>Object with the first character of $str being upper case.</p>
4791
     */
4792
    public function upperCaseFirst(): self
4793
    {
4794
        return static::create($this->utf8::ucfirst($this->str, $this->encoding), $this->encoding);
18✔
4795
    }
4796

4797
    /**
4798
     * Simple url-decoding.
4799
     *
4800
     * e.g:
4801
     * 'test+test' => 'test test'
4802
     *
4803
     * EXAMPLE: <code>
4804
     * </code>
4805
     *
4806
     * @psalm-mutation-free
4807
     *
4808
     * @return static
4809
     */
4810
    public function urlDecode(): self
4811
    {
4812
        return static::create(\urldecode($this->str));
1✔
4813
    }
4814

4815
    /**
4816
     * Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.
4817
     *
4818
     * e.g:
4819
     * 'test+test'                     => 'test test'
4820
     * 'D&#252;sseldorf'               => 'Düsseldorf'
4821
     * 'D%FCsseldorf'                  => 'Düsseldorf'
4822
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4823
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4824
     * 'Düsseldorf'                   => 'Düsseldorf'
4825
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4826
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4827
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4828
     *
4829
     * EXAMPLE: <code>
4830
     * </code>
4831
     *
4832
     * @psalm-mutation-free
4833
     *
4834
     * @return static
4835
     */
4836
    public function urlDecodeMulti(): self
4837
    {
4838
        return static::create($this->utf8::urldecode($this->str));
1✔
4839
    }
4840

4841
    /**
4842
     * Simple url-decoding.
4843
     *
4844
     * e.g:
4845
     * 'test+test' => 'test+test
4846
     *
4847
     * EXAMPLE: <code>
4848
     * </code>
4849
     *
4850
     * @psalm-mutation-free
4851
     *
4852
     * @return static
4853
     */
4854
    public function urlDecodeRaw(): self
4855
    {
4856
        return static::create(\rawurldecode($this->str));
1✔
4857
    }
4858

4859
    /**
4860
     * Multi url-decoding + decode HTML entity + fix urlencoded-win1252-chars.
4861
     *
4862
     * e.g:
4863
     * 'test+test'                     => 'test+test'
4864
     * 'D&#252;sseldorf'               => 'Düsseldorf'
4865
     * 'D%FCsseldorf'                  => 'Düsseldorf'
4866
     * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4867
     * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4868
     * 'Düsseldorf'                   => 'Düsseldorf'
4869
     * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4870
     * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4871
     * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4872
     *
4873
     * EXAMPLE: <code>
4874
     * </code>
4875
     *
4876
     * @psalm-mutation-free
4877
     *
4878
     * @return static
4879
     */
4880
    public function urlDecodeRawMulti(): self
4881
    {
4882
        return static::create($this->utf8::rawurldecode($this->str));
1✔
4883
    }
4884

4885
    /**
4886
     * Simple url-encoding.
4887
     *
4888
     * e.g:
4889
     * 'test test' => 'test+test'
4890
     *
4891
     * EXAMPLE: <code>
4892
     * </code>
4893
     *
4894
     * @psalm-mutation-free
4895
     *
4896
     * @return static
4897
     */
4898
    public function urlEncode(): self
4899
    {
4900
        return static::create(\urlencode($this->str));
1✔
4901
    }
4902

4903
    /**
4904
     * Simple url-encoding.
4905
     *
4906
     * e.g:
4907
     * 'test test' => 'test%20test'
4908
     *
4909
     * EXAMPLE: <code>
4910
     * </code>
4911
     *
4912
     * @psalm-mutation-free
4913
     *
4914
     * @return static
4915
     */
4916
    public function urlEncodeRaw(): self
4917
    {
4918
        return static::create(\rawurlencode($this->str));
1✔
4919
    }
4920

4921
    /**
4922
     * Converts the string into an URL slug. This includes replacing non-ASCII
4923
     * characters with their closest ASCII equivalents, removing remaining
4924
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
4925
     * $separator. The separator defaults to a single dash, and the string
4926
     * is also converted to lowercase.
4927
     *
4928
     * EXAMPLE: <code>
4929
     * s('Using strings like fòô bàř - 1$')->urlify(); // 'using-strings-like-foo-bar-1-dollar'
4930
     * </code>
4931
     *
4932
     * @param string                $separator    [optional] <p>The string used to replace whitespace. Default: '-'</p>
4933
     * @param string                $language     [optional] <p>The language for the url. Default: 'en'</p>
4934
     * @param array<string, string> $replacements [optional] <p>A map of replaceable strings.</p>
4935
     * @param bool                  $strToLower   [optional] <p>string to lower. Default: true</p>
4936
     *
4937
     * @psalm-mutation-free
4938
     *
4939
     * @return static
4940
     *                <p>Object whose $str has been converted to an URL slug.</p>
4941
     *
4942
     * @phpstan-param ASCII::*_LANGUAGE_CODE $language
4943
     *
4944
     * @psalm-suppress ImpureMethodCall :/
4945
     */
4946
    public function urlify(
4947
        string $separator = '-',
4948
        string $language = 'en',
4949
        array $replacements = [],
4950
        bool $strToLower = true
4951
    ): self {
4952
        // init
4953
        $str = $this->str;
32✔
4954

4955
        foreach ($replacements as $from => $to) {
32✔
4956
            $str = \str_replace($from, $to, $str);
32✔
4957
        }
4958

4959
        return static::create(
32✔
4960
            URLify::slug(
32✔
4961
                $str,
32✔
4962
                $language,
32✔
4963
                $separator,
32✔
4964
                $strToLower
32✔
4965
            ),
32✔
4966
            $this->encoding
32✔
4967
        );
32✔
4968
    }
4969

4970
    /**
4971
     * Converts the string into an valid UTF-8 string.
4972
     *
4973
     * EXAMPLE: <code>
4974
     * s('Düsseldorf')->utf8ify(); // 'Düsseldorf'
4975
     * </code>
4976
     *
4977
     * @psalm-mutation-free
4978
     *
4979
     * @return static
4980
     */
4981
    public function utf8ify(): self
4982
    {
4983
        return static::create($this->utf8::cleanup($this->str), $this->encoding);
2✔
4984
    }
4985

4986
    /**
4987
     * Convert a string into an array of words.
4988
     *
4989
     * EXAMPLE: <code>
4990
     * </code>
4991
     *
4992
     * @param string   $char_list           [optional] <p>Additional chars for the definition of "words".</p>
4993
     * @param bool     $remove_empty_values [optional] <p>Remove empty values.</p>
4994
     * @param int|null $remove_short_values [optional] <p>The min. string length or null to disable</p>
4995
     *
4996
     * @psalm-mutation-free
4997
     *
4998
     * @return static[]
4999
     *
5000
     * @phpstan-return array<int,static>
5001
     */
5002
    public function words(
5003
        string $char_list = '',
5004
        bool $remove_empty_values = false,
5005
        ?int $remove_short_values = null
5006
    ): array {
5007
        if ($remove_short_values === null) {
16✔
5008
            $strings = $this->utf8::str_to_words(
16✔
5009
                $this->str,
16✔
5010
                $char_list,
16✔
5011
                $remove_empty_values
16✔
5012
            );
16✔
5013
        } else {
5014
            $strings = $this->utf8::str_to_words(
2✔
5015
                $this->str,
2✔
5016
                $char_list,
2✔
5017
                $remove_empty_values,
2✔
5018
                $remove_short_values
2✔
5019
            );
2✔
5020
        }
5021

5022
        /** @noinspection AlterInForeachInspection */
5023
        foreach ($strings as &$string) {
16✔
5024
            $string = static::create($string);
16✔
5025
        }
5026

5027
        /** @noinspection PhpSillyAssignmentInspection */
5028
        /** @var static[] $strings */
5029
        $strings = $strings;
16✔
5030

5031
        return $strings;
16✔
5032
    }
5033

5034
    /**
5035
     * Convert a string into an collection of words.
5036
     *
5037
     * EXAMPLE: <code>
5038
     * S::create('中文空白 oöäü#s')->wordsCollection('#', true)->toStrings(); // ['中文空白', 'oöäü#s']
5039
     * </code>
5040
     *
5041
     * @param string   $char_list           [optional] <p>Additional chars for the definition of "words".</p>
5042
     * @param bool     $remove_empty_values [optional] <p>Remove empty values.</p>
5043
     * @param int|null $remove_short_values [optional] <p>The min. string length or null to disable</p>
5044
     *
5045
     * @psalm-mutation-free
5046
     *
5047
     * @return CollectionStringy|static[]
5048
     *                                    <p>An collection of Stringy objects.</p>
5049
     *
5050
     * @phpstan-return CollectionStringy<int,static>
5051
     */
5052
    public function wordsCollection(
5053
        string $char_list = '',
5054
        bool $remove_empty_values = false,
5055
        ?int $remove_short_values = null
5056
    ): CollectionStringy {
5057
        /**
5058
         * @psalm-suppress ImpureMethodCall -> add more psalm stuff to the collection class
5059
         */
5060
        return CollectionStringy::create(
2✔
5061
            $this->words(
2✔
5062
                $char_list,
2✔
5063
                $remove_empty_values,
2✔
5064
                $remove_short_values
2✔
5065
            )
2✔
5066
        );
2✔
5067
    }
5068

5069
    /**
5070
     * Surrounds $str with the given substring.
5071
     *
5072
     * EXAMPLE: <code>
5073
     * </code>
5074
     *
5075
     * @param string $substring <p>The substring to add to both sides.</P>
5076
     *
5077
     * @psalm-mutation-free
5078
     *
5079
     * @return static
5080
     *                <p>Object whose $str had the substring both prepended and appended.</p>
5081
     */
5082
    public function wrap(string $substring): self
5083
    {
5084
        return $this->surround($substring);
10✔
5085
    }
5086

5087
    /**
5088
     * Returns the replacements for the toAscii() method.
5089
     *
5090
     * @psalm-mutation-free
5091
     *
5092
     * @return array<string, array<int, string>>
5093
     *                                           <p>An array of replacements.</p>
5094
     *
5095
     * @deprecated   this is only here for backward-compatibly reasons
5096
     */
5097
    protected function charsArray(): array
5098
    {
5099
        return $this->ascii::charsArrayWithMultiLanguageValues();
1✔
5100
    }
5101

5102
    /**
5103
     * Returns true if $str matches the supplied pattern, false otherwise.
5104
     *
5105
     * @param string $pattern <p>Regex pattern to match against.</p>
5106
     *
5107
     * @psalm-mutation-free
5108
     *
5109
     * @return bool
5110
     *              <p>Whether or not $str matches the pattern.</p>
5111
     */
5112
    protected function matchesPattern(string $pattern): bool
5113
    {
5114
        return $this->utf8::str_matches_pattern($this->str, $pattern);
27✔
5115
    }
5116
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc