Completed
Push — master ( e3f0be...13bac0 )
by Lars
01:45
created

Stringy::toBoolean()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stringy;
6
7
use voku\helper\AntiXSS;
8
use voku\helper\ASCII;
9
use voku\helper\EmailCheck;
10
use voku\helper\URLify;
11
use voku\helper\UTF8;
12
13
class Stringy implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
14
{
15
    /**
16
     * An instance's string.
17
     *
18
     * @var string
19
     */
20
    protected $str;
21
22
    /**
23
     * The string's encoding, which should be one of the mbstring module's
24
     * supported encodings.
25
     *
26
     * @var string
27
     */
28
    protected $encoding;
29
30
    /**
31
     * @var UTF8
32
     */
33
    private $utf8;
34
35
    /**
36
     * @var ASCII
37
     */
38
    private $ascii;
39
40
    /**
41
     * Initializes a Stringy object and assigns both str and encoding properties
42
     * the supplied values. $str is cast to a string prior to assignment, and if
43
     * $encoding is not specified, it defaults to mb_internal_encoding(). Throws
44
     * an InvalidArgumentException if the first argument is an array or object
45
     * without a __toString method.
46
     *
47
     * @param mixed  $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
48
     * @param string $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
49
     *
50
     * @throws \InvalidArgumentException
51
     *                                   <p>if an array or object without a
52
     *                                   __toString method is passed as the first argument</p>
53
     */
54 2236
    public function __construct($str = '', string $encoding = null)
55
    {
56 2236
        if (\is_array($str)) {
57 2
            throw new \InvalidArgumentException(
58 2
                'Passed value cannot be an array'
59
            );
60
        }
61
62
        if (
63 2234
            \is_object($str)
64
            &&
65 2234
            !\method_exists($str, '__toString')
66
        ) {
67 2
            throw new \InvalidArgumentException(
68 2
                'Passed object must have a __toString method'
69
            );
70
        }
71
72 2232
        $this->str = (string) $str;
73
74 2232
        static $ASCII = null;
75 2232
        if ($ASCII === null) {
76
            $ASCII = new ASCII();
77
        }
78 2232
        $this->ascii = $ASCII;
79
80 2232
        static $UTF8 = null;
81 2232
        if ($UTF8 === null) {
82
            $UTF8 = new UTF8();
83
        }
84 2232
        $this->utf8 = $UTF8;
85
86 2232
        if ($encoding !== 'UTF-8') {
87 1471
            $this->encoding = $this->utf8::normalize_encoding($encoding, 'UTF-8');
88
        } else {
89 1675
            $this->encoding = $encoding;
90
        }
91 2232
    }
92
93
    /**
94
     * Returns the value in $str.
95
     *
96
     * @return string
97
     *                <p>The current value of the $str property.</p>
98
     */
99 990
    public function __toString()
100
    {
101 990
        return (string) $this->str;
102
    }
103
104
    /**
105
     * Returns value which can be serialized by json_encode().
106
     *
107
     * @noinspection ReturnTypeCanBeDeclaredInspection
108
     *
109
     * @return string The current value of the $str property
110
     */
111 1
    public function jsonSerialize()
112
    {
113 1
        return (string) $this;
114
    }
115
116
    /**
117
     * Gets the substring after the first occurrence of a separator.
118
     * If no match is found returns new empty Stringy object.
119
     *
120
     * @param string $separator
121
     *
122
     * @return static
123
     */
124 2
    public function afterFirst(string $separator): self
125
    {
126 2
        return static::create(
127 2
            $this->utf8::str_substr_after_first_separator(
128 2
                $this->str,
129 2
                $separator,
130 2
                $this->encoding
131
            )
132
        );
133
    }
134
135
    /**
136
     * Gets the substring after the first occurrence of a separator.
137
     * If no match is found returns new empty Stringy object.
138
     *
139
     * @param string $separator
140
     *
141
     * @return static
142
     */
143 1
    public function afterFirstIgnoreCase(string $separator): self
144
    {
145 1
        return static::create(
146 1
            $this->utf8::str_isubstr_after_first_separator(
147 1
                $this->str,
148 1
                $separator,
149 1
                $this->encoding
150
            )
151
        );
152
    }
153
154
    /**
155
     * Gets the substring after the last occurrence of a separator.
156
     * If no match is found returns new empty Stringy object.
157
     *
158
     * @param string $separator
159
     *
160
     * @return static
161
     */
162 1
    public function afterLast(string $separator): self
163
    {
164 1
        return static::create(
165 1
            $this->utf8::str_substr_after_last_separator(
166 1
                $this->str,
167 1
                $separator,
168 1
                $this->encoding
169
            )
170
        );
171
    }
172
173
    /**
174
     * Gets the substring after the last occurrence of a separator.
175
     * If no match is found returns new empty Stringy object.
176
     *
177
     * @param string $separator
178
     *
179
     * @return static
180
     */
181 1
    public function afterLastIgnoreCase(string $separator): self
182
    {
183 1
        return static::create(
184 1
            $this->utf8::str_isubstr_after_last_separator(
185 1
                $this->str,
186 1
                $separator,
187 1
                $this->encoding
188
            )
189
        );
190
    }
191
192
    /**
193
     * Returns a new string with $string appended.
194
     *
195
     * @param string ...$suffix <p>The string to append.</p>
196
     *
197
     * @return static
198
     *                <p>Object with appended $string.</p>
199
     *
200
     * @noinspection PhpDocSignatureInspection
201
     */
202 8 View Code Duplication
    public function append(string ...$suffix): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
    {
204 8
        if (\count($suffix) <= 1) {
205
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
206 8
            $suffix = $suffix[0];
207
        } else {
208
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
209
            $suffix = \implode('', $suffix);
210
        }
211
212 8
        return static::create($this->str . $suffix, $this->encoding);
213
    }
214
215
    /**
216
     * Append an password (limited to chars that are good readable).
217
     *
218
     * @param int $length <p>Length of the random string.</p>
219
     *
220
     * @return static
221
     *                <p>Object with appended password.</p>
222
     */
223 1
    public function appendPassword(int $length): self
224
    {
225 1
        return $this->appendRandomString(
226 1
            $length,
227 1
            '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ!?_#'
228
        );
229
    }
230
231
    /**
232
     * Append an random string.
233
     *
234
     * @param int    $length        <p>Length of the random string.</p>
235
     * @param string $possibleChars [optional] <p>Characters string for the random selection.</p>
236
     *
237
     * @return static
238
     *                <p>Object with appended random string.</p>
239
     */
240 2
    public function appendRandomString(int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'): self
241
    {
242 2
        $str = $this->utf8::get_random_string($length, $possibleChars);
243
244 2
        return $this->append($str);
245
    }
246
247
    /**
248
     * Append an unique identifier.
249
     *
250
     * @param int|string $entropyExtra [optional] <p>Extra entropy via a string or int value.</p>
251
     * @param bool       $md5          [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
252
     *
253
     * @return static
254
     *                <p>Object with appended unique identifier as md5-hash.</p>
255
     */
256 1
    public function appendUniqueIdentifier($entropyExtra = '', bool $md5 = true): self
257
    {
258 1
        return $this->append(
259 1
            $this->utf8::get_unique_string($entropyExtra, $md5)
260
        );
261
    }
262
263
    /**
264
     * Returns the character at $index, with indexes starting at 0.
265
     *
266
     * @param int $index <p>Position of the character.</p>
267
     *
268
     * @return static
269
     *                <p>The character at $index.</p>
270
     */
271 16
    public function at(int $index): self
272
    {
273 16
        return static::create($this->utf8::char_at($this->str, $index), $this->encoding);
274
    }
275
276
    /**
277
     * Gets the substring before the first occurrence of a separator.
278
     * If no match is found returns new empty Stringy object.
279
     *
280
     * @param string $separator
281
     *
282
     * @return static
283
     */
284 1
    public function beforeFirst(string $separator): self
285
    {
286 1
        return static::create(
287 1
            $this->utf8::str_substr_before_first_separator(
288 1
                $this->str,
289 1
                $separator,
290 1
                $this->encoding
291
            )
292
        );
293
    }
294
295
    /**
296
     * Gets the substring before the first occurrence of a separator.
297
     * If no match is found returns new empty Stringy object.
298
     *
299
     * @param string $separator
300
     *
301
     * @return static
302
     */
303 1
    public function beforeFirstIgnoreCase(string $separator): self
304
    {
305 1
        return static::create(
306 1
            $this->utf8::str_isubstr_before_first_separator(
307 1
                $this->str,
308 1
                $separator,
309 1
                $this->encoding
310
            )
311
        );
312
    }
313
314
    /**
315
     * Gets the substring before the last occurrence of a separator.
316
     * If no match is found returns new empty Stringy object.
317
     *
318
     * @param string $separator
319
     *
320
     * @return static
321
     */
322 1
    public function beforeLast(string $separator): self
323
    {
324 1
        return static::create(
325 1
            $this->utf8::str_substr_before_last_separator(
326 1
                $this->str,
327 1
                $separator,
328 1
                $this->encoding
329
            )
330
        );
331
    }
332
333
    /**
334
     * Gets the substring before the last occurrence of a separator.
335
     * If no match is found returns new empty Stringy object.
336
     *
337
     * @param string $separator
338
     *
339
     * @return static
340
     */
341 1
    public function beforeLastIgnoreCase(string $separator): self
342
    {
343 1
        return static::create(
344 1
            $this->utf8::str_isubstr_before_last_separator(
345 1
                $this->str,
346 1
                $separator,
347 1
                $this->encoding
348
            )
349
        );
350
    }
351
352
    /**
353
     * Returns the substring between $start and $end, if found, or an empty
354
     * string. An optional offset may be supplied from which to begin the
355
     * search for the start string.
356
     *
357
     * @param string $start  <p>Delimiter marking the start of the substring.</p>
358
     * @param string $end    <p>Delimiter marking the end of the substring.</p>
359
     * @param int    $offset [optional] <p>Index from which to begin the search. Default: 0</p>
360
     *
361
     * @return static
362
     *                <p>Object whose $str is a substring between $start and $end.</p>
363
     */
364 32
    public function between(string $start, string $end, int $offset = null): self
365
    {
366
        /** @noinspection UnnecessaryCastingInspection */
367 32
        $str = $this->utf8::between(
368 32
            $this->str,
369 32
            $start,
370 32
            $end,
371 32
            (int) $offset,
372 32
            $this->encoding
373
        );
374
375 32
        return static::create($str, $this->encoding);
376
    }
377
378
    /**
379
     * Returns a camelCase version of the string. Trims surrounding spaces,
380
     * capitalizes letters following digits, spaces, dashes and underscores,
381
     * and removes spaces, dashes, as well as underscores.
382
     *
383
     * @return static
384
     *                <p>Object with $str in camelCase.</p>
385
     */
386 38
    public function camelize(): self
387
    {
388 38
        return static::create(
389 38
            $this->utf8::str_camelize($this->str, $this->encoding),
390 38
            $this->encoding
391
        );
392
    }
393
394
    /**
395
     * Returns the string with the first letter of each word capitalized,
396
     * except for when the word is a name which shouldn't be capitalized.
397
     *
398
     * @return static
399
     *                <p>Object with $str capitalized.</p>
400
     */
401 39
    public function capitalizePersonalName(): self
402
    {
403 39
        return static::create(
404 39
            $this->utf8::str_capitalize_name($this->str),
405 39
            $this->encoding
406
        );
407
    }
408
409
    /**
410
     * Returns an array consisting of the characters in the string.
411
     *
412
     * @return string[]
413
     *                  <p>An array of string chars.</p>
414
     */
415 8
    public function chars(): array
416
    {
417 8
        return $this->utf8::str_split($this->str);
418
    }
419
420
    /**
421
     * Convert a string into an array of words.
422
     *
423
     * @param string   $char_list           <p>Additional chars for the definition of "words".</p>
424
     * @param bool     $remove_empty_values <p>Remove empty values.</p>
425
     * @param int|null $remove_short_values <p>The min. string length or null to disable</p>
426
     *
427
     * @return CollectionStringy|static[]
428
     */
429 1
    public function words(
430
        string $char_list = '',
431
        bool $remove_empty_values = false,
432
        int $remove_short_values = null
433
    ): CollectionStringy
434
    {
435 1
        return CollectionStringy::createFromStrings(
436 1
            $this->utf8::str_to_words(
437 1
                $this->str,
438 1
                $char_list,
439 1
                $remove_empty_values,
440 1
                $remove_short_values
441
            )
442
        );
443
    }
444
445
    /**
446
     * Trims the string and replaces consecutive whitespace characters with a
447
     * single space. This includes tabs and newline characters, as well as
448
     * multibyte whitespace such as the thin space and ideographic space.
449
     *
450
     * @return static
451
     *                <p>Object with a trimmed $str and condensed whitespace.</p>
452
     */
453 26
    public function collapseWhitespace(): self
454
    {
455 26
        return static::create(
456 26
            $this->utf8::collapse_whitespace($this->str),
457 26
            $this->encoding
458
        );
459
    }
460
461
    /**
462
     * Returns true if the string contains $needle, false otherwise. By default
463
     * the comparison is case-sensitive, but can be made insensitive by setting
464
     * $caseSensitive to false.
465
     *
466
     * @param string $needle        <p>Substring to look for.</p>
467
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
468
     *
469
     * @return bool
470
     *              <p>Whether or not $str contains $needle.</p>
471
     */
472 42
    public function contains(string $needle, bool $caseSensitive = true): bool
473
    {
474 42
        return $this->utf8::str_contains(
475 42
            $this->str,
476 42
            $needle,
477 42
            $caseSensitive
478
        );
479
    }
480
481
    /**
482
     * Returns true if the string contains all $needles, false otherwise. By
483
     * default the comparison is case-sensitive, but can be made insensitive by
484
     * setting $caseSensitive to false.
485
     *
486
     * @param array $needles       <p>SubStrings to look for.</p>
487
     * @param bool  $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
488
     *
489
     * @return bool
490
     *              <p>Whether or not $str contains $needle.</p>
491
     */
492 87
    public function containsAll(array $needles, bool $caseSensitive = true): bool
493
    {
494 87
        return $this->utf8::str_contains_all(
495 87
            $this->str,
496 87
            $needles,
497 87
            $caseSensitive
498
        );
499
    }
500
501
    /**
502
     * Returns true if the string contains any $needles, false otherwise. By
503
     * default the comparison is case-sensitive, but can be made insensitive by
504
     * setting $caseSensitive to false.
505
     *
506
     * @param array $needles       <p>SubStrings to look for.</p>
507
     * @param bool  $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
508
     *
509
     * @return bool
510
     *              <p>Whether or not $str contains $needle.</p>
511
     */
512 86
    public function containsAny(array $needles, bool $caseSensitive = true): bool
513
    {
514 86
        return $this->utf8::str_contains_any(
515 86
            $this->str,
516 86
            $needles,
517 86
            $caseSensitive
518
        );
519
    }
520
521
    /**
522
     * Returns the length of the string, implementing the countable interface.
523
     *
524
     * @return int
525
     *             <p>The number of characters in the string, given the encoding.</p>
526
     */
527 2
    public function count(): int
528
    {
529 2
        return $this->length();
530
    }
531
532
    /**
533
     * Returns the number of occurrences of $substring in the given string.
534
     * By default, the comparison is case-sensitive, but can be made insensitive
535
     * by setting $caseSensitive to false.
536
     *
537
     * @param string $substring     <p>The substring to search for.</p>
538
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
539
     *
540
     * @return int
541
     */
542 30
    public function countSubstr(string $substring, bool $caseSensitive = true): int
543
    {
544 30
        return $this->utf8::substr_count_simple(
545 30
            $this->str,
546 30
            $substring,
547 30
            $caseSensitive,
548 30
            $this->encoding
549
        );
550
    }
551
552
    /**
553
     * Creates a Stringy object and assigns both str and encoding properties
554
     * the supplied values. $str is cast to a string prior to assignment, and if
555
     * $encoding is not specified, it defaults to mb_internal_encoding(). It
556
     * then returns the initialized object. Throws an InvalidArgumentException
557
     * if the first argument is an array or object without a __toString method.
558
     *
559
     * @param mixed  $str      [optional] <p>Value to modify, after being cast to string. Default: ''</p>
560
     * @param string $encoding [optional] <p>The character encoding. Fallback: 'UTF-8'</p>
561
     *
562
     * @throws \InvalidArgumentException
563
     *                                   <p>if an array or object without a
564
     *                                   __toString method is passed as the first argument</p>
565
     *
566
     * @return static
567
     *                <p>A Stringy object.</p>
568
     */
569 2214
    public static function create($str = '', string $encoding = null): self
570
    {
571 2214
        return new static($str, $encoding);
572
    }
573
574
    /**
575
     * Returns a lowercase and trimmed string separated by dashes. Dashes are
576
     * inserted before uppercase characters (with the exception of the first
577
     * character of the string), and in place of spaces as well as underscores.
578
     *
579
     * @return static
580
     *                <p>Object with a dasherized $str</p>
581
     */
582 38
    public function dasherize(): self
583
    {
584 38
        return static::create(
585 38
            $this->utf8::str_dasherize($this->str),
586 38
            $this->encoding
587
        );
588
    }
589
590
    /**
591
     * Returns a lowercase and trimmed string separated by the given delimiter.
592
     * Delimiters are inserted before uppercase characters (with the exception
593
     * of the first character of the string), and in place of spaces, dashes,
594
     * and underscores. Alpha delimiters are not converted to lowercase.
595
     *
596
     * @param string $delimiter <p>Sequence used to separate parts of the string.</p>
597
     *
598
     * @return static
599
     *                <p>Object with a delimited $str.</p>
600
     */
601 60
    public function delimit(string $delimiter): self
602
    {
603 60
        return static::create(
604 60
            $this->utf8::str_delimit($this->str, $delimiter),
605 60
            $this->encoding
606
        );
607
    }
608
609
    /**
610
     * Returns true if the string ends with $substring, false otherwise. By
611
     * default, the comparison is case-sensitive, but can be made insensitive
612
     * by setting $caseSensitive to false.
613
     *
614
     * @param string $substring     <p>The substring to look for.</p>
615
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
616
     *
617
     * @return bool
618
     *              <p>Whether or not $str ends with $substring.</p>
619
     */
620 54
    public function endsWith(string $substring, bool $caseSensitive = true): bool
621
    {
622 54
        if ($caseSensitive) {
623 30
            return $this->utf8::str_ends_with($this->str, $substring);
624
        }
625
626 24
        return $this->utf8::str_iends_with($this->str, $substring);
627
    }
628
629
    /**
630
     * Returns true if the string ends with any of $substrings, false otherwise.
631
     * By default, the comparison is case-sensitive, but can be made insensitive
632
     * by setting $caseSensitive to false.
633
     *
634
     * @param string[] $substrings    <p>Substrings to look for.</p>
635
     * @param bool     $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
636
     *
637
     * @return bool
638
     *              <p>Whether or not $str ends with $substring.</p>
639
     */
640 22
    public function endsWithAny(array $substrings, bool $caseSensitive = true): bool
641
    {
642 22
        if ($caseSensitive) {
643 14
            return $this->utf8::str_ends_with_any($this->str, $substrings);
644
        }
645
646 8
        return $this->utf8::str_iends_with_any($this->str, $substrings);
647
    }
648
649
    /**
650
     * Ensures that the string begins with $substring. If it doesn't, it's
651
     * prepended.
652
     *
653
     * @param string $substring <p>The substring to add if not present.</p>
654
     *
655
     * @return static
656
     *                <p>Object with its $str prefixed by the $substring.</p>
657
     */
658 20
    public function ensureLeft(string $substring): self
659
    {
660 20
        return static::create(
661 20
            $this->utf8::str_ensure_left($this->str, $substring),
662 20
            $this->encoding
663
        );
664
    }
665
666
    /**
667
     * Ensures that the string ends with $substring. If it doesn't, it's appended.
668
     *
669
     * @param string $substring <p>The substring to add if not present.</p>
670
     *
671
     * @return static
672
     *                <p>Object with its $str suffixed by the $substring.</p>
673
     */
674 20
    public function ensureRight(string $substring): self
675
    {
676 20
        return static::create(
677 20
            $this->utf8::str_ensure_right($this->str, $substring),
678 20
            $this->encoding
679
        );
680
    }
681
682
    /**
683
     * Create a escape html version of the string via "htmlspecialchars()".
684
     *
685
     * @return static
686
     */
687 6
    public function escape(): self
688
    {
689 6
        return static::create(
690 6
            $this->utf8::htmlspecialchars(
691 6
                $this->str,
692 6
                \ENT_QUOTES | \ENT_SUBSTITUTE,
693 6
                $this->encoding
694
            ),
695 6
            $this->encoding
696
        );
697
    }
698
699
    /**
700
     * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
701
     *
702
     * @param string   $search
703
     * @param int|null $length                 [optional] <p>Default: null === text->length / 2</p>
704
     * @param string   $replacerForSkippedText [optional] <p>Default: …</p>
705
     *
706
     * @return static
707
     */
708 1
    public function extractText(string $search = '', int $length = null, string $replacerForSkippedText = '…'): self
709
    {
710 1
        return static::create(
711 1
            $this->utf8::extract_text(
712 1
                $this->str,
713 1
                $search,
714 1
                $length,
715 1
                $replacerForSkippedText,
716 1
                $this->encoding
717
            ),
718 1
            $this->encoding
719
        );
720
    }
721
722
    /**
723
     * Returns the first $n characters of the string.
724
     *
725
     * @param int $n <p>Number of characters to retrieve from the start.</p>
726
     *
727
     * @return static
728
     *                <p>Object with its $str being the first $n chars.</p>
729
     */
730 25
    public function first(int $n): self
731
    {
732 25
        return static::create(
733 25
            $this->utf8::first_char($this->str, $n, $this->encoding),
734 25
            $this->encoding
735
        );
736
    }
737
738
    /**
739
     * Returns the encoding used by the Stringy object.
740
     *
741
     * @return string
742
     *                <p>The current value of the $encoding property.</p>
743
     */
744 5
    public function getEncoding(): string
745
    {
746 5
        return $this->encoding;
747
    }
748
749
    /**
750
     * Returns a new ArrayIterator, thus implementing the IteratorAggregate
751
     * interface. The ArrayIterator's constructor is passed an array of chars
752
     * in the multibyte string. This enables the use of foreach with instances
753
     * of Stringy\Stringy.
754
     *
755
     * @return \ArrayIterator
756
     *                        <p>An iterator for the characters in the string.</p>
757
     */
758 2
    public function getIterator(): \ArrayIterator
759
    {
760 2
        return new \ArrayIterator($this->chars());
761
    }
762
763
    /**
764
     * Returns true if the string contains a lower case char, false otherwise.
765
     *
766
     * @return bool
767
     *              <p>Whether or not the string contains a lower case character.</p>
768
     */
769 24
    public function hasLowerCase(): bool
770
    {
771 24
        return $this->utf8::has_lowercase($this->str);
772
    }
773
774
    /**
775
     * Returns true if the string contains an upper case char, false otherwise.
776
     *
777
     * @return bool
778
     *              <p>Whether or not the string contains an upper case character.</p>
779
     */
780 24
    public function hasUpperCase(): bool
781
    {
782 24
        return $this->utf8::has_uppercase($this->str);
783
    }
784
785
    /**
786
     * Convert all HTML entities to their applicable characters.
787
     *
788
     * @param int $flags [optional] <p>
789
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
790
     *                   which document type to use. The default is ENT_COMPAT.
791
     *                   <table>
792
     *                   Available <i>flags</i> constants
793
     *                   <tr valign="top">
794
     *                   <td>Constant Name</td>
795
     *                   <td>Description</td>
796
     *                   </tr>
797
     *                   <tr valign="top">
798
     *                   <td><b>ENT_COMPAT</b></td>
799
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
800
     *                   </tr>
801
     *                   <tr valign="top">
802
     *                   <td><b>ENT_QUOTES</b></td>
803
     *                   <td>Will convert both double and single quotes.</td>
804
     *                   </tr>
805
     *                   <tr valign="top">
806
     *                   <td><b>ENT_NOQUOTES</b></td>
807
     *                   <td>Will leave both double and single quotes unconverted.</td>
808
     *                   </tr>
809
     *                   <tr valign="top">
810
     *                   <td><b>ENT_HTML401</b></td>
811
     *                   <td>
812
     *                   Handle code as HTML 4.01.
813
     *                   </td>
814
     *                   </tr>
815
     *                   <tr valign="top">
816
     *                   <td><b>ENT_XML1</b></td>
817
     *                   <td>
818
     *                   Handle code as XML 1.
819
     *                   </td>
820
     *                   </tr>
821
     *                   <tr valign="top">
822
     *                   <td><b>ENT_XHTML</b></td>
823
     *                   <td>
824
     *                   Handle code as XHTML.
825
     *                   </td>
826
     *                   </tr>
827
     *                   <tr valign="top">
828
     *                   <td><b>ENT_HTML5</b></td>
829
     *                   <td>
830
     *                   Handle code as HTML 5.
831
     *                   </td>
832
     *                   </tr>
833
     *                   </table>
834
     *                   </p>
835
     *
836
     * @return static
837
     *                <p>Object with the resulting $str after being html decoded.</p>
838
     */
839 10 View Code Duplication
    public function htmlDecode(int $flags = \ENT_COMPAT): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
840
    {
841 10
        return static::create(
842 10
            $this->utf8::html_entity_decode(
843 10
                $this->str,
844 10
                $flags,
845 10
                $this->encoding
846
            ),
847 10
            $this->encoding
848
        );
849
    }
850
851
    /**
852
     * Convert all applicable characters to HTML entities.
853
     *
854
     * @param int $flags [optional] <p>
855
     *                   A bitmask of one or more of the following flags, which specify how to handle quotes and
856
     *                   which document type to use. The default is ENT_COMPAT.
857
     *                   <table>
858
     *                   Available <i>flags</i> constants
859
     *                   <tr valign="top">
860
     *                   <td>Constant Name</td>
861
     *                   <td>Description</td>
862
     *                   </tr>
863
     *                   <tr valign="top">
864
     *                   <td><b>ENT_COMPAT</b></td>
865
     *                   <td>Will convert double-quotes and leave single-quotes alone.</td>
866
     *                   </tr>
867
     *                   <tr valign="top">
868
     *                   <td><b>ENT_QUOTES</b></td>
869
     *                   <td>Will convert both double and single quotes.</td>
870
     *                   </tr>
871
     *                   <tr valign="top">
872
     *                   <td><b>ENT_NOQUOTES</b></td>
873
     *                   <td>Will leave both double and single quotes unconverted.</td>
874
     *                   </tr>
875
     *                   <tr valign="top">
876
     *                   <td><b>ENT_HTML401</b></td>
877
     *                   <td>
878
     *                   Handle code as HTML 4.01.
879
     *                   </td>
880
     *                   </tr>
881
     *                   <tr valign="top">
882
     *                   <td><b>ENT_XML1</b></td>
883
     *                   <td>
884
     *                   Handle code as XML 1.
885
     *                   </td>
886
     *                   </tr>
887
     *                   <tr valign="top">
888
     *                   <td><b>ENT_XHTML</b></td>
889
     *                   <td>
890
     *                   Handle code as XHTML.
891
     *                   </td>
892
     *                   </tr>
893
     *                   <tr valign="top">
894
     *                   <td><b>ENT_HTML5</b></td>
895
     *                   <td>
896
     *                   Handle code as HTML 5.
897
     *                   </td>
898
     *                   </tr>
899
     *                   </table>
900
     *                   </p>
901
     *
902
     * @return static
903
     *                <p>Object with the resulting $str after being html encoded.</p>
904
     */
905 10 View Code Duplication
    public function htmlEncode(int $flags = \ENT_COMPAT): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
906
    {
907 10
        return static::create(
908 10
            $this->utf8::htmlentities(
909 10
                $this->str,
910 10
                $flags,
911 10
                $this->encoding
912
            ),
913 10
            $this->encoding
914
        );
915
    }
916
917
    /**
918
     * Capitalizes the first word of the string, replaces underscores with
919
     * spaces, and strips '_id'.
920
     *
921
     * @return static
922
     *                <p>Object with a humanized $str.</p>
923
     */
924 6
    public function humanize(): self
925
    {
926 6
        return static::create(
927 6
            $this->utf8::str_humanize($this->str),
928 6
            $this->encoding
929
        );
930
    }
931
932
    /**
933
     * Returns the index of the first occurrence of $needle in the string,
934
     * and false if not found. Accepts an optional offset from which to begin
935
     * the search.
936
     *
937
     * @param string $needle <p>Substring to look for.</p>
938
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
939
     *
940
     * @return false|int
941
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
942
     */
943 21
    public function indexOf(string $needle, int $offset = 0)
944
    {
945 21
        return $this->utf8::strpos(
946 21
            $this->str,
947 21
            $needle,
948 21
            $offset,
949 21
            $this->encoding
950
        );
951
    }
952
953
    /**
954
     * Returns the index of the first occurrence of $needle in the string,
955
     * and false if not found. Accepts an optional offset from which to begin
956
     * the search.
957
     *
958
     * @param string $needle <p>Substring to look for.</p>
959
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
960
     *
961
     * @return false|int
962
     *                   <p>The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
963
     */
964 10
    public function indexOfIgnoreCase(string $needle, int $offset = 0)
965
    {
966 10
        return $this->utf8::stripos(
967 10
            $this->str,
968 10
            $needle,
969 10
            $offset,
970 10
            $this->encoding
971
        );
972
    }
973
974
    /**
975
     * Returns the index of the last occurrence of $needle in the string,
976
     * and false if not found. Accepts an optional offset from which to begin
977
     * the search. Offsets may be negative to count from the last character
978
     * in the string.
979
     *
980
     * @param string $needle <p>Substring to look for.</p>
981
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
982
     *
983
     * @return false|int
984
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
985
     */
986 21
    public function indexOfLast(string $needle, int $offset = 0)
987
    {
988 21
        return $this->utf8::strrpos(
989 21
            $this->str,
990 21
            $needle,
991 21
            $offset,
992 21
            $this->encoding
993
        );
994
    }
995
996
    /**
997
     * Returns the index of the last occurrence of $needle in the string,
998
     * and false if not found. Accepts an optional offset from which to begin
999
     * the search. Offsets may be negative to count from the last character
1000
     * in the string.
1001
     *
1002
     * @param string $needle <p>Substring to look for.</p>
1003
     * @param int    $offset [optional] <p>Offset from which to search. Default: 0</p>
1004
     *
1005
     * @return false|int
1006
     *                   <p>The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.</p>
1007
     */
1008 10
    public function indexOfLastIgnoreCase(string $needle, int $offset = 0)
1009
    {
1010 10
        return $this->utf8::strripos(
1011 10
            $this->str,
1012 10
            $needle,
1013 10
            $offset,
1014 10
            $this->encoding
1015
        );
1016
    }
1017
1018
    /**
1019
     * Inserts $substring into the string at the $index provided.
1020
     *
1021
     * @param string $substring <p>String to be inserted.</p>
1022
     * @param int    $index     <p>The index at which to insert the substring.</p>
1023
     *
1024
     * @return static
1025
     *                <p>Object with the resulting $str after the insertion.</p>
1026
     */
1027 16
    public function insert(string $substring, int $index): self
1028
    {
1029 16
        return static::create(
1030 16
            $this->utf8::str_insert(
1031 16
                $this->str,
1032 16
                $substring,
1033 16
                $index,
1034 16
                $this->encoding
1035
            ),
1036 16
            $this->encoding
1037
        );
1038
    }
1039
1040
    /**
1041
     * Returns true if the string contains the $pattern, otherwise false.
1042
     *
1043
     * WARNING: Asterisks ("*") are translated into (".*") zero-or-more regular
1044
     * expression wildcards.
1045
     *
1046
     * @credit Originally from Laravel, thanks Taylor.
1047
     *
1048
     * @param string $pattern <p>The string or pattern to match against.</p>
1049
     *
1050
     * @return bool
1051
     *              <p>Whether or not we match the provided pattern.</p>
1052
     */
1053 13
    public function is(string $pattern): bool
1054
    {
1055 13
        if ($this->toString() === $pattern) {
1056 1
            return true;
1057
        }
1058
1059 12
        $quotedPattern = \preg_quote($pattern, '/');
1060 12
        $replaceWildCards = \str_replace('\*', '.*', $quotedPattern);
1061
1062 12
        return $this->matchesPattern('^' . $replaceWildCards . '\z');
1063
    }
1064
1065
    /**
1066
     * Returns true if the string contains only alphabetic chars, false otherwise.
1067
     *
1068
     * @return bool
1069
     *              <p>Whether or not $str contains only alphabetic chars.</p>
1070
     */
1071 20
    public function isAlpha(): bool
1072
    {
1073 20
        return $this->utf8::is_alpha($this->str);
1074
    }
1075
1076
    /**
1077
     * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
1078
     *
1079
     * @return bool
1080
     *              <p>Whether or not $str contains only alphanumeric chars.</p>
1081
     */
1082 26
    public function isAlphanumeric(): bool
1083
    {
1084 26
        return $this->utf8::is_alphanumeric($this->str);
1085
    }
1086
1087
    /**
1088
     * Returns true if the string is base64 encoded, false otherwise.
1089
     *
1090
     * @param bool $emptyStringIsValid
1091
     *
1092
     * @return bool
1093
     *              <p>Whether or not $str is base64 encoded.</p>
1094
     */
1095 14
    public function isBase64($emptyStringIsValid = true): bool
1096
    {
1097 14
        return $this->utf8::is_base64($this->str, $emptyStringIsValid);
1098
    }
1099
1100
    /**
1101
     * Returns true if the string contains only whitespace chars, false otherwise.
1102
     *
1103
     * @return bool
1104
     *              <p>Whether or not $str contains only whitespace characters.</p>
1105
     */
1106 30
    public function isBlank(): bool
1107
    {
1108 30
        return $this->utf8::is_blank($this->str);
1109
    }
1110
1111
    /**
1112
     * Returns true if the string contains a valid E-Mail address, false otherwise.
1113
     *
1114
     * @param bool $useExampleDomainCheck   [optional] <p>Default: false</p>
1115
     * @param bool $useTypoInDomainCheck    [optional] <p>Default: false</p>
1116
     * @param bool $useTemporaryDomainCheck [optional] <p>Default: false</p>
1117
     * @param bool $useDnsCheck             [optional] <p>Default: false</p>
1118
     *
1119
     * @return bool
1120
     *              <p>Whether or not $str contains a valid E-Mail address.</p>
1121
     */
1122 1
    public function isEmail(bool $useExampleDomainCheck = false, bool $useTypoInDomainCheck = false, bool $useTemporaryDomainCheck = false, bool $useDnsCheck = false): bool
1123
    {
1124 1
        return EmailCheck::isValid($this->str, $useExampleDomainCheck, $useTypoInDomainCheck, $useTemporaryDomainCheck, $useDnsCheck);
1125
    }
1126
1127
    /**
1128
     * Determine whether the string is considered to be empty.
1129
     *
1130
     * A variable is considered empty if it does not exist or if its value equals FALSE.
1131
     *
1132
     * @return bool
1133
     *              <p>Whether or not $str is empty().</p>
1134
     */
1135 5
    public function isEmpty(): bool
1136
    {
1137 5
        return $this->utf8::is_empty($this->str);
1138
    }
1139
1140
    /**
1141
     * Determine whether the string is considered to be NOT empty.
1142
     *
1143
     * A variable is considered NOT empty if it does exist or if its value equals TRUE.
1144
     *
1145
     * @return bool
1146
     *              <p>Whether or not $str is empty().</p>
1147
     */
1148 5
    public function isNotEmpty(): bool
1149
    {
1150 5
        return !$this->utf8::is_empty($this->str);
1151
    }
1152
1153
    /**
1154
     * Determine whether the string is equals to $str.
1155
     *
1156
     * @param string ...$str <p>The string to compare.</p>
1157
     *
1158
     * @return bool
1159
     *              <p>Whether or not $str is equals.</p>
1160
     *
1161
     * @noinspection PhpDocSignatureInspection
1162
     */
1163 7
    public function isEquals(string ...$str): bool
1164
    {
1165 7
        foreach ($str as $strTmp) {
1166 7
            if ($this->str !== $strTmp) {
1167 7
                return false;
1168
            }
1169
        }
1170
1171 1
        return true;
1172
    }
1173
1174
    /**
1175
     * Returns true if the string contains only hexadecimal chars, false otherwise.
1176
     *
1177
     * @return bool
1178
     *              <p>Whether or not $str contains only hexadecimal chars.</p>
1179
     */
1180 26
    public function isHexadecimal(): bool
1181
    {
1182 26
        return $this->utf8::is_hexadecimal($this->str);
1183
    }
1184
1185
    /**
1186
     * Returns true if the string contains HTML-Tags, false otherwise.
1187
     *
1188
     * @return bool
1189
     *              <p>Whether or not $str contains HTML-Tags.</p>
1190
     */
1191 1
    public function isHtml(): bool
1192
    {
1193 1
        return $this->utf8::is_html($this->str);
1194
    }
1195
1196
    /**
1197
     * Returns true if the string is JSON, false otherwise. Unlike json_decode
1198
     * in PHP 5.x, this method is consistent with PHP 7 and other JSON parsers,
1199
     * in that an empty string is not considered valid JSON.
1200
     *
1201
     * @param bool $onlyArrayOrObjectResultsAreValid
1202
     *
1203
     * @return bool
1204
     *              <p>Whether or not $str is JSON.</p>
1205
     */
1206 40
    public function isJson($onlyArrayOrObjectResultsAreValid = false): bool
1207
    {
1208 40
        return $this->utf8::is_json($this->str, $onlyArrayOrObjectResultsAreValid);
1209
    }
1210
1211
    /**
1212
     * Returns true if the string contains only lower case chars, false otherwise.
1213
     *
1214
     * @return bool
1215
     *              <p>Whether or not $str contains only lower case characters.</p>
1216
     */
1217 16
    public function isLowerCase(): bool
1218
    {
1219 16
        return $this->utf8::is_lowercase($this->str);
1220
    }
1221
1222
    /**
1223
     * Returns true if the string is serialized, false otherwise.
1224
     *
1225
     * @return bool
1226
     *              <p>Whether or not $str is serialized.</p>
1227
     */
1228 14
    public function isSerialized(): bool
1229
    {
1230 14
        return $this->utf8::is_serialized($this->str);
1231
    }
1232
1233
    /**
1234
     * Returns true if the string contains only lower case chars, false
1235
     * otherwise.
1236
     *
1237
     * @return bool
1238
     *              <p>Whether or not $str contains only lower case characters.</p>
1239
     */
1240 16
    public function isUpperCase(): bool
1241
    {
1242 16
        return $this->utf8::is_uppercase($this->str);
1243
    }
1244
1245
    /**
1246
     * Returns the last $n characters of the string.
1247
     *
1248
     * @param int $n <p>Number of characters to retrieve from the end.</p>
1249
     *
1250
     * @return static
1251
     *                <p>Object with its $str being the last $n chars.</p>
1252
     */
1253 24
    public function last(int $n): self
1254
    {
1255 24
        return static::create(
1256 24
            $this->utf8::str_last_char(
1257 24
                $this->str,
1258 24
                $n,
1259 24
                $this->encoding
1260
            ),
1261 24
            $this->encoding
1262
        );
1263
    }
1264
1265
    /**
1266
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
1267
     * If no match is found returns new empty Stringy object.
1268
     *
1269
     * @param string $needle       <p>The string to look for.</p>
1270
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
1271
     *
1272
     * @return static
1273
     */
1274 2 View Code Duplication
    public function lastSubstringOf(string $needle, bool $beforeNeedle = false): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1275
    {
1276 2
        return static::create(
1277 2
            $this->utf8::str_substr_last(
1278 2
                $this->str,
1279 2
                $needle,
1280 2
                $beforeNeedle,
1281 2
                $this->encoding
1282
            ),
1283 2
            $this->encoding
1284
        );
1285
    }
1286
1287
    /**
1288
     * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
1289
     * If no match is found returns new empty Stringy object.
1290
     *
1291
     * @param string $needle       <p>The string to look for.</p>
1292
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
1293
     *
1294
     * @return static
1295
     */
1296 1 View Code Duplication
    public function lastSubstringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1297
    {
1298 1
        return static::create(
1299 1
            $this->utf8::str_isubstr_last(
1300 1
                $this->str,
1301 1
                $needle,
1302 1
                $beforeNeedle,
1303 1
                $this->encoding
1304
            ),
1305 1
            $this->encoding
1306
        );
1307
    }
1308
1309
    /**
1310
     * Returns the length of the string.
1311
     *
1312
     * @return int
1313
     *             <p>The number of characters in $str given the encoding.</p>
1314
     */
1315 11
    public function length(): int
1316
    {
1317 11
        return (int) $this->utf8::strlen($this->str, $this->encoding);
1318
    }
1319
1320
    /**
1321
     * Line-Wrap the string after $limit, but also after the next word.
1322
     *
1323
     * @param int $limit
1324
     *
1325
     * @return static
1326
     */
1327 1
    public function lineWrapAfterWord(int $limit): self
1328
    {
1329 1
        return static::create(
1330 1
            $this->utf8::wordwrap_per_line($this->str, $limit),
1331 1
            $this->encoding
1332
        );
1333
    }
1334
1335
    /**
1336
     * Splits on newlines and carriage returns, returning an array of Stringy
1337
     * objects corresponding to the lines in the string.
1338
     *
1339
     * @return CollectionStringy|static[]
1340
     *                                    <p>An collection of Stringy objects.</p>
1341
     */
1342 34
    public function lines(): CollectionStringy
1343
    {
1344 34
        $array = $this->utf8::str_to_lines($this->str);
1345 34
        foreach ($array as $i => &$value) {
1346 34
            $value = static::create($value, $this->encoding);
1347
        }
1348
1349 34
        return CollectionStringy::create($array);
1350
    }
1351
1352
    /**
1353
     * Returns the longest common prefix between the string and $otherStr.
1354
     *
1355
     * @param string $otherStr <p>Second string for comparison.</p>
1356
     *
1357
     * @return static
1358
     *                <p>Object with its $str being the longest common prefix.</p>
1359
     */
1360 20
    public function longestCommonPrefix(string $otherStr): self
1361
    {
1362 20
        return static::create(
1363 20
            $this->utf8::str_longest_common_prefix(
1364 20
                $this->str,
1365 20
                $otherStr,
1366 20
                $this->encoding
1367
            ),
1368 20
            $this->encoding
1369
        );
1370
    }
1371
1372
    /**
1373
     * Returns the longest common substring between the string and $otherStr.
1374
     * In the case of ties, it returns that which occurs first.
1375
     *
1376
     * @param string $otherStr <p>Second string for comparison.</p>
1377
     *
1378
     * @return static
1379
     *                <p>Object with its $str being the longest common substring.</p>
1380
     */
1381 20
    public function longestCommonSubstring(string $otherStr): self
1382
    {
1383 20
        return static::create(
1384 20
            $this->utf8::str_longest_common_substring(
1385 20
                $this->str,
1386 20
                $otherStr,
1387 20
                $this->encoding
1388
            ),
1389 20
            $this->encoding
1390
        );
1391
    }
1392
1393
    /**
1394
     * Returns the longest common suffix between the string and $otherStr.
1395
     *
1396
     * @param string $otherStr <p>Second string for comparison.</p>
1397
     *
1398
     * @return static
1399
     *                <p>Object with its $str being the longest common suffix.</p>
1400
     */
1401 20
    public function longestCommonSuffix(string $otherStr): self
1402
    {
1403 20
        return static::create(
1404 20
            $this->utf8::str_longest_common_suffix(
1405 20
                $this->str,
1406 20
                $otherStr,
1407 20
                $this->encoding
1408
            ),
1409 20
            $this->encoding
1410
        );
1411
    }
1412
1413
    /**
1414
     * Converts the first character of the string to lower case.
1415
     *
1416
     * @return static
1417
     *                <p>Object with the first character of $str being lower case.</p>
1418
     */
1419 10
    public function lowerCaseFirst(): self
1420
    {
1421 10
        return static::create(
1422 10
            $this->utf8::lcfirst($this->str, $this->encoding),
1423 10
            $this->encoding
1424
        );
1425
    }
1426
1427
    /**
1428
     * Returns whether or not a character exists at an index. Offsets may be
1429
     * negative to count from the last character in the string. Implements
1430
     * part of the ArrayAccess interface.
1431
     *
1432
     * @param int $offset <p>The index to check.</p>
1433
     *
1434
     * @return bool
1435
     *              <p>Whether or not the index exists.</p>
1436
     */
1437 12
    public function offsetExists($offset): bool
1438
    {
1439 12
        return $this->utf8::str_offset_exists(
1440 12
            $this->str,
1441 12
            $offset,
1442 12
            $this->encoding
1443
        );
1444
    }
1445
1446
    /**
1447
     * Returns the character at the given index. Offsets may be negative to
1448
     * count from the last character in the string. Implements part of the
1449
     * ArrayAccess interface, and throws an OutOfBoundsException if the index
1450
     * does not exist.
1451
     *
1452
     * @param int $offset <p>The <strong>index</strong> from which to retrieve the char.</p>
1453
     *
1454
     * @throws \OutOfBoundsException
1455
     *                               <p>If the positive or negative offset does not exist.</p>
1456
     *
1457
     * @return string
1458
     *                <p>The character at the specified index.</p>
1459
     */
1460 4
    public function offsetGet($offset): string
1461
    {
1462 4
        return $this->utf8::str_offset_get($this->str, $offset, $this->encoding);
1463
    }
1464
1465
    /**
1466
     * Implements part of the ArrayAccess interface, but throws an exception
1467
     * when called. This maintains the immutability of Stringy objects.
1468
     *
1469
     * @param int   $offset <p>The index of the character.</p>
1470
     * @param mixed $value  <p>Value to set.</p>
1471
     *
1472
     * @throws \Exception
1473
     *                    <p>When called.</p>
1474
     */
1475 2
    public function offsetSet($offset, $value)
1476
    {
1477
        // Stringy is immutable, cannot directly set char
1478
        /** @noinspection ThrowRawExceptionInspection */
1479 2
        throw new \Exception('Stringy object is immutable, cannot modify char');
1480
    }
1481
1482
    /**
1483
     * Implements part of the ArrayAccess interface, but throws an exception
1484
     * when called. This maintains the immutability of Stringy objects.
1485
     *
1486
     * @param int $offset <p>The index of the character.</p>
1487
     *
1488
     * @throws \Exception
1489
     *                    <p>When called.</p>
1490
     */
1491 2
    public function offsetUnset($offset)
1492
    {
1493
        // Don't allow directly modifying the string
1494
        /** @noinspection ThrowRawExceptionInspection */
1495 2
        throw new \Exception('Stringy object is immutable, cannot unset char');
1496
    }
1497
1498
    /**
1499
     * Pads the string to a given length with $padStr. If length is less than
1500
     * or equal to the length of the string, no padding takes places. The
1501
     * default string used for padding is a space, and the default type (one of
1502
     * 'left', 'right', 'both') is 'right'. Throws an InvalidArgumentException
1503
     * if $padType isn't one of those 3 values.
1504
     *
1505
     * @param int    $length  <p>Desired string length after padding.</p>
1506
     * @param string $padStr  [optional] <p>String used to pad, defaults to space. Default: ' '</p>
1507
     * @param string $padType [optional] <p>One of 'left', 'right', 'both'. Default: 'right'</p>
1508
     *
1509
     * @throws \InvalidArgumentException
1510
     *                                   <p>If $padType isn't one of 'right', 'left' or 'both'.</p>
1511
     *
1512
     * @return static
1513
     *                <p>Object with a padded $str.</p>
1514
     */
1515 26
    public function pad(int $length, string $padStr = ' ', string $padType = 'right'): self
1516
    {
1517 26
        return static::create(
1518 26
            $this->utf8::str_pad(
1519 26
                $this->str,
1520 26
                $length,
1521 26
                $padStr,
1522 26
                $padType,
1523 26
                $this->encoding
1524
            )
1525
        );
1526
    }
1527
1528
    /**
1529
     * Returns a new string of a given length such that both sides of the
1530
     * string are padded. Alias for pad() with a $padType of 'both'.
1531
     *
1532
     * @param int    $length <p>Desired string length after padding.</p>
1533
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
1534
     *
1535
     * @return static
1536
     *                <p>String with padding applied.</p>
1537
     */
1538 22
    public function padBoth(int $length, string $padStr = ' '): self
1539
    {
1540 22
        return static::create(
1541 22
            $this->utf8::str_pad_both(
1542 22
                $this->str,
1543 22
                $length,
1544 22
                $padStr,
1545 22
                $this->encoding
1546
            )
1547
        );
1548
    }
1549
1550
    /**
1551
     * Returns a new string of a given length such that the beginning of the
1552
     * string is padded. Alias for pad() with a $padType of 'left'.
1553
     *
1554
     * @param int    $length <p>Desired string length after padding.</p>
1555
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
1556
     *
1557
     * @return static
1558
     *                <p>String with left padding.</p>
1559
     */
1560 14
    public function padLeft(int $length, string $padStr = ' '): self
1561
    {
1562 14
        return static::create(
1563 14
            $this->utf8::str_pad_left(
1564 14
                $this->str,
1565 14
                $length,
1566 14
                $padStr,
1567 14
                $this->encoding
1568
            )
1569
        );
1570
    }
1571
1572
    /**
1573
     * Returns a new string of a given length such that the end of the string
1574
     * is padded. Alias for pad() with a $padType of 'right'.
1575
     *
1576
     * @param int    $length <p>Desired string length after padding.</p>
1577
     * @param string $padStr [optional] <p>String used to pad, defaults to space. Default: ' '</p>
1578
     *
1579
     * @return static
1580
     *                <p>String with right padding.</p>
1581
     */
1582 14
    public function padRight(int $length, string $padStr = ' '): self
1583
    {
1584 14
        return static::create(
1585 14
            $this->utf8::str_pad_right(
1586 14
                $this->str,
1587 14
                $length,
1588 14
                $padStr,
1589 14
                $this->encoding
1590
            )
1591
        );
1592
    }
1593
1594
    /**
1595
     * Returns a new string starting with $string.
1596
     *
1597
     * @param string ...$prefix <p>The string to append.</p>
1598
     *
1599
     * @return static
1600
     *                <p>Object with appended $string.</p>
1601
     *
1602
     * @noinspection PhpDocSignatureInspection
1603
     */
1604 4 View Code Duplication
    public function prepend(string ...$prefix): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1605
    {
1606 4
        if (\count($prefix) <= 1) {
1607
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
1608 4
            $prefix = $prefix[0];
1609
        } else {
1610
            /** @noinspection CallableParameterUseCaseInTypeContextInspection */
1611
            $prefix = \implode('', ...$prefix);
1612
        }
1613
1614 4
        return static::create($prefix . $this->str, $this->encoding);
1615
    }
1616
1617
    /**
1618
     * Replaces all occurrences of $pattern in $str by $replacement.
1619
     *
1620
     * @param string $pattern     <p>The regular expression pattern.</p>
1621
     * @param string $replacement <p>The string to replace with.</p>
1622
     * @param string $options     [optional] <p>Matching conditions to be used.</p>
1623
     * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
1624
     *
1625
     * @return static
1626
     *                <p>Object with the result2ing $str after the replacements.</p>
1627
     */
1628 19
    public function regexReplace(string $pattern, string $replacement, string $options = '', string $delimiter = '/'): self
1629
    {
1630 19
        return static::create(
1631 19
            $this->utf8::regex_replace(
1632 19
                $this->str,
1633 19
                $pattern,
1634 19
                $replacement,
1635 19
                $options,
1636 19
                $delimiter
1637
            ),
1638 19
            $this->encoding
1639
        );
1640
    }
1641
1642
    /**
1643
     * Remove html via "strip_tags()" from the string.
1644
     *
1645
     * @param string $allowableTags [optional] <p>You can use the optional second parameter to specify tags which should
1646
     *                              not be stripped. Default: null
1647
     *                              </p>
1648
     *
1649
     * @return static
1650
     */
1651 6
    public function removeHtml(string $allowableTags = ''): self
1652
    {
1653 6
        return static::create(
1654 6
            $this->utf8::remove_html($this->str, $allowableTags),
1655 6
            $this->encoding
1656
        );
1657
    }
1658
1659
    /**
1660
     * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
1661
     *
1662
     * @param string $replacement [optional] <p>Default is a empty string.</p>
1663
     *
1664
     * @return static
1665
     */
1666 6
    public function removeHtmlBreak(string $replacement = ''): self
1667
    {
1668 6
        return static::create(
1669 6
            $this->utf8::remove_html_breaks($this->str, $replacement),
1670 6
            $this->encoding
1671
        );
1672
    }
1673
1674
    /**
1675
     * Returns a new string with the prefix $substring removed, if present.
1676
     *
1677
     * @param string $substring <p>The prefix to remove.</p>
1678
     *
1679
     * @return static
1680
     *                <p>Object having a $str without the prefix $substring.</p>
1681
     */
1682 24
    public function removeLeft(string $substring): self
1683
    {
1684 24
        return static::create(
1685 24
            $this->utf8::remove_left($this->str, $substring, $this->encoding),
1686 24
            $this->encoding
1687
        );
1688
    }
1689
1690
    /**
1691
     * Returns a new string with the suffix $substring removed, if present.
1692
     *
1693
     * @param string $substring <p>The suffix to remove.</p>
1694
     *
1695
     * @return static
1696
     *                <p>Object having a $str without the suffix $substring.</p>
1697
     */
1698 24
    public function removeRight(string $substring): self
1699
    {
1700 24
        return static::create(
1701 24
            $this->utf8::remove_right($this->str, $substring, $this->encoding),
1702 24
            $this->encoding
1703
        );
1704
    }
1705
1706
    /**
1707
     * Try to remove all XSS-attacks from the string.
1708
     *
1709
     * @return static
1710
     */
1711 6
    public function removeXss(): self
1712
    {
1713 6
        static $antiXss = null;
1714
1715 6
        if ($antiXss === null) {
1716 1
            $antiXss = new AntiXSS();
1717
        }
1718
1719 6
        $str = $antiXss->xss_clean($this->str);
1720
1721 6
        return static::create($str, $this->encoding);
1722
    }
1723
1724
    /**
1725
     * Returns a repeated string given a multiplier.
1726
     *
1727
     * @param int $multiplier <p>The number of times to repeat the string.</p>
1728
     *
1729
     * @return static
1730
     *                <p>Object with a repeated str.</p>
1731
     */
1732 14
    public function repeat(int $multiplier): self
1733
    {
1734 14
        return static::create(
1735 14
            \str_repeat($this->str, $multiplier),
1736 14
            $this->encoding
1737
        );
1738
    }
1739
1740
    /**
1741
     * Replaces all occurrences of $search in $str by $replacement.
1742
     *
1743
     * @param string $search        <p>The needle to search for.</p>
1744
     * @param string $replacement   <p>The string to replace with.</p>
1745
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1746
     *
1747
     * @return static
1748
     *                <p>Object with the resulting $str after the replacements.</p>
1749
     */
1750 45
    public function replace(string $search, string $replacement, bool $caseSensitive = true): self
1751
    {
1752 45
        if ($search === '' && $replacement === '') {
1753 10
            return static::create($this->str, $this->encoding);
1754
        }
1755
1756 35
        if ($this->str === '' && $search === '') {
1757 2
            return static::create($replacement, $this->encoding);
1758
        }
1759
1760 33
        if ($caseSensitive) {
1761 28
            return static::create(
1762 28
                $this->utf8::str_replace($search, $replacement, $this->str),
1763 28
                $this->encoding
1764
            );
1765
        }
1766
1767 5
        return static::create(
1768 5
            $this->utf8::str_ireplace($search, $replacement, $this->str),
1769 5
            $this->encoding
1770
        );
1771
    }
1772
1773
    /**
1774
     * Replaces all occurrences of $search in $str by $replacement.
1775
     *
1776
     * @param array        $search        <p>The elements to search for.</p>
1777
     * @param array|string $replacement   <p>The string to replace with.</p>
1778
     * @param bool         $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
1779
     *
1780
     * @return static
1781
     *                <p>Object with the resulting $str after the replacements.</p>
1782
     */
1783 30
    public function replaceAll(array $search, $replacement, bool $caseSensitive = true): self
1784
    {
1785 30
        if ($caseSensitive) {
1786 23
            return static::create(
1787 23
                $this->utf8::str_replace($search, $replacement, $this->str),
1788 23
                $this->encoding
1789
            );
1790
        }
1791
1792 7
        return static::create(
1793 7
            $this->utf8::str_ireplace($search, $replacement, $this->str),
1794 7
            $this->encoding
1795
        );
1796
    }
1797
1798
    /**
1799
     * Replaces first occurrences of $search from the beginning of string with $replacement.
1800
     *
1801
     * @param string $search      <p>The string to search for.</p>
1802
     * @param string $replacement <p>The replacement.</p>
1803
     *
1804
     * @return static
1805
     *                <p>Object with the resulting $str after the replacements.</p>
1806
     */
1807 16
    public function replaceFirst(string $search, string $replacement): self
1808
    {
1809 16
        return static::create(
1810 16
            $this->utf8::str_replace_first($search, $replacement, $this->str),
1811 16
            $this->encoding
1812
        );
1813
    }
1814
1815
    /**
1816
     * Replaces last occurrences of $search from the ending of string with $replacement.
1817
     *
1818
     * @param string $search      <p>The string to search for.</p>
1819
     * @param string $replacement <p>The replacement.</p>
1820
     *
1821
     * @return static
1822
     *                <p>Object with the resulting $str after the replacements.</p>
1823
     */
1824 15
    public function replaceLast(string $search, string $replacement): self
1825
    {
1826 15
        return static::create(
1827 15
            $this->utf8::str_replace_last($search, $replacement, $this->str),
1828 15
            $this->encoding
1829
        );
1830
    }
1831
1832
    /**
1833
     * Replaces all occurrences of $search from the beginning of string with $replacement.
1834
     *
1835
     * @param string $search      <p>The string to search for.</p>
1836
     * @param string $replacement <p>The replacement.</p>
1837
     *
1838
     * @return static
1839
     *                <p>Object with the resulting $str after the replacements.</p>
1840
     */
1841 16
    public function replaceBeginning(string $search, string $replacement): self
1842
    {
1843 16
        return static::create(
1844 16
            $this->utf8::str_replace_beginning($this->str, $search, $replacement),
1845 16
            $this->encoding
1846
        );
1847
    }
1848
1849
    /**
1850
     * Replaces all occurrences of $search from the ending of string with $replacement.
1851
     *
1852
     * @param string $search      <p>The string to search for.</p>
1853
     * @param string $replacement <p>The replacement.</p>
1854
     *
1855
     * @return static
1856
     *                <p>Object with the resulting $str after the replacements.</p>
1857
     */
1858 16
    public function replaceEnding(string $search, string $replacement): self
1859
    {
1860 16
        return static::create(
1861 16
            $this->utf8::str_replace_ending($this->str, $search, $replacement),
1862 16
            $this->encoding
1863
        );
1864
    }
1865
1866
    /**
1867
     * Returns a reversed string. A multibyte version of strrev().
1868
     *
1869
     * @return static
1870
     *                <p>Object with a reversed $str.</p>
1871
     */
1872 10
    public function reverse(): self
1873
    {
1874 10
        return static::create($this->utf8::strrev($this->str), $this->encoding);
1875
    }
1876
1877
    /**
1878
     * Truncates the string to a given length, while ensuring that it does not
1879
     * split words. If $substring is provided, and truncating occurs, the
1880
     * string is further truncated so that the substring may be appended without
1881
     * exceeding the desired length.
1882
     *
1883
     * @param int    $length                          <p>Desired length of the truncated string.</p>
1884
     * @param string $substring                       [optional] <p>The substring to append if it can fit. Default: ''</p>
1885
     * @param bool   $ignoreDoNotSplitWordsForOneWord
1886
     *
1887
     * @return static
1888
     *                <p>Object with the resulting $str after truncating.</p>
1889
     */
1890 45
    public function safeTruncate(int $length, string $substring = '', bool $ignoreDoNotSplitWordsForOneWord = true): self
1891
    {
1892 45
        return static::create(
1893 45
            $this->utf8::str_truncate_safe(
1894 45
                $this->str,
1895 45
                $length,
1896 45
                $substring,
1897 45
                $this->encoding,
1898 45
                $ignoreDoNotSplitWordsForOneWord
1899
            ),
1900 45
            $this->encoding
1901
        );
1902
    }
1903
1904
    /**
1905
     * Shorten the string after $length, but also after the next word.
1906
     *
1907
     * @param int    $length
1908
     * @param string $strAddOn [optional] <p>Default: '…'</p>
1909
     *
1910
     * @return static
1911
     */
1912 4
    public function shortenAfterWord(int $length, string $strAddOn = '…'): self
1913
    {
1914 4
        return static::create(
1915 4
            $this->utf8::str_limit_after_word($this->str, $length, $strAddOn),
1916 4
            $this->encoding
1917
        );
1918
    }
1919
1920
    /**
1921
     * A multibyte string shuffle function. It returns a string with its
1922
     * characters in random order.
1923
     *
1924
     * @return static
1925
     *                <p>Object with a shuffled $str.</p>
1926
     */
1927 6
    public function shuffle(): self
1928
    {
1929 6
        return static::create($this->utf8::str_shuffle($this->str), $this->encoding);
1930
    }
1931
1932
    /**
1933
     * Returns the substring beginning at $start, and up to, but not including
1934
     * the index specified by $end. If $end is omitted, the function extracts
1935
     * the remaining string. If $end is negative, it is computed from the end
1936
     * of the string.
1937
     *
1938
     * @param int $start <p>Initial index from which to begin extraction.</p>
1939
     * @param int $end   [optional] <p>Index at which to end extraction. Default: null</p>
1940
     *
1941
     * @return static
1942
     *                <p>Object with its $str being the extracted substring.</p>
1943
     */
1944 34
    public function slice(int $start, int $end = null): self
1945
    {
1946 34
        return static::create(
1947 34
            $this->utf8::str_slice($this->str, $start, $end, $this->encoding),
1948 34
            $this->encoding
1949
        );
1950
    }
1951
1952
    /**
1953
     * Converts the string into an URL slug. This includes replacing non-ASCII
1954
     * characters with their closest ASCII equivalents, removing remaining
1955
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
1956
     * $separator. The separator defaults to a single dash, and the string
1957
     * is also converted to lowercase. The language of the source string can
1958
     * also be supplied for language-specific transliteration.
1959
     *
1960
     * @param string                $separator             [optional] <p>The string used to replace whitespace.</p>
1961
     * @param string                $language              [optional] <p>Language of the source string.</p>
1962
     * @param array<string, string> $replacements          [optional] <p>A map of replaceable strings.</p>
1963
     * @param bool                  $replace_extra_symbols [optional]  <p>Add some more replacements e.g. "£" with "
1964
     *                                                     pound ".</p>
1965
     * @param bool                  $use_str_to_lower      [optional] <p>Use "string to lower" for the input.</p>
1966
     * @param bool                  $use_transliterate     [optional]  <p>Use ASCII::to_transliterate() for unknown
1967
     *                                                     chars.</p>
1968
     *
1969
     * @return static
1970
     *                <p>Object whose $str has been converted to an URL slug.</p>
1971
     */
1972 17
    public function slugify(
1973
        string $separator = '-',
1974
        string $language = 'en',
1975
        array $replacements = [],
1976
        bool $replace_extra_symbols = true,
1977
        bool $use_str_to_lower = true,
1978
        bool $use_transliterate = false
1979
    ): self {
1980 17
        return static::create(
1981 17
            $this->ascii::to_slugify(
1982 17
                $this->str,
1983 17
                $separator,
1984 17
                $language,
1985 17
                $replacements,
1986 17
                $replace_extra_symbols,
1987 17
                $use_str_to_lower,
1988 17
                $use_transliterate
1989
            ),
1990 17
            $this->encoding
1991
        );
1992
    }
1993
1994
    /**
1995
     * Converts the string into an URL slug. This includes replacing non-ASCII
1996
     * characters with their closest ASCII equivalents, removing remaining
1997
     * non-ASCII and non-alphanumeric characters, and replacing whitespace with
1998
     * $separator. The separator defaults to a single dash, and the string
1999
     * is also converted to lowercase.
2000
     *
2001
     * @param string                $separator    [optional] <p>The string used to replace whitespace. Default: '-'</p>
2002
     * @param string                $language     [optional] <p>The language for the url. Default: 'en'</p>
2003
     * @param array<string, string> $replacements [optional] <p>A map of replaceable strings.</p>
2004
     * @param bool                  $strToLower   [optional] <p>string to lower. Default: true</p>
2005
     *
2006
     * @return static
2007
     *                <p>Object whose $str has been converted to an URL slug.</p>
2008
     */
2009 16
    public function urlify(
2010
        string $separator = '-',
2011
        string $language = 'en',
2012
        array $replacements = [],
2013
        bool $strToLower = true
2014
    ): self {
2015
        // init
2016 16
        $str = $this->str;
2017
2018 16
        foreach ($replacements as $from => $to) {
2019 16
            $str = \str_replace($from, $to, $str);
2020
        }
2021
2022 16
        return static::create(
2023 16
            URLify::slug(
2024 16
                $str,
2025 16
                $language,
2026 16
                $separator,
2027 16
                $strToLower
2028
            ),
2029 16
            $this->encoding
2030
        );
2031
    }
2032
2033
    /**
2034
     * Convert a string to e.g.: "snake_case"
2035
     *
2036
     * @return static
2037
     *                <p>Object with $str in snake_case.</p>
2038
     */
2039 20
    public function snakeize(): self
2040
    {
2041 20
        return static::create(
2042 20
            $this->utf8::str_snakeize($this->str, $this->encoding),
2043 20
            $this->encoding
2044
        );
2045
    }
2046
2047
    /**
2048
     * Return a formatted string via sprintf + named parameters via array syntax.
2049
     *
2050
     * <p>
2051
     * <br>
2052
     * It will use "sprintf()" so you can use e.g.:
2053
     * <br>
2054
     * <br><pre>s('There are %d monkeys in the %s')->format(5, 'tree');</pre>
2055
     * <br>
2056
     * <br><pre>s('There are %2$d monkeys in the %1$s')->format('tree', 5);</pre>
2057
     * <br>
2058
     * <br>
2059
     * But you can also use named parameter via array syntax e.g.:
2060
     * <br>
2061
     * <br><pre>s('There are %:count monkeys in the %:location')->format(['count' => 5, 'location' => 'tree');</pre>
2062
     * </p>
2063
     *
2064
     * @param mixed ...$args [optional]
2065
     *
2066
     * @return static
2067
     *                <p>A Stringy object produced according to the formatting string
2068
     *                format.</p>
2069
     */
2070 5
    public function format(...$args): self
2071
    {
2072
        // init
2073 5
        $str = $this->str;
2074
2075 5
        if (\strpos($this->str, '%:') !== false) {
2076 4
            $offset = null;
2077 4
            $replacement = null;
2078
            /** @noinspection AlterInForeachInspection */
2079 4
            foreach ($args as $key => &$arg) {
2080 4
                if (!\is_array($arg)) {
2081 2
                    continue;
2082
                }
2083
2084 4
                foreach ($arg as $name => $param) {
2085 4
                    $name = (string) $name;
2086
2087 4
                    if (\strpos($name, '%:') !== 0) {
2088 4
                        $nameTmp = '%:' . $name;
2089
                    } else {
2090
                        $nameTmp = $name;
2091
                    }
2092
2093 4
                    if ($offset === null) {
2094 4
                        $offset = \strpos($str, $nameTmp);
2095
                    } else {
2096 3
                        $offset = \strpos($str, $nameTmp, $offset + \strlen((string) $replacement));
2097
                    }
2098 4
                    if ($offset === false) {
2099 2
                        continue;
2100
                    }
2101
2102 4
                    unset($arg[$name]);
2103
2104 4
                    $str = \substr_replace($str, $param, $offset, \strlen($nameTmp));
2105
                }
2106
2107 4
                unset($args[$key]);
2108
            }
2109
        }
2110
2111 5
        $str = \str_replace('%:', '%%:', $str);
2112
2113 5
        return static::create(
2114 5
            \sprintf($str, ...$args),
2115 5
            $this->encoding
2116
        );
2117
    }
2118
2119
    /**
2120
     * Splits the string into chunks of Stringy objects.
2121
     *
2122
     * @param int $length
2123
     *
2124
     * @return CollectionStringy|static[]
2125
     *                                    <p>An collection of Stringy objects.</p>
2126
     */
2127 5
    public function chunk(int $length = 1): CollectionStringy
2128
    {
2129 5
        if ($length < 1) {
2130
            throw new \InvalidArgumentException('The chunk length must be greater than zero.');
2131
        }
2132
2133 5
        if ($this->str === '') {
2134 1
            return CollectionStringy::create();
2135
        }
2136
2137 4
        $chunks = $this->utf8::str_split($this->str, $length);
2138 4
        foreach ($chunks as $i => &$value) {
2139 4
            $value = static::create($value, $this->encoding);
2140
        }
2141
2142 4
        return CollectionStringy::create($chunks);
2143
    }
2144
2145
    /**
2146
     * Splits the string with the provided regular expression, returning an
2147
     * array of Stringy objects. An optional integer $limit will truncate the
2148
     * results.
2149
     *
2150
     * @param string $pattern <p>The regex with which to split the string.</p>
2151
     * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
2152
     *
2153
     * @return CollectionStringy|static[]
2154
     *                                    <p>An collection of Stringy objects.</p>
2155
     */
2156 35
    public function split(string $pattern, int $limit = null): CollectionStringy
2157
    {
2158 35
        if ($limit === null) {
2159 7
            $limit = -1;
2160
        }
2161
2162 35
        $array = $this->utf8::str_split_pattern($this->str, $pattern, $limit);
2163 35
        foreach ($array as $i => &$value) {
2164 31
            $value = static::create($value, $this->encoding);
2165
        }
2166
2167 35
        return CollectionStringy::create($array);
2168
    }
2169
2170
    /**
2171
     * Returns true if the string begins with $substring, false otherwise. By
2172
     * default, the comparison is case-sensitive, but can be made insensitive
2173
     * by setting $caseSensitive to false.
2174
     *
2175
     * @param string $substring     <p>The substring to look for.</p>
2176
     * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
2177
     *
2178
     * @return bool
2179
     *              <p>Whether or not $str starts with $substring.</p>
2180
     */
2181 55
    public function startsWith(string $substring, bool $caseSensitive = true): bool
2182
    {
2183 55
        if ($caseSensitive) {
2184 30
            return $this->utf8::str_starts_with($this->str, $substring);
2185
        }
2186
2187 25
        return $this->utf8::str_istarts_with($this->str, $substring);
2188
    }
2189
2190
    /**
2191
     * Returns true if the string begins with any of $substrings, false otherwise.
2192
     * By default the comparison is case-sensitive, but can be made insensitive by
2193
     * setting $caseSensitive to false.
2194
     *
2195
     * @param array $substrings    <p>Substrings to look for.</p>
2196
     * @param bool  $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
2197
     *
2198
     * @return bool
2199
     *              <p>Whether or not $str starts with $substring.</p>
2200
     */
2201 23
    public function startsWithAny(array $substrings, bool $caseSensitive = true): bool
2202
    {
2203 23
        if ($caseSensitive) {
2204 15
            return $this->utf8::str_starts_with_any($this->str, $substrings);
2205
        }
2206
2207 8
        return $this->utf8::str_istarts_with_any($this->str, $substrings);
2208
    }
2209
2210
    /**
2211
     * Strip all whitespace characters. This includes tabs and newline characters,
2212
     * as well as multibyte whitespace such as the thin space and ideographic space.
2213
     *
2214
     * @return static
2215
     */
2216 24
    public function stripWhitespace(): self
2217
    {
2218 24
        return static::create(
2219 24
            $this->utf8::strip_whitespace($this->str),
2220 24
            $this->encoding
2221
        );
2222
    }
2223
2224
    /**
2225
     * Remove css media-queries.
2226
     *
2227
     * @return static
2228
     */
2229 1
    public function stripeCssMediaQueries(): self
2230
    {
2231 1
        return static::create(
2232 1
            $this->utf8::css_stripe_media_queries($this->str),
2233 1
            $this->encoding
2234
        );
2235
    }
2236
2237
    /**
2238
     * Remove empty html-tag.
2239
     *
2240
     * e.g.: <tag></tag>
2241
     *
2242
     * @return static
2243
     */
2244 1
    public function stripeEmptyHtmlTags(): self
2245
    {
2246 1
        return static::create(
2247 1
            $this->utf8::html_stripe_empty_tags($this->str),
2248 1
            $this->encoding
2249
        );
2250
    }
2251
2252
    /**
2253
     * Returns the substring beginning at $start with the specified $length.
2254
     * It differs from the $this->utf8::substr() function in that providing a $length of
2255
     * null will return the rest of the string, rather than an empty string.
2256
     *
2257
     * @param int $start  <p>Position of the first character to use.</p>
2258
     * @param int $length [optional] <p>Maximum number of characters used. Default: null</p>
2259
     *
2260
     * @return static
2261
     *                <p>Object with its $str being the substring.</p>
2262
     */
2263 18
    public function substr(int $start, int $length = null): self
2264
    {
2265 18
        return static::create(
2266 18
            $this->utf8::substr(
2267 18
                $this->str,
2268 18
                $start,
2269 18
                $length,
2270 18
                $this->encoding
2271
            ),
2272 18
            $this->encoding
2273
        );
2274
    }
2275
2276
    /**
2277
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
2278
     * If no match is found returns new empty Stringy object.
2279
     *
2280
     * @param string $needle       <p>The string to look for.</p>
2281
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2282
     *
2283
     * @return static
2284
     */
2285 2 View Code Duplication
    public function substringOf(string $needle, bool $beforeNeedle = false): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2286
    {
2287 2
        return static::create(
2288 2
            $this->utf8::str_substr_first(
2289 2
                $this->str,
2290 2
                $needle,
2291 2
                $beforeNeedle,
2292 2
                $this->encoding
2293
            ),
2294 2
            $this->encoding
2295
        );
2296
    }
2297
2298
    /**
2299
     * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
2300
     * If no match is found returns new empty Stringy object.
2301
     *
2302
     * @param string $needle       <p>The string to look for.</p>
2303
     * @param bool   $beforeNeedle [optional] <p>Default: false</p>
2304
     *
2305
     * @return static
2306
     */
2307 2 View Code Duplication
    public function substringOfIgnoreCase(string $needle, bool $beforeNeedle = false): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2308
    {
2309 2
        return static::create(
2310 2
            $this->utf8::str_isubstr_first(
2311 2
                $this->str,
2312 2
                $needle,
2313 2
                $beforeNeedle,
2314 2
                $this->encoding
2315
            ),
2316 2
            $this->encoding
2317
        );
2318
    }
2319
2320
    /**
2321
     * Surrounds $str with the given substring.
2322
     *
2323
     * @param string $substring <p>The substring to add to both sides.</P>
2324
     *
2325
     * @return static
2326
     *                <p>Object whose $str had the substring both prepended and appended.</p>
2327
     */
2328 10
    public function surround(string $substring): self
2329
    {
2330 10
        return static::create(
2331 10
            $substring . $this->str . $substring,
2332 10
            $this->encoding
2333
        );
2334
    }
2335
2336
    /**
2337
     * Returns a case swapped version of the string.
2338
     *
2339
     * @return static
2340
     *                <p>Object whose $str has each character's case swapped.</P>
2341
     */
2342 10
    public function swapCase(): self
2343
    {
2344 10
        return static::create(
2345 10
            $this->utf8::swapCase($this->str, $this->encoding),
2346 10
            $this->encoding
2347
        );
2348
    }
2349
2350
    /**
2351
     * Returns a string with smart quotes, ellipsis characters, and dashes from
2352
     * Windows-1252 (commonly used in Word documents) replaced by their ASCII
2353
     * equivalents.
2354
     *
2355
     * @return static
2356
     *                <p>Object whose $str has those characters removed.</p>
2357
     */
2358 8
    public function tidy(): self
2359
    {
2360 8
        return static::create(
2361 8
            $this->ascii::normalize_msword($this->str),
2362 8
            $this->encoding
2363
        );
2364
    }
2365
2366
    /**
2367
     * Returns a trimmed string with the first letter of each word capitalized.
2368
     * Also accepts an array, $ignore, allowing you to list words not to be
2369
     * capitalized.
2370
     *
2371
     * @param array|string[]|null $ignore            [optional] <p>An array of words not to capitalize or null.
2372
     *                                               Default: null</p>
2373
     * @param string|null         $word_define_chars [optional] <p>An string of chars that will be used as whitespace
2374
     *                                               separator === words.</p>
2375
     * @param string|null         $language          [optional] <p>Language of the source string.</p>
2376
     *
2377
     * @return static
2378
     *                <p>Object with a titleized $str.</p>
2379
     */
2380 14
    public function titleize(
2381
        array $ignore = null,
2382
        string $word_define_chars = null,
2383
        string $language = null
2384
    ): self {
2385 14
        return static::create(
2386 14
            $this->utf8::str_titleize(
2387 14
                $this->str,
2388 14
                $ignore,
2389 14
                $this->encoding,
2390 14
                false,
2391 14
                $language,
2392 14
                false,
2393 14
                true,
2394 14
                $word_define_chars
2395
            ),
2396 14
            $this->encoding
2397
        );
2398
    }
2399
2400
    /**
2401
     * Returns a trimmed string in proper title case.
2402
     *
2403
     * Also accepts an array, $ignore, allowing you to list words not to be
2404
     * capitalized.
2405
     *
2406
     * Adapted from John Gruber's script.
2407
     *
2408
     * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
2409
     *
2410
     * @param array $ignore <p>An array of words not to capitalize.</p>
2411
     *
2412
     * @return static
2413
     *                <p>Object with a titleized $str</p>
2414
     */
2415 35
    public function titleizeForHumans(array $ignore = []): self
2416
    {
2417 35
        return static::create(
2418 35
            $this->utf8::str_titleize_for_humans(
2419 35
                $this->str,
2420 35
                $ignore,
2421 35
                $this->encoding
2422
            ),
2423 35
            $this->encoding
2424
        );
2425
    }
2426
2427
    /**
2428
     * Returns an ASCII version of the string. A set of non-ASCII characters are
2429
     * replaced with their closest ASCII counterparts, and the rest are removed
2430
     * unless instructed otherwise.
2431
     *
2432
     * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
2433
     *                        performance | Default: false</p>
2434
     * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
2435
     *
2436
     * @return static
2437
     *                <p>Object whose $str contains only ASCII characters.</p>
2438
     */
2439 17
    public function toTransliterate(bool $strict = false, string $unknown = '?'): self
2440
    {
2441 17
        return static::create(
2442 17
            $this->ascii::to_transliterate($this->str, $unknown, $strict),
2443 17
            $this->encoding
2444
        );
2445
    }
2446
2447
    /**
2448
     * Returns an ASCII version of the string. A set of non-ASCII characters are
2449
     * replaced with their closest ASCII counterparts, and the rest are removed
2450
     * by default. The language or locale of the source string can be supplied
2451
     * for language-specific transliteration in any of the following formats:
2452
     * en, en_GB, or en-GB. For example, passing "de" results in "äöü" mapping
2453
     * to "aeoeue" rather than "aou" as in other languages.
2454
     *
2455
     * @param string $language          [optional] <p>Language of the source string.</p>
2456
     * @param bool   $removeUnsupported [optional] <p>Whether or not to remove the
2457
     *                                  unsupported characters.</p>
2458
     *
2459
     * @return static
2460
     *                <p>Object whose $str contains only ASCII characters.</p>
2461
     */
2462 23
    public function toAscii(string $language = 'en', bool $removeUnsupported = true): self
2463
    {
2464 23
        return static::create(
2465 23
            $this->ascii::to_ascii(
2466 23
                $this->str,
2467 23
                $language,
2468 23
                $removeUnsupported
2469
            ),
2470 23
            $this->encoding
2471
        );
2472
    }
2473
2474
    /**
2475
     * Returns a boolean representation of the given logical string value.
2476
     * For example, 'true', '1', 'on' and 'yes' will return true. 'false', '0',
2477
     * 'off', and 'no' will return false. In all instances, case is ignored.
2478
     * For other numeric strings, their sign will determine the return value.
2479
     * In addition, blank strings consisting of only whitespace will return
2480
     * false. For all other strings, the return value is a result of a
2481
     * boolean cast.
2482
     *
2483
     * @return bool
2484
     *              <p>A boolean value for the string.</p>
2485
     */
2486 30
    public function toBoolean(): bool
2487
    {
2488 30
        return $this->utf8::to_boolean($this->str);
2489
    }
2490
2491
    /**
2492
     * Converts all characters in the string to lowercase.
2493
     *
2494
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
2495
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
2496
     *
2497
     * @return static
2498
     *                <p>Object with all characters of $str being lowercase.</p>
2499
     */
2500 12 View Code Duplication
    public function toLowerCase($tryToKeepStringLength = false, $lang = null): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2501
    {
2502 12
        return static::create(
2503 12
            $this->utf8::strtolower(
2504 12
                $this->str,
2505 12
                $this->encoding,
2506 12
                false,
2507 12
                $lang,
2508 12
                $tryToKeepStringLength
2509
            ),
2510 12
            $this->encoding
2511
        );
2512
    }
2513
2514
    /**
2515
     * Converts each tab in the string to some number of spaces, as defined by
2516
     * $tabLength. By default, each tab is converted to 4 consecutive spaces.
2517
     *
2518
     * @param int $tabLength [optional] <p>Number of spaces to replace each tab with. Default: 4</p>
2519
     *
2520
     * @return static
2521
     *                <p>Object whose $str has had tabs switched to spaces.</p>
2522
     */
2523 12 View Code Duplication
    public function toSpaces(int $tabLength = 4): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2524
    {
2525 12
        if ($tabLength === 4) {
2526 6
            $tab = '    ';
2527 6
        } elseif ($tabLength === 2) {
2528 2
            $tab = '  ';
2529
        } else {
2530 4
            $tab = \str_repeat(' ', $tabLength);
2531
        }
2532
2533 12
        return static::create(
2534 12
            \str_replace("\t", $tab, $this->str),
2535 12
            $this->encoding
2536
        );
2537
    }
2538
2539
    /**
2540
     * Return Stringy object as string, but you can also use (string) for automatically casting the object into a
2541
     * string.
2542
     *
2543
     * @return string
2544
     */
2545 1084
    public function toString(): string
2546
    {
2547 1084
        return (string) $this->str;
2548
    }
2549
2550
    /**
2551
     * Converts each occurrence of some consecutive number of spaces, as
2552
     * defined by $tabLength, to a tab. By default, each 4 consecutive spaces
2553
     * are converted to a tab.
2554
     *
2555
     * @param int $tabLength [optional] <p>Number of spaces to replace with a tab. Default: 4</p>
2556
     *
2557
     * @return static
2558
     *                <p>Object whose $str has had spaces switched to tabs.</p>
2559
     */
2560 10 View Code Duplication
    public function toTabs(int $tabLength = 4): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2561
    {
2562 10
        if ($tabLength === 4) {
2563 6
            $tab = '    ';
2564 4
        } elseif ($tabLength === 2) {
2565 2
            $tab = '  ';
2566
        } else {
2567 2
            $tab = \str_repeat(' ', $tabLength);
2568
        }
2569
2570 10
        return static::create(
2571 10
            \str_replace($tab, "\t", $this->str),
2572 10
            $this->encoding
2573
        );
2574
    }
2575
2576
    /**
2577
     * Converts the first character of each word in the string to uppercase
2578
     * and all other chars to lowercase.
2579
     *
2580
     * @return static
2581
     *                <p>Object with all characters of $str being title-cased.</p>
2582
     */
2583 10
    public function toTitleCase(): self
2584
    {
2585 10
        return static::create(
2586 10
            $this->utf8::titlecase($this->str, $this->encoding),
2587 10
            $this->encoding
2588
        );
2589
    }
2590
2591
    /**
2592
     * Converts all characters in the string to uppercase.
2593
     *
2594
     * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
2595
     * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
2596
     *
2597
     * @return static
2598
     *                <p>Object with all characters of $str being uppercase.</p>
2599
     */
2600 11 View Code Duplication
    public function toUpperCase($tryToKeepStringLength = false, $lang = null): self
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
2601
    {
2602 11
        return static::create(
2603 11
            $this->utf8::strtoupper($this->str, $this->encoding, false, $lang, $tryToKeepStringLength),
2604 11
            $this->encoding
2605
        );
2606
    }
2607
2608
    /**
2609
     * Returns a string with whitespace removed from the start and end of the
2610
     * string. Supports the removal of unicode whitespace. Accepts an optional
2611
     * string of characters to strip instead of the defaults.
2612
     *
2613
     * @param string $chars [optional] <p>String of characters to strip. Default: null</p>
2614
     *
2615
     * @return static
2616
     *                <p>Object with a trimmed $str.</p>
2617
     */
2618 24
    public function trim(string $chars = null): self
2619
    {
2620 24
        return static::create(
2621 24
            $this->utf8::trim($this->str, $chars),
2622 24
            $this->encoding
2623
        );
2624
    }
2625
2626
    /**
2627
     * Returns a string with whitespace removed from the start of the string.
2628
     * Supports the removal of unicode whitespace. Accepts an optional
2629
     * string of characters to strip instead of the defaults.
2630
     *
2631
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
2632
     *
2633
     * @return static
2634
     *                <p>Object with a trimmed $str.</p>
2635
     */
2636 26
    public function trimLeft(string $chars = null): self
2637
    {
2638 26
        return static::create(
2639 26
            $this->utf8::ltrim($this->str, $chars),
2640 26
            $this->encoding
2641
        );
2642
    }
2643
2644
    /**
2645
     * Returns a string with whitespace removed from the end of the string.
2646
     * Supports the removal of unicode whitespace. Accepts an optional
2647
     * string of characters to strip instead of the defaults.
2648
     *
2649
     * @param string $chars [optional] <p>Optional string of characters to strip. Default: null</p>
2650
     *
2651
     * @return static
2652
     *                <p>Object with a trimmed $str.</p>
2653
     */
2654 26
    public function trimRight(string $chars = null): self
2655
    {
2656 26
        return static::create(
2657 26
            $this->utf8::rtrim($this->str, $chars),
2658 26
            $this->encoding
2659
        );
2660
    }
2661
2662
    /**
2663
     * Truncates the string to a given length. If $substring is provided, and
2664
     * truncating occurs, the string is further truncated so that the substring
2665
     * may be appended without exceeding the desired length.
2666
     *
2667
     * @param int    $length    <p>Desired length of the truncated string.</p>
2668
     * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
2669
     *
2670
     * @return static
2671
     *                <p>Object with the resulting $str after truncating.</p>
2672
     */
2673 44
    public function truncate(int $length, string $substring = ''): self
2674
    {
2675 44
        return static::create(
2676 44
            $this->utf8::str_truncate($this->str, $length, $substring, $this->encoding),
2677 44
            $this->encoding
2678
        );
2679
    }
2680
2681
    /**
2682
     * Returns a lowercase and trimmed string separated by underscores.
2683
     * Underscores are inserted before uppercase characters (with the exception
2684
     * of the first character of the string), and in place of spaces as well as
2685
     * dashes.
2686
     *
2687
     * @return static
2688
     *                <p>Object with an underscored $str.</p>
2689
     */
2690 32
    public function underscored(): self
2691
    {
2692 32
        return $this->delimit('_');
2693
    }
2694
2695
    /**
2696
     * Returns an UpperCamelCase version of the supplied string. It trims
2697
     * surrounding spaces, capitalizes letters following digits, spaces, dashes
2698
     * and underscores, and removes spaces, dashes, underscores.
2699
     *
2700
     * @return static
2701
     *                <p>Object with $str in UpperCamelCase.</p>
2702
     */
2703 26
    public function upperCamelize(): self
2704
    {
2705 26
        return static::create(
2706 26
            $this->utf8::str_upper_camelize($this->str, $this->encoding),
2707 26
            $this->encoding
2708
        );
2709
    }
2710
2711
    /**
2712
     * Converts the first character of the supplied string to upper case.
2713
     *
2714
     * @return static
2715
     *                <p>Object with the first character of $str being upper case.</p>
2716
     */
2717 12
    public function upperCaseFirst(): self
2718
    {
2719 12
        return static::create($this->utf8::ucfirst($this->str, $this->encoding), $this->encoding);
2720
    }
2721
2722
    /**
2723
     * Converts the string into an valid UTF-8 string.
2724
     *
2725
     * @return static
2726
     */
2727 1
    public function utf8ify(): self
2728
    {
2729 1
        return static::create($this->utf8::cleanup($this->str), $this->encoding);
2730
    }
2731
2732
    /**
2733
     * Returns the replacements for the toAscii() method.
2734
     *
2735
     * @noinspection PhpUnused
2736
     *
2737
     * @return array<string, array<int, string>>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
2738
     *                       <p>An array of replacements.</p>
2739
     *
2740
     * @deprecated   this is only here for backward-compatibly reasons
2741
     */
2742 1
    protected function charsArray(): array
2743
    {
2744 1
        return $this->ascii::charsArrayWithMultiLanguageValues();
2745
    }
2746
2747
    /**
2748
     * Returns true if $str matches the supplied pattern, false otherwise.
2749
     *
2750
     * @param string $pattern <p>Regex pattern to match against.</p>
2751
     *
2752
     * @return bool
2753
     *              <p>Whether or not $str matches the pattern.</p>
2754
     */
2755 12
    protected function matchesPattern(string $pattern): bool
2756
    {
2757 12
        return $this->utf8::str_matches_pattern($this->str, $pattern);
2758
    }
2759
}
2760