Passed
Push — master ( 3e5c55...27a0be )
by Lars
06:13
created

UTF8::str_shuffle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\helper;
6
7
/**
8
 * UTF8-Helper-Class
9
 *
10
 * @package voku\helper
11
 */
12
final class UTF8
13
{
14
  // (CRLF|([ZWNJ-ZWJ]|T+|L*(LV?V+|LV|LVT)T*|L+|[^Control])[Extend]*|[Control])
15
  // This regular expression is a work around for http://bugs.exim.org/1279
16
  const GRAPHEME_CLUSTER_RX = "(?:\r\n|(?:[ -~\x{200C}\x{200D}]|[ᆨ-ᇹ]+|[ᄀ-ᅟ]*(?:[가개갸걔거게겨계고과괘괴교구궈궤귀규그긔기까깨꺄꺠꺼께껴꼐꼬꽈꽤꾀꾜꾸꿔꿰뀌뀨끄끠끼나내냐냬너네녀녜노놔놰뇌뇨누눠눼뉘뉴느늬니다대댜댸더데뎌뎨도돠돼되됴두둬뒈뒤듀드듸디따때땨떄떠떼뗘뗴또똬뙈뙤뚀뚜뚸뛔뛰뜌뜨띄띠라래랴럐러레려례로롸뢔뢰료루뤄뤠뤼류르릐리마매먀먜머메며몌모뫄뫠뫼묘무뭐뭬뮈뮤므믜미바배뱌뱨버베벼볘보봐봬뵈뵤부붜붸뷔뷰브븨비빠빼뺘뺴뻐뻬뼈뼤뽀뽜뽸뾔뾰뿌뿨쀄쀠쀼쁘쁴삐사새샤섀서세셔셰소솨쇄쇠쇼수숴쉐쉬슈스싀시싸쌔쌰썌써쎄쎠쎼쏘쏴쐐쐬쑈쑤쒀쒜쒸쓔쓰씌씨아애야얘어에여예오와왜외요우워웨위유으의이자재쟈쟤저제져졔조좌좨죄죠주줘줴쥐쥬즈즤지짜째쨔쨰쩌쩨쪄쪠쪼쫘쫴쬐쬬쭈쭤쮀쮜쮸쯔쯰찌차채챠챼처체쳐쳬초촤쵀최쵸추춰췌취츄츠츼치카캐캬컈커케켜켸코콰쾌쾨쿄쿠쿼퀘퀴큐크킈키타태탸턔터테텨톄토톼퇘퇴툐투퉈퉤튀튜트틔티파패퍄퍠퍼페펴폐포퐈퐤푀표푸풔풰퓌퓨프픠피하해햐햬허헤혀혜호화홰회효후훠훼휘휴흐희히]?[ᅠ-ᆢ]+|[가-힣])[ᆨ-ᇹ]*|[ᄀ-ᅟ]+|[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}])[\p{Mn}\p{Me}\x{09BE}\x{09D7}\x{0B3E}\x{0B57}\x{0BBE}\x{0BD7}\x{0CC2}\x{0CD5}\x{0CD6}\x{0D3E}\x{0D57}\x{0DCF}\x{0DDF}\x{200C}\x{200D}\x{1D165}\x{1D16E}-\x{1D172}]*|[\p{Cc}\p{Cf}\p{Zl}\p{Zp}])";
17
18
  /**
19
   * Bom => Byte-Length
20
   *
21
   * INFO: https://en.wikipedia.org/wiki/Byte_order_mark
22
   *
23
   * @var array
24
   */
25
  private static $BOM = [
26
      "\xef\xbb\xbf"     => 3, // UTF-8 BOM
27
      ''              => 6, // UTF-8 BOM as "WINDOWS-1252" (one char has [maybe] more then one byte ...)
28
      "\x00\x00\xfe\xff" => 4, // UTF-32 (BE) BOM
29
      '  þÿ'             => 6, // UTF-32 (BE) BOM as "WINDOWS-1252"
30
      "\xff\xfe\x00\x00" => 4, // UTF-32 (LE) BOM
31
      'ÿþ  '             => 6, // UTF-32 (LE) BOM as "WINDOWS-1252"
32
      "\xfe\xff"         => 2, // UTF-16 (BE) BOM
33
      'þÿ'               => 4, // UTF-16 (BE) BOM as "WINDOWS-1252"
34
      "\xff\xfe"         => 2, // UTF-16 (LE) BOM
35
      'ÿþ'               => 4, // UTF-16 (LE) BOM as "WINDOWS-1252"
36
  ];
37
38
  /**
39
   * Numeric code point => UTF-8 Character
40
   *
41
   * url: http://www.w3schools.com/charsets/ref_utf_punctuation.asp
42
   *
43
   * @var array
44
   */
45
  private static $WHITESPACE = [
46
    // NUL Byte
47
    0     => "\x0",
48
    // Tab
49
    9     => "\x9",
50
    // New Line
51
    10    => "\xa",
52
    // Vertical Tab
53
    11    => "\xb",
54
    // Carriage Return
55
    13    => "\xd",
56
    // Ordinary Space
57
    32    => "\x20",
58
    // NO-BREAK SPACE
59
    160   => "\xc2\xa0",
60
    // OGHAM SPACE MARK
61
    5760  => "\xe1\x9a\x80",
62
    // MONGOLIAN VOWEL SEPARATOR
63
    6158  => "\xe1\xa0\x8e",
64
    // EN QUAD
65
    8192  => "\xe2\x80\x80",
66
    // EM QUAD
67
    8193  => "\xe2\x80\x81",
68
    // EN SPACE
69
    8194  => "\xe2\x80\x82",
70
    // EM SPACE
71
    8195  => "\xe2\x80\x83",
72
    // THREE-PER-EM SPACE
73
    8196  => "\xe2\x80\x84",
74
    // FOUR-PER-EM SPACE
75
    8197  => "\xe2\x80\x85",
76
    // SIX-PER-EM SPACE
77
    8198  => "\xe2\x80\x86",
78
    // FIGURE SPACE
79
    8199  => "\xe2\x80\x87",
80
    // PUNCTUATION SPACE
81
    8200  => "\xe2\x80\x88",
82
    // THIN SPACE
83
    8201  => "\xe2\x80\x89",
84
    //HAIR SPACE
85
    8202  => "\xe2\x80\x8a",
86
    // LINE SEPARATOR
87
    8232  => "\xe2\x80\xa8",
88
    // PARAGRAPH SEPARATOR
89
    8233  => "\xe2\x80\xa9",
90
    // NARROW NO-BREAK SPACE
91
    8239  => "\xe2\x80\xaf",
92
    // MEDIUM MATHEMATICAL SPACE
93
    8287  => "\xe2\x81\x9f",
94
    // IDEOGRAPHIC SPACE
95
    12288 => "\xe3\x80\x80",
96
  ];
97
98
  /**
99
   * @var array
100
   */
101
  private static $WHITESPACE_TABLE = [
102
      'SPACE'                     => "\x20",
103
      'NO-BREAK SPACE'            => "\xc2\xa0",
104
      'OGHAM SPACE MARK'          => "\xe1\x9a\x80",
105
      'EN QUAD'                   => "\xe2\x80\x80",
106
      'EM QUAD'                   => "\xe2\x80\x81",
107
      'EN SPACE'                  => "\xe2\x80\x82",
108
      'EM SPACE'                  => "\xe2\x80\x83",
109
      'THREE-PER-EM SPACE'        => "\xe2\x80\x84",
110
      'FOUR-PER-EM SPACE'         => "\xe2\x80\x85",
111
      'SIX-PER-EM SPACE'          => "\xe2\x80\x86",
112
      'FIGURE SPACE'              => "\xe2\x80\x87",
113
      'PUNCTUATION SPACE'         => "\xe2\x80\x88",
114
      'THIN SPACE'                => "\xe2\x80\x89",
115
      'HAIR SPACE'                => "\xe2\x80\x8a",
116
      'LINE SEPARATOR'            => "\xe2\x80\xa8",
117
      'PARAGRAPH SEPARATOR'       => "\xe2\x80\xa9",
118
      'ZERO WIDTH SPACE'          => "\xe2\x80\x8b",
119
      'NARROW NO-BREAK SPACE'     => "\xe2\x80\xaf",
120
      'MEDIUM MATHEMATICAL SPACE' => "\xe2\x81\x9f",
121
      'IDEOGRAPHIC SPACE'         => "\xe3\x80\x80",
122
  ];
123
124
  /**
125
   * bidirectional text chars
126
   *
127
   * url: https://www.w3.org/International/questions/qa-bidi-unicode-controls
128
   *
129
   * @var array
130
   */
131
  private static $BIDI_UNI_CODE_CONTROLS_TABLE = [
132
    // LEFT-TO-RIGHT EMBEDDING (use -> dir = "ltr")
133
    8234 => "\xE2\x80\xAA",
134
    // RIGHT-TO-LEFT EMBEDDING (use -> dir = "rtl")
135
    8235 => "\xE2\x80\xAB",
136
    // POP DIRECTIONAL FORMATTING // (use -> </bdo>)
137
    8236 => "\xE2\x80\xAC",
138
    // LEFT-TO-RIGHT OVERRIDE // (use -> <bdo dir = "ltr">)
139
    8237 => "\xE2\x80\xAD",
140
    // RIGHT-TO-LEFT OVERRIDE // (use -> <bdo dir = "rtl">)
141
    8238 => "\xE2\x80\xAE",
142
    // LEFT-TO-RIGHT ISOLATE // (use -> dir = "ltr")
143
    8294 => "\xE2\x81\xA6",
144
    // RIGHT-TO-LEFT ISOLATE // (use -> dir = "rtl")
145
    8295 => "\xE2\x81\xA7",
146
    // FIRST STRONG ISOLATE // (use -> dir = "auto")
147
    8296 => "\xE2\x81\xA8",
148
    // POP DIRECTIONAL ISOLATE
149
    8297 => "\xE2\x81\xA9",
150
  ];
151
152
  /**
153
   * @var array
154
   */
155
  private static $COMMON_CASE_FOLD = [
156
      'upper' => [
157
          'µ',
158
          'ſ',
159
          "\xCD\x85",
160
          'ς',
161
          'ẞ',
162
          "\xCF\x90",
163
          "\xCF\x91",
164
          "\xCF\x95",
165
          "\xCF\x96",
166
          "\xCF\xB0",
167
          "\xCF\xB1",
168
          "\xCF\xB5",
169
          "\xE1\xBA\x9B",
170
          "\xE1\xBE\xBE",
171
      ],
172
      'lower' => [
173
          'μ',
174
          's',
175
          'ι',
176
          'σ',
177
          'ß',
178
          'β',
179
          'θ',
180
          'φ',
181
          'π',
182
          'κ',
183
          'ρ',
184
          'ε',
185
          "\xE1\xB9\xA1",
186
          'ι',
187
      ],
188
  ];
189
190
191
  /**
192
   * @var array
193
   */
194
  private static $SUPPORT = [];
195
196
  /**
197
   * @var null|array
198
   */
199
  private static $UTF8_MSWORD;
200
201
  /**
202
   * @var null|array
203
   */
204
  private static $BROKEN_UTF8_FIX;
205
206
  /**
207
   * @var null|array
208
   */
209
  private static $WIN1252_TO_UTF8;
210
211
  /**
212
   * @var null|array
213
   */
214
  private static $ENCODINGS;
215
216
  /**
217
   * @var null|array
218
   */
219
  private static $ORD;
220
221
  /**
222
   * @var null|array
223
   */
224
  private static $CHR;
225
226
  /**
227
   * __construct()
228
   */
229 32
  public function __construct()
230
  {
231 32
    self::checkForSupport();
232 32
  }
233
234
  /**
235
   * Return the character at the specified position: $str[1] like functionality.
236
   *
237
   * @param string $str <p>A UTF-8 string.</p>
238
   * @param int    $pos <p>The position of character to return.</p>
239
   *
240
   * @return string Single Multi-Byte character.
241
   */
242 3
  public static function access(string $str, int $pos): string
243
  {
244 3
    if ('' === $str) {
245 1
      return '';
246
    }
247
248 3
    if ($pos < 0) {
249 2
      return '';
250
    }
251
252 3
    return (string)self::substr($str, $pos, 1);
253
  }
254
255
  /**
256
   * Prepends UTF-8 BOM character to the string and returns the whole string.
257
   *
258
   * INFO: If BOM already existed there, the Input string is returned.
259
   *
260
   * @param string $str <p>The input string.</p>
261
   *
262
   * @return string The output string that contains BOM.
263
   */
264 2
  public static function add_bom_to_string(string $str): string
265
  {
266 2
    if (self::string_has_bom($str) === false) {
267 2
      $str = self::bom() . $str;
268
    }
269
270 2
    return $str;
271
  }
272
273
  /**
274
   * Adds the specified amount of left and right padding to the given string.
275
   * The default character used is a space.
276
   *
277
   * @param string $str
278
   * @param int    $left     [optional] <p>Length of left padding. Default: 0</p>
279
   * @param int    $right    [optional] <p>Length of right padding. Default: 0</p>
280
   * @param string $padStr   [optional] <p>String used to pad. Default: ' '</p>
281
   * @param string $encoding [optional] <p>Default: UTF-8</p>
282
   *
283
   * @return string String with padding applied.
284
   */
285 25
  private static function apply_padding(string $str, int $left = 0, int $right = 0, string $padStr = ' ', string $encoding): string
286
  {
287 25
    $strlen = self::strlen($str, $encoding);
288
289 25
    if ($left && $right) {
290 8
      $length = ($left + $right) + $strlen;
291 8
      $type = STR_PAD_BOTH;
292 17
    } elseif ($left) {
293 7
      $length = $left + $strlen;
294 7
      $type = STR_PAD_LEFT;
295 10
    } elseif ($right) {
296 10
      $length = $right + $strlen;
297 10
      $type = STR_PAD_RIGHT;
298
    } else {
299
      $length = ($left + $right) + $strlen;
300
      $type = STR_PAD_BOTH;
301
    }
302
303 25
    return self::str_pad($str, $length, $padStr, $type, $encoding);
304
  }
305
306
  /**
307
   * Changes all keys in an array.
308
   *
309
   * @param array $array <p>The array to work on</p>
310
   * @param int   $case  [optional] <p> Either <strong>CASE_UPPER</strong><br>
311
   *                     or <strong>CASE_LOWER</strong> (default)</p>
312
   *
313
   * @return string[] An array with its keys lower or uppercased.
314
   */
315 2
  public static function array_change_key_case(array $array, int $case = CASE_LOWER): array
316
  {
317
    if (
318 2
        $case !== CASE_LOWER
319
        &&
320 2
        $case !== CASE_UPPER
321
    ) {
322
      $case = CASE_LOWER;
323
    }
324
325 2
    $return = [];
326 2
    foreach ($array as $key => $value) {
327 2
      if ($case === CASE_LOWER) {
328 2
        $key = self::strtolower($key);
329
      } else {
330 2
        $key = self::strtoupper($key);
331
      }
332
333 2
      $return[$key] = $value;
334
    }
335
336 2
    return $return;
337
  }
338
339
  /**
340
   * Returns the substring between $start and $end, if found, or an empty
341
   * string. An optional offset may be supplied from which to begin the
342
   * search for the start string.
343
   *
344
   * @param string $str
345
   * @param string $start    <p>Delimiter marking the start of the substring.</p>
346
   * @param string $end      <p>Delimiter marking the end of the substring.</p>
347
   * @param int    $offset   [optional] <p>Index from which to begin the search. Default: 0</p>
348
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
349
   *
350
   * @return string
351
   */
352 16
  public static function between(string $str, string $start, string $end, int $offset = 0, string $encoding = 'UTF-8'): string
353
  {
354 16
    $posStart = self::strpos($str, $start, $offset, $encoding);
355 16
    if ($posStart === false) {
356 2
      return '';
357
    }
358
359 14
    $substrIndex = $posStart + self::strlen($start, $encoding);
360 14
    $posEnd = self::strpos($str, $end, $substrIndex, $encoding);
361
    if (
362 14
        $posEnd === false
363
        ||
364 14
        $posEnd === $substrIndex
365
    ) {
366 4
      return '';
367
    }
368
369 10
    $return = self::substr($str, $substrIndex, $posEnd - $substrIndex, $encoding);
370
371 10
    if ($return === false) {
372
      return '';
373
    }
374
375 10
    return $return;
376
  }
377
378
  /**
379
   * Convert binary into an string.
380
   *
381
   * @param mixed $bin 1|0
382
   *
383
   * @return string
384
   */
385 2
  public static function binary_to_str($bin): string
386
  {
387 2
    if (!isset($bin[0])) {
388
      return '';
389
    }
390
391 2
    $convert = \base_convert($bin, 2, 16);
392 2
    if ($convert === '0') {
393 1
      return '';
394
    }
395
396 2
    return \pack('H*', $convert);
397
  }
398
399
  /**
400
   * Returns the UTF-8 Byte Order Mark Character.
401
   *
402
   * INFO: take a look at UTF8::$bom for e.g. UTF-16 and UTF-32 BOM values
403
   *
404
   * @return string UTF-8 Byte Order Mark
405
   */
406 4
  public static function bom(): string
407
  {
408 4
    return "\xef\xbb\xbf";
409
  }
410
411
  /**
412
   * @alias of UTF8::chr_map()
413
   *
414
   * @see   UTF8::chr_map()
415
   *
416
   * @param string|array $callback
417
   * @param string       $str
418
   *
419
   * @return string[]
420
   */
421 2
  public static function callback($callback, string $str): array
422
  {
423 2
    return self::chr_map($callback, $str);
424
  }
425
426
  /**
427
   * Returns the character at $index, with indexes starting at 0.
428
   *
429
   * @param string $str
430
   * @param int    $index    <p>Position of the character.</p>
431
   * @param string $encoding [optional] <p>Default is UTF-8</p>
432
   *
433
   * @return string The character at $index.
434
   */
435 9
  public static function char_at(string $str, int $index, string $encoding = 'UTF-8'): string
436
  {
437 9
    return (string)self::substr($str, $index, 1, $encoding);
438
  }
439
440
  /**
441
   * Returns an array consisting of the characters in the string.
442
   *
443
   * @param string $str <p>The input string.</p>
444
   *
445
   * @return string[] An array of chars.
446
   */
447 3
  public static function chars(string $str): array
448
  {
449 3
    return self::str_split($str, 1);
450
  }
451
452
  /**
453
   * This method will auto-detect your server environment for UTF-8 support.
454
   *
455
   * INFO: You don't need to run it manually, it will be triggered if it's needed.
456
   */
457 37
  public static function checkForSupport()
458
  {
459 37
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
460
461
      self::$SUPPORT['already_checked_via_portable_utf8'] = true;
462
463
      // http://php.net/manual/en/book.mbstring.php
464
      self::$SUPPORT['mbstring'] = self::mbstring_loaded();
465
      self::$SUPPORT['mbstring_func_overload'] = self::mbstring_overloaded();
466
467
      // http://php.net/manual/en/book.iconv.php
468
      self::$SUPPORT['iconv'] = self::iconv_loaded();
469
470
      // http://php.net/manual/en/book.intl.php
471
      self::$SUPPORT['intl'] = self::intl_loaded();
472
      self::$SUPPORT['intl__transliterator_list_ids'] = [];
473
474
      self::$SUPPORT['symfony_polyfill_used'] = self::symfony_polyfill_used();
475
476
      if (
477
          self::$SUPPORT['intl'] === true
478
          &&
479
          \function_exists('transliterator_list_ids') === true
480
      ) {
481
        /** @noinspection PhpComposerExtensionStubsInspection */
482
        self::$SUPPORT['intl__transliterator_list_ids'] = \transliterator_list_ids();
483
      }
484
485
      // http://php.net/manual/en/class.intlchar.php
486
      self::$SUPPORT['intlChar'] = self::intlChar_loaded();
487
488
      // http://php.net/manual/en/book.ctype.php
489
      self::$SUPPORT['ctype'] = self::ctype_loaded();
490
491
      // http://php.net/manual/en/class.finfo.php
492
      self::$SUPPORT['finfo'] = self::finfo_loaded();
493
494
      // http://php.net/manual/en/book.json.php
495
      self::$SUPPORT['json'] = self::json_loaded();
496
497
      // http://php.net/manual/en/book.pcre.php
498
      self::$SUPPORT['pcre_utf8'] = self::pcre_utf8_support();
499
    }
500 37
  }
501
502
  /**
503
   * Generates a UTF-8 encoded character from the given code point.
504
   *
505
   * INFO: opposite to UTF8::ord()
506
   *
507
   * @param int|string $code_point <p>The code point for which to generate a character.</p>
508
   * @param string     $encoding   [optional] <p>Default is UTF-8</p>
509
   *
510
   * @return string|null Multi-Byte character, returns null on failure or empty input.
511
   */
512 17
  public static function chr($code_point, string $encoding = 'UTF-8')
513
  {
514
    // init
515 17
    static $CHAR_CACHE = [];
516
517 17
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
518
      self::checkForSupport();
519
    }
520
521 17
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
522 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
523
    }
524
525
    if (
526 17
        $encoding !== 'UTF-8'
527
        &&
528 17
        $encoding !== 'ISO-8859-1'
529
        &&
530 17
        $encoding !== 'WINDOWS-1252'
531
        &&
532 17
        self::$SUPPORT['mbstring'] === false
533
    ) {
534
      \trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
535
    }
536
537 17
    $cacheKey = $code_point . $encoding;
538 17
    if (isset($CHAR_CACHE[$cacheKey]) === true) {
539 16
      return $CHAR_CACHE[$cacheKey];
540
    }
541
542 11
    if ($code_point <= 127) { // use "simple"-char only until "\x80"
543
544 10
      if (self::$CHR === null) {
545
        $chrTmp = self::getData('chr');
546
        if ($chrTmp) {
547
          self::$CHR = (array)$chrTmp;
548
        }
549
      }
550
551 10
      $chr = self::$CHR[$code_point];
552
553 10
      if ($encoding !== 'UTF-8') {
554 1
        $chr = self::encode($encoding, $chr);
555
      }
556
557 10
      return $CHAR_CACHE[$cacheKey] = $chr;
558
    }
559
560 7
    if (self::$SUPPORT['intlChar'] === true) {
561
      /** @noinspection PhpComposerExtensionStubsInspection */
562 7
      $chr = \IntlChar::chr($code_point);
563
564 7
      if ($encoding !== 'UTF-8') {
565
        $chr = self::encode($encoding, $chr);
566
      }
567
568 7
      return $CHAR_CACHE[$cacheKey] = $chr;
569
    }
570
571
    if (self::$CHR === null) {
572
      $chrTmp = self::getData('chr');
573
      if ($chrTmp) {
574
        self::$CHR = (array)$chrTmp;
575
      }
576
    }
577
578
    $code_point = (int)$code_point;
579
    if ($code_point <= 0x7F) {
580
      $chr = self::$CHR[$code_point];
581
    } elseif ($code_point <= 0x7FF) {
582
      $chr = self::$CHR[($code_point >> 6) + 0xC0] .
583
             self::$CHR[($code_point & 0x3F) + 0x80];
584
    } elseif ($code_point <= 0xFFFF) {
585
      $chr = self::$CHR[($code_point >> 12) + 0xE0] .
586
             self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
587
             self::$CHR[($code_point & 0x3F) + 0x80];
588
    } else {
589
      $chr = self::$CHR[($code_point >> 18) + 0xF0] .
590
             self::$CHR[(($code_point >> 12) & 0x3F) + 0x80] .
591
             self::$CHR[(($code_point >> 6) & 0x3F) + 0x80] .
592
             self::$CHR[($code_point & 0x3F) + 0x80];
593
    }
594
595
    if ($encoding !== 'UTF-8') {
596
      $chr = self::encode($encoding, $chr);
597
    }
598
599
    return $CHAR_CACHE[$cacheKey] = $chr;
600
  }
601
602
  /**
603
   * Applies callback to all characters of a string.
604
   *
605
   * @param string|array $callback <p>The callback function.</p>
606
   * @param string       $str      <p>UTF-8 string to run callback on.</p>
607
   *
608
   * @return string[] The outcome of callback.
609
   */
610 2
  public static function chr_map($callback, string $str): array
611
  {
612 2
    $chars = self::split($str);
613
614 2
    return \array_map($callback, $chars);
615
  }
616
617
  /**
618
   * Generates an array of byte length of each character of a Unicode string.
619
   *
620
   * 1 byte => U+0000  - U+007F
621
   * 2 byte => U+0080  - U+07FF
622
   * 3 byte => U+0800  - U+FFFF
623
   * 4 byte => U+10000 - U+10FFFF
624
   *
625
   * @param string $str <p>The original unicode string.</p>
626
   *
627
   * @return int[] An array of byte lengths of each character.
628
   */
629 4
  public static function chr_size_list(string $str): array
630
  {
631 4
    if ('' === $str) {
632 4
      return [];
633
    }
634
635 4
    $strSplit = self::split($str);
636
637 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
638
      self::checkForSupport();
639
    }
640
641 4
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
642
      return \array_map(
643
          function ($data) {
644
            return UTF8::strlen_in_byte($data);
645
          },
646
          $strSplit
647
      );
648
    }
649
650 4
    return \array_map('\strlen', $strSplit);
651
  }
652
653
  /**
654
   * Get a decimal code representation of a specific character.
655
   *
656
   * @param string $char <p>The input character.</p>
657
   *
658
   * @return int
659
   */
660 4
  public static function chr_to_decimal(string $char): int
661
  {
662 4
    $code = self::ord($char[0]);
663 4
    $bytes = 1;
664
665 4
    if (!($code & 0x80)) {
666
      // 0xxxxxxx
667 4
      return $code;
668
    }
669
670 4
    if (($code & 0xe0) === 0xc0) {
671
      // 110xxxxx
672 4
      $bytes = 2;
673 4
      $code &= ~0xc0;
674 4
    } elseif (($code & 0xf0) === 0xe0) {
675
      // 1110xxxx
676 4
      $bytes = 3;
677 4
      $code &= ~0xe0;
678 2
    } elseif (($code & 0xf8) === 0xf0) {
679
      // 11110xxx
680 2
      $bytes = 4;
681 2
      $code &= ~0xf0;
682
    }
683
684 4
    for ($i = 2; $i <= $bytes; $i++) {
685
      // 10xxxxxx
686 4
      $code = ($code << 6) + (self::ord($char[$i - 1]) & ~0x80);
687
    }
688
689 4
    return $code;
690
  }
691
692
  /**
693
   * Get hexadecimal code point (U+xxxx) of a UTF-8 encoded character.
694
   *
695
   * @param string|int $char <p>The input character</p>
696
   * @param string     $pfix [optional]
697
   *
698
   * @return string The code point encoded as U+xxxx
699
   */
700 2
  public static function chr_to_hex($char, string $pfix = 'U+'): string
701
  {
702 2
    if ('' === $char) {
703 2
      return '';
704
    }
705
706 2
    if ($char === '&#0;') {
707 2
      $char = '';
708
    }
709
710 2
    return self::int_to_hex(self::ord($char), $pfix);
711
  }
712
713
  /**
714
   * alias for "UTF8::chr_to_decimal()"
715
   *
716
   * @see UTF8::chr_to_decimal()
717
   *
718
   * @param string $chr
719
   *
720
   * @return int
721
   */
722 2
  public static function chr_to_int(string $chr): int
723
  {
724 2
    return self::chr_to_decimal($chr);
725
  }
726
727
  /**
728
   * Splits a string into smaller chunks and multiple lines, using the specified line ending character.
729
   *
730
   * @param string $body     <p>The original string to be split.</p>
731
   * @param int    $chunklen [optional] <p>The maximum character length of a chunk.</p>
732
   * @param string $end      [optional] <p>The character(s) to be inserted at the end of each chunk.</p>
733
   *
734
   * @return string The chunked string.
735
   */
736 4
  public static function chunk_split(string $body, int $chunklen = 76, string $end = "\r\n"): string
737
  {
738 4
    return \implode($end, self::split($body, $chunklen));
739
  }
740
741
  /**
742
   * Accepts a string and removes all non-UTF-8 characters from it + extras if needed.
743
   *
744
   * @param string $str                           <p>The string to be sanitized.</p>
745
   * @param bool   $remove_bom                    [optional] <p>Set to true, if you need to remove UTF-BOM.</p>
746
   * @param bool   $normalize_whitespace          [optional] <p>Set to true, if you need to normalize the
747
   *                                              whitespace.</p>
748
   * @param bool   $normalize_msword              [optional] <p>Set to true, if you need to normalize MS Word chars
749
   *                                              e.g.: "…"
750
   *                                              => "..."</p>
751
   * @param bool   $keep_non_breaking_space       [optional] <p>Set to true, to keep non-breaking-spaces, in
752
   *                                              combination with
753
   *                                              $normalize_whitespace</p>
754
   * @param bool   $replace_diamond_question_mark [optional] <p>Set to true, if you need to remove diamond question
755
   *                                              mark e.g.: "�"</p>
756
   * @param bool   $remove_invisible_characters   [optional] <p>Set to false, if you not want to remove invisible
757
   *                                              characters e.g.: "\0"</p>
758
   *
759
   * @return string Clean UTF-8 encoded string.
760
   */
761 112
  public static function clean(
762
      string $str,
763
      bool $remove_bom = false,
764
      bool $normalize_whitespace = false,
765
      bool $normalize_msword = false,
766
      bool $keep_non_breaking_space = false,
767
      bool $replace_diamond_question_mark = false,
768
      bool $remove_invisible_characters = true
769
  ): string
770
  {
771
    // http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string
772
    // caused connection reset problem on larger strings
773
774 112
    $regx = '/
775
      (
776
        (?: [\x00-\x7F]               # single-byte sequences   0xxxxxxx
777
        |   [\xC0-\xDF][\x80-\xBF]    # double-byte sequences   110xxxxx 10xxxxxx
778
        |   [\xE0-\xEF][\x80-\xBF]{2} # triple-byte sequences   1110xxxx 10xxxxxx * 2
779
        |   [\xF0-\xF7][\x80-\xBF]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3
780
        ){1,100}                      # ...one or more times
781
      )
782
    | ( [\x80-\xBF] )                 # invalid byte in range 10000000 - 10111111
783
    | ( [\xC0-\xFF] )                 # invalid byte in range 11000000 - 11111111
784
    /x';
785 112
    $str = (string)\preg_replace($regx, '$1', $str);
786
787 112
    if ($replace_diamond_question_mark === true) {
788 62
      $str = self::replace_diamond_question_mark($str, '');
789
    }
790
791 112
    if ($remove_invisible_characters === true) {
792 112
      $str = self::remove_invisible_characters($str);
793
    }
794
795 112
    if ($normalize_whitespace === true) {
796 66
      $str = self::normalize_whitespace($str, $keep_non_breaking_space);
797
    }
798
799 112
    if ($normalize_msword === true) {
800 34
      $str = self::normalize_msword($str);
801
    }
802
803 112
    if ($remove_bom === true) {
804 64
      $str = self::remove_bom($str);
805
    }
806
807 112
    return $str;
808
  }
809
810
  /**
811
   * Clean-up a and show only printable UTF-8 chars at the end  + fix UTF-8 encoding.
812
   *
813
   * @param string $str <p>The input string.</p>
814
   *
815
   * @return string
816
   */
817 33
  public static function cleanup($str): string
818
  {
819
    // init
820 33
    $str = (string)$str;
821
822 33
    if ('' === $str) {
823 5
      return '';
824
    }
825
826
    // fixed ISO <-> UTF-8 Errors
827 33
    $str = self::fix_simple_utf8($str);
828
829
    // remove all none UTF-8 symbols
830
    // && remove diamond question mark (�)
831
    // && remove remove invisible characters (e.g. "\0")
832
    // && remove BOM
833
    // && normalize whitespace chars (but keep non-breaking-spaces)
834 33
    $str = self::clean(
835 33
        $str,
836 33
        true,
837 33
        true,
838 33
        false,
839 33
        true,
840 33
        true,
841 33
        true
842
    );
843
844 33
    return $str;
845
  }
846
847
  /**
848
   * Accepts a string or a array of strings and returns an array of Unicode code points.
849
   *
850
   * INFO: opposite to UTF8::string()
851
   *
852
   * @param string|string[] $arg        <p>A UTF-8 encoded string or an array of such strings.</p>
853
   * @param bool            $u_style    <p>If True, will return code points in U+xxxx format,
854
   *                                    default, code points will be returned as integers.</p>
855
   *
856
   * @return array<int|string>
857
   *                           The array of code points:<br>
858
   *                           array<int> for $u_style === false<br>
859
   *                           array<string> for $u_style === true<br>
860
   */
861 12
  public static function codepoints($arg, bool $u_style = false): array
862
  {
863 12
    if (\is_string($arg) === true) {
864 12
      $arg = self::split($arg);
865
    }
866
867 12
    $arg = \array_map(
868
        [
869 12
            self::class,
870
            'ord',
871
        ],
872 12
        $arg
873
    );
874
875 12
    if (\count($arg) === 0) {
876 7
      return [];
877
    }
878
879 11
    if ($u_style) {
880 2
      $arg = \array_map(
881
          [
882 2
              self::class,
883
              'int_to_hex',
884
          ],
885 2
          $arg
886
      );
887
    }
888
889 11
    return $arg;
890
  }
891
892
  /**
893
   * Trims the string and replaces consecutive whitespace characters with a
894
   * single space. This includes tabs and newline characters, as well as
895
   * multibyte whitespace such as the thin space and ideographic space.
896
   *
897
   * @param string $str <p>The input string.</p>
898
   *
899
   * @return string String with a trimmed $str and condensed whitespace.
900
   */
901 13
  public static function collapse_whitespace(string $str): string
902
  {
903 13
    return self::trim(
904 13
        self::regex_replace($str, '[[:space:]]+', ' ')
905
    );
906
  }
907
908
  /**
909
   * Returns count of characters used in a string.
910
   *
911
   * @param string $str       <p>The input string.</p>
912
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
913
   *
914
   * @return int[] An associative array of Character as keys and
915
   *               their count as values.
916
   */
917 18
  public static function count_chars(string $str, bool $cleanUtf8 = false): array
918
  {
919 18
    return \array_count_values(self::split($str, 1, $cleanUtf8));
920
  }
921
922
  /**
923
   * Remove css media-queries.
924
   *
925
   * @param string $str
926
   *
927
   * @return string
928
   */
929 1
  public static function css_stripe_media_queries(string $str): string
930
  {
931 1
    return (string)\preg_replace(
932 1
        '#@media\\s+(?:only\\s)?(?:[\\s{\\(]|screen|all)\\s?[^{]+{.*}\\s*}\\s*#misU',
933 1
        '',
934 1
        $str
935
    );
936
  }
937
938
  /**
939
   * Checks whether ctype is available on the server.
940
   *
941
   * @return bool
942
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
943
   */
944
  public static function ctype_loaded(): bool
945
  {
946
    return \extension_loaded('ctype');
947
  }
948
949
  /**
950
   * Converts a int-value into an UTF-8 character.
951
   *
952
   * @param mixed $int
953
   *
954
   * @return string
955
   */
956 10
  public static function decimal_to_chr($int): string
957
  {
958 10
    return self::html_entity_decode('&#' . $int . ';', ENT_QUOTES | ENT_HTML5);
959
  }
960
961
  /**
962
   * Decodes a MIME header field
963
   *
964
   * @param string $str
965
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
966
   *
967
   * @return string|false
968
   *                      A decoded MIME field on success,
969
   *                      or false if an error occurs during the decoding.
970
   */
971
  public static function decode_mimeheader($str, $encoding = 'UTF-8')
972
  {
973
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
974
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
975
    }
976
977
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
978
      self::checkForSupport();
979
    }
980
981
    if (self::$SUPPORT['iconv'] === true) {
982
      return \iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $encoding);
983
    }
984
985
    if ($encoding != 'UTF-8') {
986
      $str = self::encode($encoding, $str);
987
    }
988
989
    return \mb_decode_mimeheader($str);
990
  }
991
992
  /**
993
   * Encode a string with a new charset-encoding.
994
   *
995
   * INFO:  The different to "UTF8::utf8_encode()" is that this function, try to fix also broken / double encoding,
996
   *        so you can call this function also on a UTF-8 String and you don't mess the string.
997
   *
998
   * @param string $toEncoding                  <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.</p>
999
   * @param string $str                         <p>The input string</p>
1000
   * @param bool   $autodetectFromEncoding      [optional] <p>Force the new encoding (we try to fix broken / double
1001
   *                                            encoding for UTF-8)<br> otherwise we auto-detect the current
1002
   *                                            string-encoding</p>
1003
   * @param string $fromEncoding                [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1004
   *                                            A empty string will trigger the autodetect anyway.</p>
1005
   *
1006
   * @return string
1007
   */
1008 28
  public static function encode(string $toEncoding, string $str, bool $autodetectFromEncoding = true, string $fromEncoding = ''): string
1009
  {
1010 28
    if ('' === $str || '' === $toEncoding) {
1011 12
      return $str;
1012
    }
1013
1014 28
    if ($toEncoding !== 'UTF-8' && $toEncoding !== 'CP850') {
1015 6
      $toEncoding = self::normalize_encoding($toEncoding, 'UTF-8');
1016
    }
1017
1018 28
    if ($fromEncoding && $fromEncoding !== 'UTF-8' && $fromEncoding !== 'CP850') {
1019 2
      $fromEncoding = self::normalize_encoding($fromEncoding, null);
1020
    }
1021
1022 28
    if ($toEncoding && $fromEncoding && $fromEncoding === $toEncoding) {
1023
      return $str;
1024
    }
1025
1026 28
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1027
      self::checkForSupport();
1028
    }
1029
1030 28
    if ($toEncoding === 'JSON') {
1031 1
      return self::json_encode($str);
1032
    }
1033 28
    if ($fromEncoding === 'JSON') {
1034 1
      $str = self::json_decode($str);
1035 1
      $fromEncoding = '';
1036
    }
1037
1038 28
    if ($toEncoding === 'BASE64') {
1039 2
      return base64_encode($str);
1040
    }
1041 28
    if ($fromEncoding === 'BASE64') {
1042 2
      $str = base64_decode($str);
1043 2
      $fromEncoding = '';
1044
    }
1045
1046 28
    if ($toEncoding === 'HTML-ENTITIES') {
1047 2
      return self::html_encode($str, true, 'UTF-8');
1048
    }
1049 28
    if ($fromEncoding === 'HTML-ENTITIES') {
1050 2
      $str = self::html_decode($str, ENT_COMPAT, 'UTF-8');
1051 2
      $fromEncoding = '';
1052
    }
1053
1054 28
    $fromEncodingDetected = false;
1055
    if (
1056 28
        $autodetectFromEncoding === true
1057
        ||
1058 28
        !$fromEncoding
1059
    ) {
1060 28
      $fromEncodingDetected = self::str_detect_encoding($str);
1061
    }
1062
1063
    // DEBUG
1064
    //var_dump($toEncoding, $fromEncoding, $fromEncodingDetected, $str, "\n\n");
1065
1066 28
    if ($fromEncodingDetected !== false) {
1067 24
      $fromEncoding = $fromEncodingDetected;
1068 6
    } elseif ($fromEncodingDetected === false && $autodetectFromEncoding === true) {
1069
      // fallback for the "autodetect"-mode
1070 6
      return self::to_utf8($str);
1071
    }
1072
1073
    if (
1074 24
        !$fromEncoding
1075
        ||
1076 24
        $fromEncoding === $toEncoding
1077
    ) {
1078 15
      return $str;
1079
    }
1080
1081
    if (
1082 18
        $toEncoding === 'UTF-8'
1083
        &&
1084
        (
1085 17
            $fromEncoding === 'WINDOWS-1252'
1086
            ||
1087 18
            $fromEncoding === 'ISO-8859-1'
1088
        )
1089
    ) {
1090 14
      return self::to_utf8($str);
1091
    }
1092
1093
    if (
1094 10
        $toEncoding === 'ISO-8859-1'
1095
        &&
1096
        (
1097 5
            $fromEncoding === 'WINDOWS-1252'
1098
            ||
1099 10
            $fromEncoding === 'UTF-8'
1100
        )
1101
    ) {
1102 5
      return self::to_iso8859($str);
1103
    }
1104
1105
    if (
1106 9
        $toEncoding !== 'UTF-8'
1107
        &&
1108 9
        $toEncoding !== 'ISO-8859-1'
1109
        &&
1110 9
        $toEncoding !== 'WINDOWS-1252'
1111
        &&
1112 9
        self::$SUPPORT['mbstring'] === false
1113
    ) {
1114
      \trigger_error('UTF8::encode() without mbstring cannot handle "' . $toEncoding . '" encoding', E_USER_WARNING);
1115
    }
1116
1117 9
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1118
      self::checkForSupport();
1119
    }
1120
1121 9
    if (self::$SUPPORT['mbstring'] === true) {
1122
      // info: do not use the symfony polyfill here
1123 9
      $strEncoded = \mb_convert_encoding(
1124 9
          $str,
1125 9
          $toEncoding,
1126 9
          $fromEncoding
1127
      );
1128
1129 9
      if ($strEncoded) {
1130 9
        return $strEncoded;
1131
      }
1132
    }
1133
1134
    $return = \iconv($fromEncoding, $toEncoding, $str);
1135
    if ($return !== false) {
1136
      return $return;
1137
    }
1138
1139
    return $str;
1140
  }
1141
1142
  /**
1143
   * @param string $str
1144
   * @param string $fromCharset      [optional] <p>Set the input charset.</p>
1145
   * @param string $toCharset        [optional] <p>Set the output charset.</p>
1146
   * @param string $transferEncoding [optional] <p>Set the transfer encoding.</p>
1147
   * @param string $linefeed         [optional] <p>Set the used linefeed.</p>
1148
   * @param int    $indent           [optional] <p>Set the max length indent.</p>
1149
   *
1150
   * @return string|false
1151
   *                      An encoded MIME field on success,
1152
   *                      or false if an error occurs during the encoding.
1153
   */
1154
  public static function encode_mimeheader(
1155
      $str,
1156
      $fromCharset = 'UTF-8',
1157
      $toCharset = 'UTF-8',
1158
      $transferEncoding = 'Q',
1159
      $linefeed = "\r\n",
1160
      $indent = 76
1161
  )
1162
  {
1163
    if ($fromCharset !== 'UTF-8' && $fromCharset !== 'CP850') {
1164
      $fromCharset = self::normalize_encoding($fromCharset, 'UTF-8');
1165
    }
1166
1167
    if ($toCharset !== 'UTF-8' && $toCharset !== 'CP850') {
1168
      $toCharset = self::normalize_encoding($toCharset, 'UTF-8');
1169
    }
1170
1171
    $output = \iconv_mime_encode(
1172
        '',
1173
        $str,
1174
        [
1175
            'scheme'           => $transferEncoding,
1176
            'line-length'      => $indent,
1177
            'input-charset'    => $fromCharset,
1178
            'output-charset'   => $toCharset,
1179
            'line-break-chars' => $linefeed,
1180
        ]
1181
    );
1182
1183
    return $output;
1184
  }
1185
1186
  /**
1187
   * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1188
   *
1189
   * @param string   $str                    <p>The input string.</p>
1190
   * @param string   $search                 <p>The searched string.</p>
1191
   * @param int|null $length                 [optional] <p>Default: null === text->length / 2</p>
1192
   * @param string   $replacerForSkippedText [optional] <p>Default: …</p>
1193
   * @param string   $encoding               [optional] <p>Set the charset for e.g. "mb_" function</p>
1194
   *
1195
   * @return string
1196
   */
1197 1
  public static function extract_text(string $str, string $search = '', int $length = null, string $replacerForSkippedText = '…', string $encoding = 'UTF-8'): string
1198
  {
1199 1
    if ('' === $str) {
1200 1
      return '';
1201
    }
1202
1203 1
    $trimChars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
1204
1205 1
    if ($length === null) {
1206 1
      $length = (int)\round(self::strlen($str, $encoding) / 2, 0);
1207
    }
1208
1209 1
    if (empty($search)) {
1210
1211 1
      $stringLength = self::strlen($str, $encoding);
1212
1213 1
      if ($length > 0) {
1214 1
        $end = ($length - 1) > $stringLength ? $stringLength : ($length - 1);
1215
      } else {
1216 1
        $end = 0;
1217
      }
1218
1219 1
      $pos = (int)\min(
1220 1
          self::strpos($str, ' ', $end, $encoding),
0 ignored issues
show
Bug introduced by
It seems like $end can also be of type false; however, parameter $offset of voku\helper\UTF8::strpos() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1220
          self::strpos($str, ' ', /** @scrutinizer ignore-type */ $end, $encoding),
Loading history...
1221 1
          self::strpos($str, '.', $end, $encoding)
1222
      );
1223
1224 1
      if ($pos) {
1225 1
        $strSub = self::substr($str, 0, $pos, $encoding);
1226 1
        if ($strSub === false) {
1227
          return '';
1228
        }
1229
1230 1
        return \rtrim($strSub, $trimChars) . $replacerForSkippedText;
1231
      }
1232
1233
      return $str;
1234
    }
1235
1236 1
    $wordPos = self::stripos($str, $search, 0, $encoding);
1237 1
    $halfSide = (int)($wordPos - $length / 2 + self::strlen($search, $encoding) / 2);
1238
1239 1
    $pos_start = 0;
1240 1
    if ($halfSide > 0) {
1241 1
      $halfText = self::substr($str, 0, $halfSide, $encoding);
1242 1
      if ($halfText !== false) {
1243 1
        $pos_start = (int)\max(
1244 1
            self::strrpos($halfText, ' ', 0, $encoding),
1245 1
            self::strrpos($halfText, '.', 0, $encoding)
1246
        );
1247
      }
1248
    }
1249
1250 1
    if ($wordPos && $halfSide > 0) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $wordPos of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1251 1
      $l = $pos_start + $length - 1;
1252 1
      $realLength = self::strlen($str, $encoding);
1253
1254 1
      if ($l > $realLength) {
1255
        $l = $realLength;
1256
      }
1257
1258 1
      $pos_end = (int)\min(
1259 1
              self::strpos($str, ' ', $l, $encoding),
1260 1
              self::strpos($str, '.', $l, $encoding)
1261 1
          ) - $pos_start;
1262
1263 1
      if (!$pos_end || $pos_end <= 0) {
1264 1
        $strSub = self::substr($str, $pos_start, self::strlen($str), $encoding);
0 ignored issues
show
Bug introduced by
It seems like self::strlen($str) can also be of type false; however, parameter $length of voku\helper\UTF8::substr() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1264
        $strSub = self::substr($str, $pos_start, /** @scrutinizer ignore-type */ self::strlen($str), $encoding);
Loading history...
1265 1
        if ($strSub !== false) {
1266 1
          $extract = $replacerForSkippedText . \ltrim($strSub, $trimChars);
1267
        } else {
1268 1
          $extract = '';
1269
        }
1270
      } else {
1271 1
        $strSub = self::substr($str, $pos_start, $pos_end, $encoding);
1272 1
        if ($strSub !== false) {
1273 1
          $extract = $replacerForSkippedText . \trim($strSub, $trimChars) . $replacerForSkippedText;
1274
        } else {
1275 1
          $extract = '';
1276
        }
1277
      }
1278
1279
    } else {
1280
1281 1
      $l = $length - 1;
1282 1
      $trueLength = self::strlen($str, $encoding);
1283
1284 1
      if ($l > $trueLength) {
1285
        $l = $trueLength;
1286
      }
1287
1288 1
      $pos_end = \min(
1289 1
          self::strpos($str, ' ', $l, $encoding),
1290 1
          self::strpos($str, '.', $l, $encoding)
1291
      );
1292
1293 1
      if ($pos_end) {
1294 1
        $strSub = self::substr($str, 0, $pos_end, $encoding);
1295 1
        if ($strSub !== false) {
1296 1
          $extract = \rtrim($strSub, $trimChars) . $replacerForSkippedText;
1297
        } else {
1298 1
          $extract = '';
1299
        }
1300
      } else {
1301 1
        $extract = $str;
1302
      }
1303
    }
1304
1305 1
    return $extract;
1306
  }
1307
1308
  /**
1309
   * Reads entire file into a string.
1310
   *
1311
   * WARNING: do not use UTF-8 Option ($convertToUtf8) for binary-files (e.g.: images) !!!
1312
   *
1313
   * @link http://php.net/manual/en/function.file-get-contents.php
1314
   *
1315
   * @param string        $filename             <p>
1316
   *                                            Name of the file to read.
1317
   *                                            </p>
1318
   * @param bool          $use_include_path     [optional] <p>
1319
   *                                            Prior to PHP 5, this parameter is called
1320
   *                                            use_include_path and is a bool.
1321
   *                                            As of PHP 5 the FILE_USE_INCLUDE_PATH can be used
1322
   *                                            to trigger include path
1323
   *                                            search.
1324
   *                                            </p>
1325
   * @param resource|null $context              [optional] <p>
1326
   *                                            A valid context resource created with
1327
   *                                            stream_context_create. If you don't need to use a
1328
   *                                            custom context, you can skip this parameter by &null;.
1329
   *                                            </p>
1330
   * @param int|null      $offset               [optional] <p>
1331
   *                                            The offset where the reading starts.
1332
   *                                            </p>
1333
   * @param int|null      $maxLength            [optional] <p>
1334
   *                                            Maximum length of data read. The default is to read until end
1335
   *                                            of file is reached.
1336
   *                                            </p>
1337
   * @param int           $timeout              <p>The time in seconds for the timeout.</p>
1338
   *
1339
   * @param bool          $convertToUtf8        <strong>WARNING!!!</strong> <p>Maybe you can't use this option for some
1340
   *                                            files, because they used non default utf-8 chars. Binary files like
1341
   *                                            images or pdf will not be converted.</p>
1342
   * @param string        $fromEncoding         [optional] <p>e.g. 'UTF-16', 'UTF-8', 'ISO-8859-1', etc.<br>
1343
   *                                            A empty string will trigger the autodetect anyway.</p>
1344
   *
1345
   * @return string|false The function returns the read data or false on failure.
1346
   */
1347 11
  public static function file_get_contents(
1348
      string $filename,
1349
      bool $use_include_path = false,
1350
      $context = null,
1351
      int $offset = null,
1352
      int $maxLength = null,
1353
      int $timeout = 10,
1354
      bool $convertToUtf8 = true,
1355
      string $fromEncoding = ''
1356
  )
1357
  {
1358
    // init
1359 11
    $filename = \filter_var($filename, FILTER_SANITIZE_STRING);
1360
1361 11
    if ($timeout && $context === null) {
1362 9
      $context = \stream_context_create(
1363
          [
1364
              'http' =>
1365
                  [
1366 9
                      'timeout' => $timeout,
1367
                  ],
1368
          ]
1369
      );
1370
    }
1371
1372 11
    if ($offset === null) {
1373 11
      $offset = 0;
1374
    }
1375
1376 11
    if (\is_int($maxLength) === true) {
1377 2
      $data = \file_get_contents($filename, $use_include_path, $context, $offset, $maxLength);
1378
    } else {
1379 11
      $data = \file_get_contents($filename, $use_include_path, $context, $offset);
1380
    }
1381
1382
    // return false on error
1383 11
    if ($data === false) {
1384
      return false;
1385
    }
1386
1387 11
    if ($convertToUtf8 === true) {
1388
      if (
1389 11
          self::is_binary($data, true) === true
1390
          &&
1391 11
          self::is_utf16($data, false) === false
1392
          &&
1393 11
          self::is_utf32($data, false) === false
1394 6
      ) {
1395
        // do nothing, it's binary and not UTF16 or UTF32
1396
      } else {
1397
1398 9
        $data = self::encode('UTF-8', $data, false, $fromEncoding);
1399 9
        $data = self::cleanup($data);
1400
1401
      }
1402
    }
1403
1404 11
    return $data;
1405
  }
1406
1407
  /**
1408
   * Checks if a file starts with BOM (Byte Order Mark) character.
1409
   *
1410
   * @param string $file_path <p>Path to a valid file.</p>
1411
   *
1412
   * @throws \RuntimeException if file_get_contents() returned false
1413
   *
1414
   * @return bool
1415
   *              <strong>true</strong> if the file has BOM at the start, <strong>false</strong> otherwise.
1416
   */
1417 2
  public static function file_has_bom(string $file_path): bool
1418
  {
1419 2
    $file_content = \file_get_contents($file_path);
1420 2
    if ($file_content === false) {
1421
      throw new \RuntimeException('file_get_contents() returned false for:' . $file_path);
1422
    }
1423
1424 2
    return self::string_has_bom($file_content);
1425
  }
1426
1427
  /**
1428
   * Normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1429
   *
1430
   * @param mixed  $var
1431
   * @param int    $normalization_form
1432
   * @param string $leading_combining
1433
   *
1434
   * @return mixed
1435
   */
1436 43
  public static function filter($var, int $normalization_form = 4 /* n::NFC */, string $leading_combining = '◌')
1437
  {
1438 43
    switch (\gettype($var)) {
1439 43
      case 'array':
1440 6
        foreach ($var as $k => $v) {
1441
          /** @noinspection AlterInForeachInspection */
1442 6
          $var[$k] = self::filter($v, $normalization_form, $leading_combining);
1443
        }
1444 6
        break;
1445 43
      case 'object':
1446 4
        foreach ($var as $k => $v) {
1447 4
          $var->{$k} = self::filter($v, $normalization_form, $leading_combining);
1448
        }
1449 4
        break;
1450 43
      case 'string':
1451
1452 43
        if (false !== \strpos($var, "\r")) {
1453
          // Workaround https://bugs.php.net/65732
1454 3
          $var = self::normalize_line_ending($var);
1455
        }
1456
1457 43
        if (self::is_ascii($var) === false) {
1458
          /** @noinspection PhpUndefinedClassInspection */
1459 26
          if (\Normalizer::isNormalized($var, $normalization_form)) {
1460 21
            $n = '-';
1461
          } else {
1462
            /** @noinspection PhpUndefinedClassInspection */
1463 13
            $n = \Normalizer::normalize($var, $normalization_form);
1464
1465 13
            if (isset($n[0])) {
1466 7
              $var = $n;
1467
            } else {
1468 9
              $var = self::encode('UTF-8', $var, true);
1469
            }
1470
          }
1471
1472
          if (
1473 26
              $var[0] >= "\x80"
1474
              &&
1475 26
              isset($n[0], $leading_combining[0])
1476
              &&
1477 26
              \preg_match('/^\p{Mn}/u', $var)
1478
          ) {
1479
            // Prevent leading combining chars
1480
            // for NFC-safe concatenations.
1481 3
            $var = $leading_combining . $var;
1482
          }
1483
        }
1484
1485 43
        break;
1486
    }
1487
1488 43
    return $var;
1489
  }
1490
1491
  /**
1492
   * "filter_input()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1493
   *
1494
   * Gets a specific external variable by name and optionally filters it
1495
   *
1496
   * @link  http://php.net/manual/en/function.filter-input.php
1497
   *
1498
   * @param int    $type          <p>
1499
   *                              One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1500
   *                              <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1501
   *                              <b>INPUT_ENV</b>.
1502
   *                              </p>
1503
   * @param string $variable_name <p>
1504
   *                              Name of a variable to get.
1505
   *                              </p>
1506
   * @param int    $filter        [optional] <p>
1507
   *                              The ID of the filter to apply. The
1508
   *                              manual page lists the available filters.
1509
   *                              </p>
1510
   * @param mixed  $options       [optional] <p>
1511
   *                              Associative array of options or bitwise disjunction of flags. If filter
1512
   *                              accepts options, flags can be provided in "flags" field of array.
1513
   *                              </p>
1514
   *
1515
   * @return mixed Value of the requested variable on success, <b>FALSE</b> if the filter fails, or <b>NULL</b> if the
1516
   *               <i>variable_name</i> variable is not set. If the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it
1517
   *               returns <b>FALSE</b> if the variable is not set and <b>NULL</b> if the filter fails.
1518
   */
1519
  public static function filter_input(int $type, string $variable_name, int $filter = FILTER_DEFAULT, $options = null)
1520
  {
1521
    if (4 > \func_num_args()) {
1522
      $var = \filter_input($type, $variable_name, $filter);
1523
    } else {
1524
      $var = \filter_input($type, $variable_name, $filter, $options);
1525
    }
1526
1527
    return self::filter($var);
1528
  }
1529
1530
  /**
1531
   * "filter_input_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1532
   *
1533
   * Gets external variables and optionally filters them
1534
   *
1535
   * @link  http://php.net/manual/en/function.filter-input-array.php
1536
   *
1537
   * @param int   $type       <p>
1538
   *                          One of <b>INPUT_GET</b>, <b>INPUT_POST</b>,
1539
   *                          <b>INPUT_COOKIE</b>, <b>INPUT_SERVER</b>, or
1540
   *                          <b>INPUT_ENV</b>.
1541
   *                          </p>
1542
   * @param mixed $definition [optional] <p>
1543
   *                          An array defining the arguments. A valid key is a string
1544
   *                          containing a variable name and a valid value is either a filter type, or an array
1545
   *                          optionally specifying the filter, flags and options. If the value is an
1546
   *                          array, valid keys are filter which specifies the
1547
   *                          filter type,
1548
   *                          flags which specifies any flags that apply to the
1549
   *                          filter, and options which specifies any options that
1550
   *                          apply to the filter. See the example below for a better understanding.
1551
   *                          </p>
1552
   *                          <p>
1553
   *                          This parameter can be also an integer holding a filter constant. Then all values in the
1554
   *                          input array are filtered by this filter.
1555
   *                          </p>
1556
   * @param bool  $add_empty  [optional] <p>
1557
   *                          Add missing keys as <b>NULL</b> to the return value.
1558
   *                          </p>
1559
   *
1560
   * @return mixed An array containing the values of the requested variables on success, or <b>FALSE</b> on failure. An
1561
   *               array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not set. Or
1562
   *               if the flag <b>FILTER_NULL_ON_FAILURE</b> is used, it returns <b>FALSE</b> if the variable is not
1563
   *               set and <b>NULL</b> if the filter fails.
1564
   */
1565
  public static function filter_input_array(int $type, $definition = null, bool $add_empty = true)
1566
  {
1567
    if (2 > \func_num_args()) {
1568
      $a = \filter_input_array($type);
1569
    } else {
1570
      $a = \filter_input_array($type, $definition, $add_empty);
1571
    }
1572
1573
    return self::filter($a);
1574
  }
1575
1576
  /**
1577
   * "filter_var()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1578
   *
1579
   * Filters a variable with a specified filter
1580
   *
1581
   * @link  http://php.net/manual/en/function.filter-var.php
1582
   *
1583
   * @param mixed $variable <p>
1584
   *                        Value to filter.
1585
   *                        </p>
1586
   * @param int   $filter   [optional] <p>
1587
   *                        The ID of the filter to apply. The
1588
   *                        manual page lists the available filters.
1589
   *                        </p>
1590
   * @param mixed $options  [optional] <p>
1591
   *                        Associative array of options or bitwise disjunction of flags. If filter
1592
   *                        accepts options, flags can be provided in "flags" field of array. For
1593
   *                        the "callback" filter, callable type should be passed. The
1594
   *                        callback must accept one argument, the value to be filtered, and return
1595
   *                        the value after filtering/sanitizing it.
1596
   *                        </p>
1597
   *                        <p>
1598
   *                        <code>
1599
   *                        // for filters that accept options, use this format
1600
   *                        $options = array(
1601
   *                        'options' => array(
1602
   *                        'default' => 3, // value to return if the filter fails
1603
   *                        // other options here
1604
   *                        'min_range' => 0
1605
   *                        ),
1606
   *                        'flags' => FILTER_FLAG_ALLOW_OCTAL,
1607
   *                        );
1608
   *                        $var = filter_var('0755', FILTER_VALIDATE_INT, $options);
1609
   *                        // for filter that only accept flags, you can pass them directly
1610
   *                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
1611
   *                        // for filter that only accept flags, you can also pass as an array
1612
   *                        $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,
1613
   *                        array('flags' => FILTER_NULL_ON_FAILURE));
1614
   *                        // callback validate filter
1615
   *                        function foo($value)
1616
   *                        {
1617
   *                        // Expected format: Surname, GivenNames
1618
   *                        if (strpos($value, ", ") === false) return false;
1619
   *                        list($surname, $givennames) = explode(", ", $value, 2);
1620
   *                        $empty = (empty($surname) || empty($givennames));
1621
   *                        $notstrings = (!is_string($surname) || !is_string($givennames));
1622
   *                        if ($empty || $notstrings) {
1623
   *                        return false;
1624
   *                        } else {
1625
   *                        return $value;
1626
   *                        }
1627
   *                        }
1628
   *                        $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo'));
1629
   *                        </code>
1630
   *                        </p>
1631
   *
1632
   * @return mixed the filtered data, or <b>FALSE</b> if the filter fails.
1633
   */
1634 2
  public static function filter_var($variable, int $filter = FILTER_DEFAULT, $options = null)
1635
  {
1636 2
    if (3 > \func_num_args()) {
1637 2
      $variable = \filter_var($variable, $filter);
1638
    } else {
1639 2
      $variable = \filter_var($variable, $filter, $options);
1640
    }
1641
1642 2
    return self::filter($variable);
1643
  }
1644
1645
  /**
1646
   * "filter_var_array()"-wrapper with normalizes to UTF-8 NFC, converting from WINDOWS-1252 when needed.
1647
   *
1648
   * Gets multiple variables and optionally filters them
1649
   *
1650
   * @link  http://php.net/manual/en/function.filter-var-array.php
1651
   *
1652
   * @param array $data       <p>
1653
   *                          An array with string keys containing the data to filter.
1654
   *                          </p>
1655
   * @param mixed $definition [optional] <p>
1656
   *                          An array defining the arguments. A valid key is a string
1657
   *                          containing a variable name and a valid value is either a
1658
   *                          filter type, or an
1659
   *                          array optionally specifying the filter, flags and options.
1660
   *                          If the value is an array, valid keys are filter
1661
   *                          which specifies the filter type,
1662
   *                          flags which specifies any flags that apply to the
1663
   *                          filter, and options which specifies any options that
1664
   *                          apply to the filter. See the example below for a better understanding.
1665
   *                          </p>
1666
   *                          <p>
1667
   *                          This parameter can be also an integer holding a filter constant. Then all values in the
1668
   *                          input array are filtered by this filter.
1669
   *                          </p>
1670
   * @param bool  $add_empty  [optional] <p>
1671
   *                          Add missing keys as <b>NULL</b> to the return value.
1672
   *                          </p>
1673
   *
1674
   * @return mixed An array containing the values of the requested variables on success, or <b>FALSE</b> on failure. An
1675
   *               array value will be <b>FALSE</b> if the filter fails, or <b>NULL</b> if the variable is not set.
1676
   */
1677 2
  public static function filter_var_array(array $data, $definition = null, bool $add_empty = true)
1678
  {
1679 2
    if (2 > \func_num_args()) {
1680 2
      $a = \filter_var_array($data);
1681
    } else {
1682 2
      $a = \filter_var_array($data, $definition, $add_empty);
1683
    }
1684
1685 2
    return self::filter($a);
1686
  }
1687
1688
  /**
1689
   * Checks whether finfo is available on the server.
1690
   *
1691
   * @return bool
1692
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
1693
   */
1694
  public static function finfo_loaded(): bool
1695
  {
1696
    return \class_exists('finfo');
1697
  }
1698
1699
  /**
1700
   * Returns the first $n characters of the string.
1701
   *
1702
   * @param string $str      <p>The input string.</p>
1703
   * @param int    $n        <p>Number of characters to retrieve from the start.</p>
1704
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
1705
   *
1706
   * @return string
1707
   */
1708 13
  public static function first_char(string $str, int $n = 1, string $encoding = 'UTF-8'): string
1709
  {
1710 13
    if ($n <= 0) {
1711 4
      return '';
1712
    }
1713
1714 9
    $strSub = self::substr($str, 0, $n, $encoding);
1715 9
    if ($strSub === false) {
1716
      return '';
1717
    }
1718
1719 9
    return $strSub;
1720
  }
1721
1722
  /**
1723
   * Check if the number of unicode characters are not more than the specified integer.
1724
   *
1725
   * @param string $str      The original string to be checked.
1726
   * @param int    $box_size The size in number of chars to be checked against string.
1727
   *
1728
   * @return bool true if string is less than or equal to $box_size, false otherwise.
1729
   */
1730 2
  public static function fits_inside(string $str, int $box_size): bool
1731
  {
1732 2
    return (self::strlen($str) <= $box_size);
1733
  }
1734
1735
  /**
1736
   * @param string $str
1737
   * @param bool   $useLower     <p>Use uppercase by default, otherwise use lowecase.</p>
1738
   * @param bool   $fullCaseFold <p>Convert not only common cases.</p>
1739
   *
1740
   * @return string
1741
   */
1742 54
  private static function fixStrCaseHelper(string $str, $useLower = false, $fullCaseFold = false): string
1743
  {
1744 54
    $upper = self::$COMMON_CASE_FOLD['upper'];
1745 54
    $lower = self::$COMMON_CASE_FOLD['lower'];
1746
1747 54
    if ($useLower === true) {
1748 2
      $str = (string)\str_replace(
1749 2
          $upper,
1750 2
          $lower,
1751 2
          $str
1752
      );
1753
    } else {
1754 52
      $str = (string)\str_replace(
1755 52
          $lower,
1756 52
          $upper,
1757 52
          $str
1758
      );
1759
    }
1760
1761 54
    if ($fullCaseFold) {
1762
1763 52
      static $FULL_CASE_FOLD = null;
1764 52
      if ($FULL_CASE_FOLD === null) {
1765 1
        $FULL_CASE_FOLD = self::getData('caseFolding_full');
1766
      }
1767
1768 52
      if ($useLower === true) {
1769 2
        $str = (string)\str_replace($FULL_CASE_FOLD[0], $FULL_CASE_FOLD[1], $str);
1770
      } else {
1771 50
        $str = (string)\str_replace($FULL_CASE_FOLD[1], $FULL_CASE_FOLD[0], $str);
1772
      }
1773
    }
1774
1775 54
    return $str;
1776
  }
1777
1778
  /**
1779
   * Try to fix simple broken UTF-8 strings.
1780
   *
1781
   * INFO: Take a look at "UTF8::fix_utf8()" if you need a more advanced fix for broken UTF-8 strings.
1782
   *
1783
   * If you received an UTF-8 string that was converted from Windows-1252 as it was ISO-8859-1
1784
   * (ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
1785
   * See: http://en.wikipedia.org/wiki/Windows-1252
1786
   *
1787
   * @param string $str <p>The input string</p>
1788
   *
1789
   * @return string
1790
   */
1791 42
  public static function fix_simple_utf8(string $str): string
1792
  {
1793 42
    if ('' === $str) {
1794 4
      return '';
1795
    }
1796
1797 42
    static $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = null;
1798 42
    static $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = null;
1799
1800 42
    if ($BROKEN_UTF8_TO_UTF8_KEYS_CACHE === null) {
1801
1802 1
      if (self::$BROKEN_UTF8_FIX === null) {
1803 1
        self::$BROKEN_UTF8_FIX = self::getData('utf8_fix');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('utf8_fix') can also be of type false. However, the property $BROKEN_UTF8_FIX is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1804
      }
1805
1806 1
      $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(self::$BROKEN_UTF8_FIX);
0 ignored issues
show
Bug introduced by
It seems like self::BROKEN_UTF8_FIX can also be of type false; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1806
      $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$BROKEN_UTF8_FIX);
Loading history...
1807 1
      $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = \array_values(self::$BROKEN_UTF8_FIX);
0 ignored issues
show
Bug introduced by
It seems like self::BROKEN_UTF8_FIX can also be of type false; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1807
      $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$BROKEN_UTF8_FIX);
Loading history...
1808
    }
1809
1810 42
    return \str_replace($BROKEN_UTF8_TO_UTF8_KEYS_CACHE, $BROKEN_UTF8_TO_UTF8_VALUES_CACHE, $str);
1811
  }
1812
1813
  /**
1814
   * Fix a double (or multiple) encoded UTF8 string.
1815
   *
1816
   * @param string[]|string $str You can use a string or an array of strings.
1817
   *
1818
   * @return string[]|string
1819
   *                          Will return the fixed input-"array" or
1820
   *                          the fixed input-"string".
1821
   */
1822 2
  public static function fix_utf8($str)
1823
  {
1824 2
    if (\is_array($str) === true) {
1825 2
      foreach ($str as $k => $v) {
1826 2
        $str[$k] = self::fix_utf8($v);
1827
      }
1828
1829 2
      return $str;
1830
    }
1831
1832 2
    $str = (string)$str;
1833 2
    $last = '';
1834 2
    while ($last !== $str) {
1835 2
      $last = $str;
1836 2
      $str = self::to_utf8(
1837 2
          self::utf8_decode($str, true)
1838
      );
1839
    }
1840
1841 2
    return $str;
1842
  }
1843
1844
  /**
1845
   * Get character of a specific character.
1846
   *
1847
   * @param string $char
1848
   *
1849
   * @return string 'RTL' or 'LTR'
1850
   */
1851 2
  public static function getCharDirection(string $char): string
1852
  {
1853 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1854
      self::checkForSupport();
1855
    }
1856
1857 2
    if (self::$SUPPORT['intlChar'] === true) {
1858
      /** @noinspection PhpComposerExtensionStubsInspection */
1859 2
      $tmpReturn = \IntlChar::charDirection($char);
1860
1861
      // from "IntlChar"-Class
1862
      $charDirection = [
1863 2
          'RTL' => [1, 13, 14, 15, 21],
1864
          'LTR' => [0, 11, 12, 20],
1865
      ];
1866
1867 2
      if (\in_array($tmpReturn, $charDirection['LTR'], true)) {
1868
        return 'LTR';
1869
      }
1870
1871 2
      if (\in_array($tmpReturn, $charDirection['RTL'], true)) {
1872 2
        return 'RTL';
1873
      }
1874
    }
1875
1876 2
    $c = static::chr_to_decimal($char);
1877
1878 2
    if (!(0x5be <= $c && 0x10b7f >= $c)) {
1879 2
      return 'LTR';
1880
    }
1881
1882 2
    if (0x85e >= $c) {
1883
1884 2
      if (0x5be === $c ||
1885 2
          0x5c0 === $c ||
1886 2
          0x5c3 === $c ||
1887 2
          0x5c6 === $c ||
1888 2
          (0x5d0 <= $c && 0x5ea >= $c) ||
1889 2
          (0x5f0 <= $c && 0x5f4 >= $c) ||
1890 2
          0x608 === $c ||
1891 2
          0x60b === $c ||
1892 2
          0x60d === $c ||
1893 2
          0x61b === $c ||
1894 2
          (0x61e <= $c && 0x64a >= $c) ||
1895
          (0x66d <= $c && 0x66f >= $c) ||
1896
          (0x671 <= $c && 0x6d5 >= $c) ||
1897
          (0x6e5 <= $c && 0x6e6 >= $c) ||
1898
          (0x6ee <= $c && 0x6ef >= $c) ||
1899
          (0x6fa <= $c && 0x70d >= $c) ||
1900
          0x710 === $c ||
1901
          (0x712 <= $c && 0x72f >= $c) ||
1902
          (0x74d <= $c && 0x7a5 >= $c) ||
1903
          0x7b1 === $c ||
1904
          (0x7c0 <= $c && 0x7ea >= $c) ||
1905
          (0x7f4 <= $c && 0x7f5 >= $c) ||
1906
          0x7fa === $c ||
1907
          (0x800 <= $c && 0x815 >= $c) ||
1908
          0x81a === $c ||
1909
          0x824 === $c ||
1910
          0x828 === $c ||
1911
          (0x830 <= $c && 0x83e >= $c) ||
1912
          (0x840 <= $c && 0x858 >= $c) ||
1913 2
          0x85e === $c
1914
      ) {
1915 2
        return 'RTL';
1916
      }
1917
1918 2
    } elseif (0x200f === $c) {
1919
1920
      return 'RTL';
1921
1922 2
    } elseif (0xfb1d <= $c) {
1923
1924 2
      if (0xfb1d === $c ||
1925 2
          (0xfb1f <= $c && 0xfb28 >= $c) ||
1926 2
          (0xfb2a <= $c && 0xfb36 >= $c) ||
1927 2
          (0xfb38 <= $c && 0xfb3c >= $c) ||
1928 2
          0xfb3e === $c ||
1929 2
          (0xfb40 <= $c && 0xfb41 >= $c) ||
1930 2
          (0xfb43 <= $c && 0xfb44 >= $c) ||
1931 2
          (0xfb46 <= $c && 0xfbc1 >= $c) ||
1932 2
          (0xfbd3 <= $c && 0xfd3d >= $c) ||
1933 2
          (0xfd50 <= $c && 0xfd8f >= $c) ||
1934 2
          (0xfd92 <= $c && 0xfdc7 >= $c) ||
1935 2
          (0xfdf0 <= $c && 0xfdfc >= $c) ||
1936 2
          (0xfe70 <= $c && 0xfe74 >= $c) ||
1937 2
          (0xfe76 <= $c && 0xfefc >= $c) ||
1938 2
          (0x10800 <= $c && 0x10805 >= $c) ||
1939 2
          0x10808 === $c ||
1940 2
          (0x1080a <= $c && 0x10835 >= $c) ||
1941 2
          (0x10837 <= $c && 0x10838 >= $c) ||
1942 2
          0x1083c === $c ||
1943 2
          (0x1083f <= $c && 0x10855 >= $c) ||
1944 2
          (0x10857 <= $c && 0x1085f >= $c) ||
1945 2
          (0x10900 <= $c && 0x1091b >= $c) ||
1946 2
          (0x10920 <= $c && 0x10939 >= $c) ||
1947 2
          0x1093f === $c ||
1948 2
          0x10a00 === $c ||
1949 2
          (0x10a10 <= $c && 0x10a13 >= $c) ||
1950 2
          (0x10a15 <= $c && 0x10a17 >= $c) ||
1951 2
          (0x10a19 <= $c && 0x10a33 >= $c) ||
1952 2
          (0x10a40 <= $c && 0x10a47 >= $c) ||
1953 2
          (0x10a50 <= $c && 0x10a58 >= $c) ||
1954 2
          (0x10a60 <= $c && 0x10a7f >= $c) ||
1955 2
          (0x10b00 <= $c && 0x10b35 >= $c) ||
1956 2
          (0x10b40 <= $c && 0x10b55 >= $c) ||
1957 2
          (0x10b58 <= $c && 0x10b72 >= $c) ||
1958 2
          (0x10b78 <= $c && 0x10b7f >= $c)
1959
      ) {
1960 2
        return 'RTL';
1961
      }
1962
    }
1963
1964 2
    return 'LTR';
1965
  }
1966
1967
  /**
1968
   * get data from "/data/*.ser"
1969
   *
1970
   * @param string $file
1971
   *
1972
   * @return mixed|false Will return false on error.
1973
   */
1974 13
  private static function getData(string $file)
1975
  {
1976 13
    $file = __DIR__ . '/data/' . $file . '.php';
1977 13
    if (\file_exists($file)) {
1978
      /** @noinspection PhpIncludeInspection */
1979 12
      return require $file;
1980
    }
1981
1982 2
    return false;
1983
  }
1984
1985
  /**
1986
   * Check for php-support.
1987
   *
1988
   * @param string|null $key
1989
   *
1990
   * @return mixed
1991
   *               Return the full support-"array", if $key === null<br>
1992
   *               return bool-value, if $key is used and available<br>
1993
   *               otherwise return <strong>null</strong>.
1994
   */
1995 26
  public static function getSupportInfo(string $key = null)
1996
  {
1997 26
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1998
      self::checkForSupport();
1999
    }
2000
2001 26
    if ($key === null) {
2002 4
      return self::$SUPPORT;
2003
    }
2004
2005 24
    if (!isset(self::$SUPPORT[$key])) {
2006 2
      return null;
2007
    }
2008
2009 22
    return self::$SUPPORT[$key];
2010
  }
2011
2012
  /**
2013
   * @param string $str
2014
   * @param array  $fallback with this keys: 'ext', 'mime', 'type'
2015
   *
2016
   * @return array
2017
   *               with this keys: 'ext', 'mime', 'type'
2018
   */
2019 38
  private static function get_file_type(
2020
      string $str,
2021
      array $fallback = [
2022
          'ext'  => null,
2023
          'mime' => 'application/octet-stream',
2024
          'type' => null,
2025
      ]
2026
  ): array
2027
  {
2028 38
    if ($str === '') {
2029
      return $fallback;
2030
    }
2031
2032 38
    $str_info = self::substr_in_byte($str, 0, 2);
2033 38
    if (self::strlen_in_byte($str_info) !== 2) {
2034 10
      return $fallback;
2035
    }
2036
2037 34
    $str_info = \unpack('C2chars', $str_info);
2038 34
    $type_code = (int)($str_info['chars1'] . $str_info['chars2']);
2039
2040
    // DEBUG
2041
    //var_dump($type_code);
2042
2043
    switch ($type_code) {
2044 34
      case 3780:
2045 4
        $ext = 'pdf';
2046 4
        $mime = 'application/pdf';
2047 4
        $type = 'binary';
2048
2049 4
        break;
2050 34
      case 7790:
2051
        $ext = 'exe';
2052
        $mime = 'application/octet-stream';
2053
        $type = 'binary';
2054
2055
        break;
2056 34
      case 7784:
2057
        $ext = 'midi';
2058
        $mime = 'audio/x-midi';
2059
        $type = 'binary';
2060
2061
        break;
2062 34
      case 8075:
2063 6
        $ext = 'zip';
2064 6
        $mime = 'application/zip';
2065 6
        $type = 'binary';
2066
2067 6
        break;
2068 34
      case 8297:
2069
        $ext = 'rar';
2070
        $mime = 'application/rar';
2071
        $type = 'binary';
2072
2073
        break;
2074 34
      case 255216:
2075
        $ext = 'jpg';
2076
        $mime = 'image/jpeg';
2077
        $type = 'binary';
2078
2079
        break;
2080 34
      case 7173:
2081
        $ext = 'gif';
2082
        $mime = 'image/gif';
2083
        $type = 'binary';
2084
2085
        break;
2086 34
      case 6677:
2087
        $ext = 'bmp';
2088
        $mime = 'image/bmp';
2089
        $type = 'binary';
2090
2091
        break;
2092 34
      case 13780:
2093 6
        $ext = 'png';
2094 6
        $mime = 'image/png';
2095 6
        $type = 'binary';
2096
2097 6
        break;
2098
      default:
2099 32
        return $fallback;
2100
    }
2101
2102
    return [
2103 6
        'ext'  => $ext,
2104 6
        'mime' => $mime,
2105 6
        'type' => $type,
2106
    ];
2107
  }
2108
2109
  /**
2110
   * @param int    $length        <p>Length of the random string.</p>
2111
   * @param string $possibleChars [optional] <p>Characters string for the random selection.</p>
2112
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
2113
   *
2114
   * @return string
2115
   */
2116 1
  public static function get_random_string(int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', string $encoding = 'UTF-8'): string
2117
  {
2118
    // init
2119 1
    $i = 0;
2120 1
    $str = '';
2121 1
    $maxlength = self::strlen($possibleChars, $encoding);
2122
2123 1
    if ($maxlength === 0) {
2124 1
      return '';
2125
    }
2126
2127
    // add random chars
2128 1
    while ($i < $length) {
2129
      try {
2130 1
        $randInt = \random_int(0, $maxlength - 1);
2131
      } catch (\Exception $e) {
2132
        /** @noinspection RandomApiMigrationInspection */
2133
        $randInt = \mt_rand(0, $maxlength - 1);
2134
      }
2135 1
      $char = self::substr($possibleChars, $randInt, 1, $encoding);
2136 1
      $str .= $char;
2137 1
      $i++;
2138
    }
2139
2140 1
    return $str;
2141
  }
2142
2143
  /**
2144
   * @param string|int $entropyExtra [optional] <p>Extra entropy via a string or int value.</p>
2145
   * @param bool       $md5          [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
2146
   *
2147
   * @return string
2148
   */
2149 1
  public static function get_unique_string($entropyExtra = '', bool $md5 = true): string
2150
  {
2151 1
    $uniqueHelper = \mt_rand() .
2152 1
                    \session_id() .
2153 1
                    ($_SERVER['REMOTE_ADDR'] ?? '') .
2154 1
                    ($_SERVER['SERVER_ADDR'] ?? '') .
2155 1
                    $entropyExtra;
2156
2157 1
    $uniqueString = \uniqid($uniqueHelper, true);
2158
2159 1
    if ($md5) {
2160 1
      $uniqueString = \md5($uniqueString . $uniqueHelper);
2161
    }
2162
2163 1
    return $uniqueString;
2164
  }
2165
2166
  /**
2167
   * alias for "UTF8::string_has_bom()"
2168
   *
2169
   * @see        UTF8::string_has_bom()
2170
   *
2171
   * @param string $str
2172
   *
2173
   * @return bool
2174
   *
2175
   * @deprecated <p>use "UTF8::string_has_bom()"</p>
2176
   */
2177 2
  public static function hasBom(string $str): bool
2178
  {
2179 2
    return self::string_has_bom($str);
2180
  }
2181
2182
  /**
2183
   * Returns true if the string contains a lower case char, false otherwise.
2184
   *
2185
   * @param string $str <p>The input string.</p>
2186
   *
2187
   * @return bool Whether or not the string contains a lower case character.
2188
   */
2189 47
  public static function has_lowercase(string $str): bool
2190
  {
2191 47
    return self::str_matches_pattern($str, '.*[[:lower:]]');
2192
  }
2193
2194
  /**
2195
   * Returns true if the string contains an upper case char, false otherwise.
2196
   *
2197
   * @param string $str <p>The input string.</p>
2198
   *
2199
   * @return bool Whether or not the string contains an upper case character.
2200
   */
2201 12
  public static function has_uppercase(string $str): bool
2202
  {
2203 12
    return self::str_matches_pattern($str, '.*[[:upper:]]');
2204
  }
2205
2206
  /**
2207
   * Converts a hexadecimal-value into an UTF-8 character.
2208
   *
2209
   * @param string $hexdec <p>The hexadecimal value.</p>
2210
   *
2211
   * @return string|false One single UTF-8 character.
2212
   */
2213 4
  public static function hex_to_chr(string $hexdec)
2214
  {
2215 4
    return self::decimal_to_chr(\hexdec($hexdec));
2216
  }
2217
2218
  /**
2219
   * Converts hexadecimal U+xxxx code point representation to integer.
2220
   *
2221
   * INFO: opposite to UTF8::int_to_hex()
2222
   *
2223
   * @param string $hexDec <p>The hexadecimal code point representation.</p>
2224
   *
2225
   * @return int|false The code point, or false on failure.
2226
   */
2227 2
  public static function hex_to_int($hexDec)
2228
  {
2229
    // init
2230 2
    $hexDec = (string)$hexDec;
2231
2232 2
    if ('' === $hexDec) {
2233 2
      return false;
2234
    }
2235
2236 2
    if (\preg_match('/^(?:\\\u|U\+|)([a-z0-9]{4,6})$/i', $hexDec, $match)) {
2237 2
      return \intval($match[1], 16);
2238
    }
2239
2240 2
    return false;
2241
  }
2242
2243
  /**
2244
   * alias for "UTF8::html_entity_decode()"
2245
   *
2246
   * @see UTF8::html_entity_decode()
2247
   *
2248
   * @param string $str
2249
   * @param int    $flags
2250
   * @param string $encoding
2251
   *
2252
   * @return string
2253
   */
2254 4
  public static function html_decode(string $str, int $flags = null, string $encoding = 'UTF-8'): string
2255
  {
2256 4
    return self::html_entity_decode($str, $flags, $encoding);
2257
  }
2258
2259
  /**
2260
   * Converts a UTF-8 string to a series of HTML numbered entities.
2261
   *
2262
   * INFO: opposite to UTF8::html_decode()
2263
   *
2264
   * @param string $str            <p>The Unicode string to be encoded as numbered entities.</p>
2265
   * @param bool   $keepAsciiChars [optional] <p>Keep ASCII chars.</p>
2266
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
2267
   *
2268
   * @return string HTML numbered entities.
2269
   */
2270 13
  public static function html_encode(string $str, bool $keepAsciiChars = false, string $encoding = 'UTF-8'): string
2271
  {
2272 13
    if ('' === $str) {
2273 4
      return '';
2274
    }
2275
2276 13
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2277 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2278
    }
2279
2280 13
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
2281
      self::checkForSupport();
2282
    }
2283
2284
    # INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2285 13
    if (self::$SUPPORT['mbstring'] === true) {
2286 13
      $startCode = 0x00;
2287 13
      if ($keepAsciiChars === true) {
2288 13
        $startCode = 0x80;
2289
      }
2290
2291 13
      return \mb_encode_numericentity(
2292 13
          $str,
2293 13
          [$startCode, 0xfffff, 0, 0xfffff, 0],
2294 13
          $encoding
2295
      );
2296
    }
2297
2298
    //
2299
    // fallback via vanilla php
2300
    //
2301
2302
    return \implode(
2303
        '',
2304
        \array_map(
2305
            function ($chr) use ($keepAsciiChars, $encoding) {
2306
              return UTF8::single_chr_html_encode($chr, $keepAsciiChars, $encoding);
2307
            },
2308
            self::split($str)
2309
        )
2310
    );
2311
  }
2312
2313
  /**
2314
   * UTF-8 version of html_entity_decode()
2315
   *
2316
   * The reason we are not using html_entity_decode() by itself is because
2317
   * while it is not technically correct to leave out the semicolon
2318
   * at the end of an entity most browsers will still interpret the entity
2319
   * correctly. html_entity_decode() does not convert entities without
2320
   * semicolons, so we are left with our own little solution here. Bummer.
2321
   *
2322
   * Convert all HTML entities to their applicable characters
2323
   *
2324
   * INFO: opposite to UTF8::html_encode()
2325
   *
2326
   * @link http://php.net/manual/en/function.html-entity-decode.php
2327
   *
2328
   * @param string $str      <p>
2329
   *                         The input string.
2330
   *                         </p>
2331
   * @param int    $flags    [optional] <p>
2332
   *                         A bitmask of one or more of the following flags, which specify how to handle quotes and
2333
   *                         which document type to use. The default is ENT_COMPAT | ENT_HTML401.
2334
   *                         <table>
2335
   *                         Available <i>flags</i> constants
2336
   *                         <tr valign="top">
2337
   *                         <td>Constant Name</td>
2338
   *                         <td>Description</td>
2339
   *                         </tr>
2340
   *                         <tr valign="top">
2341
   *                         <td><b>ENT_COMPAT</b></td>
2342
   *                         <td>Will convert double-quotes and leave single-quotes alone.</td>
2343
   *                         </tr>
2344
   *                         <tr valign="top">
2345
   *                         <td><b>ENT_QUOTES</b></td>
2346
   *                         <td>Will convert both double and single quotes.</td>
2347
   *                         </tr>
2348
   *                         <tr valign="top">
2349
   *                         <td><b>ENT_NOQUOTES</b></td>
2350
   *                         <td>Will leave both double and single quotes unconverted.</td>
2351
   *                         </tr>
2352
   *                         <tr valign="top">
2353
   *                         <td><b>ENT_HTML401</b></td>
2354
   *                         <td>
2355
   *                         Handle code as HTML 4.01.
2356
   *                         </td>
2357
   *                         </tr>
2358
   *                         <tr valign="top">
2359
   *                         <td><b>ENT_XML1</b></td>
2360
   *                         <td>
2361
   *                         Handle code as XML 1.
2362
   *                         </td>
2363
   *                         </tr>
2364
   *                         <tr valign="top">
2365
   *                         <td><b>ENT_XHTML</b></td>
2366
   *                         <td>
2367
   *                         Handle code as XHTML.
2368
   *                         </td>
2369
   *                         </tr>
2370
   *                         <tr valign="top">
2371
   *                         <td><b>ENT_HTML5</b></td>
2372
   *                         <td>
2373
   *                         Handle code as HTML 5.
2374
   *                         </td>
2375
   *                         </tr>
2376
   *                         </table>
2377
   *                         </p>
2378
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2379
   *
2380
   * @return string The decoded string.
2381
   */
2382 40
  public static function html_entity_decode(string $str, int $flags = null, string $encoding = 'UTF-8'): string
2383
  {
2384 40
    if ('' === $str) {
2385 12
      return '';
2386
    }
2387
2388 40
    if (!isset($str[3])) { // examples: &; || &x;
2389 19
      return $str;
2390
    }
2391
2392
    if (
2393 39
        \strpos($str, '&') === false
2394
        ||
2395
        (
2396 39
            \strpos($str, '&#') === false
2397
            &&
2398 39
            \strpos($str, ';') === false
2399
        )
2400
    ) {
2401 18
      return $str;
2402
    }
2403
2404 39
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2405 9
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2406
    }
2407
2408 39
    if ($flags === null) {
2409 10
      $flags = ENT_QUOTES | ENT_HTML5;
2410
    }
2411
2412
    if (
2413 39
        $encoding !== 'UTF-8'
2414
        &&
2415 39
        $encoding !== 'ISO-8859-1'
2416
        &&
2417 39
        $encoding !== 'WINDOWS-1252'
2418
        &&
2419 39
        self::$SUPPORT['mbstring'] === false
2420
    ) {
2421
      \trigger_error('UTF8::html_entity_decode() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
2422
    }
2423
2424 39
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
2425
      self::checkForSupport();
2426
    }
2427
2428
    do {
2429 39
      $str_compare = $str;
2430
2431
      # INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2432 39
      if (self::$SUPPORT['mbstring'] === true) {
2433
2434 39
        $str = \mb_decode_numericentity(
2435 39
            $str,
2436 39
            [0x80, 0xfffff, 0, 0xfffff, 0],
2437 39
            $encoding
2438
        );
2439
2440
      } else {
2441
2442
        $str = (string)\preg_replace_callback(
2443
            "/&#\d{2,6};/",
2444
            function ($matches) use ($encoding) {
2445
              // always fallback via symfony polyfill
2446
              $returnTmp = \mb_convert_encoding($matches[0], $encoding, 'HTML-ENTITIES');
2447
2448
              if ($returnTmp !== '"' && $returnTmp !== "'") {
2449
                return $returnTmp;
2450
              }
2451
2452
              return $matches[0];
2453
            },
2454
            $str
2455
        );
2456
2457
      }
2458
2459
      // decode numeric & UTF16 two byte entities
2460 39
      $str = \html_entity_decode(
2461 39
          \preg_replace('/(&#(?:x0*[0-9a-f]{2,6}(?![0-9a-f;])|(?:0*\d{2,6}(?![0-9;]))))/iS', '$1;', $str),
2462 39
          $flags,
2463 39
          $encoding
2464
      );
2465
2466 39
    } while ($str_compare !== $str);
2467
2468 39
    return $str;
2469
  }
2470
2471
  /**
2472
   * Create a escape html version of the string via "UTF8::htmlspecialchars()".
2473
   *
2474
   * @param string $str
2475
   * @param string $encoding [optional] <p>Default: UTF-8</p>
2476
   *
2477
   * @return string
2478
   */
2479 6
  public static function html_escape(string $str, string $encoding = 'UTF-8'): string
2480
  {
2481 6
    return self::htmlspecialchars(
2482 6
        $str,
2483 6
        ENT_QUOTES | ENT_SUBSTITUTE,
2484 6
        $encoding
2485
    );
2486
  }
2487
2488
  /**
2489
   * Remove empty html-tag.
2490
   *
2491
   * e.g.: <tag></tag>
2492
   *
2493
   * @param string $str
2494
   *
2495
   * @return string
2496
   */
2497 1
  public static function html_stripe_empty_tags(string $str): string
2498
  {
2499 1
    return (string)\preg_replace(
2500 1
        "/<[^\/>]*>(([\s]?)*|)<\/[^>]*>/iu",
2501 1
        '',
2502 1
        $str
2503
    );
2504
  }
2505
2506
  /**
2507
   * Convert all applicable characters to HTML entities: UTF-8 version of htmlentities()
2508
   *
2509
   * @link http://php.net/manual/en/function.htmlentities.php
2510
   *
2511
   * @param string $str           <p>
2512
   *                              The input string.
2513
   *                              </p>
2514
   * @param int    $flags         [optional] <p>
2515
   *                              A bitmask of one or more of the following flags, which specify how to handle quotes,
2516
   *                              invalid code unit sequences and the used document type. The default is
2517
   *                              ENT_COMPAT | ENT_HTML401.
2518
   *                              <table>
2519
   *                              Available <i>flags</i> constants
2520
   *                              <tr valign="top">
2521
   *                              <td>Constant Name</td>
2522
   *                              <td>Description</td>
2523
   *                              </tr>
2524
   *                              <tr valign="top">
2525
   *                              <td><b>ENT_COMPAT</b></td>
2526
   *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2527
   *                              </tr>
2528
   *                              <tr valign="top">
2529
   *                              <td><b>ENT_QUOTES</b></td>
2530
   *                              <td>Will convert both double and single quotes.</td>
2531
   *                              </tr>
2532
   *                              <tr valign="top">
2533
   *                              <td><b>ENT_NOQUOTES</b></td>
2534
   *                              <td>Will leave both double and single quotes unconverted.</td>
2535
   *                              </tr>
2536
   *                              <tr valign="top">
2537
   *                              <td><b>ENT_IGNORE</b></td>
2538
   *                              <td>
2539
   *                              Silently discard invalid code unit sequences instead of returning
2540
   *                              an empty string. Using this flag is discouraged as it
2541
   *                              may have security implications.
2542
   *                              </td>
2543
   *                              </tr>
2544
   *                              <tr valign="top">
2545
   *                              <td><b>ENT_SUBSTITUTE</b></td>
2546
   *                              <td>
2547
   *                              Replace invalid code unit sequences with a Unicode Replacement Character
2548
   *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty string.
2549
   *                              </td>
2550
   *                              </tr>
2551
   *                              <tr valign="top">
2552
   *                              <td><b>ENT_DISALLOWED</b></td>
2553
   *                              <td>
2554
   *                              Replace invalid code points for the given document type with a
2555
   *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2556
   *                              (otherwise) instead of leaving them as is. This may be useful, for
2557
   *                              instance, to ensure the well-formedness of XML documents with
2558
   *                              embedded external content.
2559
   *                              </td>
2560
   *                              </tr>
2561
   *                              <tr valign="top">
2562
   *                              <td><b>ENT_HTML401</b></td>
2563
   *                              <td>
2564
   *                              Handle code as HTML 4.01.
2565
   *                              </td>
2566
   *                              </tr>
2567
   *                              <tr valign="top">
2568
   *                              <td><b>ENT_XML1</b></td>
2569
   *                              <td>
2570
   *                              Handle code as XML 1.
2571
   *                              </td>
2572
   *                              </tr>
2573
   *                              <tr valign="top">
2574
   *                              <td><b>ENT_XHTML</b></td>
2575
   *                              <td>
2576
   *                              Handle code as XHTML.
2577
   *                              </td>
2578
   *                              </tr>
2579
   *                              <tr valign="top">
2580
   *                              <td><b>ENT_HTML5</b></td>
2581
   *                              <td>
2582
   *                              Handle code as HTML 5.
2583
   *                              </td>
2584
   *                              </tr>
2585
   *                              </table>
2586
   *                              </p>
2587
   * @param string $encoding      [optional] <p>
2588
   *                              Like <b>htmlspecialchars</b>,
2589
   *                              <b>htmlentities</b> takes an optional third argument
2590
   *                              <i>encoding</i> which defines encoding used in
2591
   *                              conversion.
2592
   *                              Although this argument is technically optional, you are highly
2593
   *                              encouraged to specify the correct value for your code.
2594
   *                              </p>
2595
   * @param bool   $double_encode [optional] <p>
2596
   *                              When <i>double_encode</i> is turned off PHP will not
2597
   *                              encode existing html entities. The default is to convert everything.
2598
   *                              </p>
2599
   *
2600
   *
2601
   * @return string The encoded string.
2602
   * </p>
2603
   * <p>
2604
   * If the input <i>string</i> contains an invalid code unit
2605
   * sequence within the given <i>encoding</i> an empty string
2606
   * will be returned, unless either the <b>ENT_IGNORE</b> or
2607
   * <b>ENT_SUBSTITUTE</b> flags are set.
2608
   */
2609 9
  public static function htmlentities(string $str, int $flags = ENT_COMPAT, string $encoding = 'UTF-8', bool $double_encode = true): string
2610
  {
2611 9
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2612 7
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2613
    }
2614
2615 9
    $str = \htmlentities($str, $flags, $encoding, $double_encode);
2616
2617
    /**
2618
     * PHP doesn't replace a backslash to its html entity since this is something
2619
     * that's mostly used to escape characters when inserting in a database. Since
2620
     * we're using a decent database layer, we don't need this shit and we're replacing
2621
     * the double backslashes by its' html entity equivalent.
2622
     *
2623
     * https://github.com/forkcms/library/blob/master/spoon/filter/filter.php#L303
2624
     */
2625 9
    $str = \str_replace('\\', '&#92;', $str);
2626
2627 9
    return self::html_encode($str, true, $encoding);
2628
  }
2629
2630
  /**
2631
   * Convert only special characters to HTML entities: UTF-8 version of htmlspecialchars()
2632
   *
2633
   * INFO: Take a look at "UTF8::htmlentities()"
2634
   *
2635
   * @link http://php.net/manual/en/function.htmlspecialchars.php
2636
   *
2637
   * @param string $str           <p>
2638
   *                              The string being converted.
2639
   *                              </p>
2640
   * @param int    $flags         [optional] <p>
2641
   *                              A bitmask of one or more of the following flags, which specify how to handle quotes,
2642
   *                              invalid code unit sequences and the used document type. The default is
2643
   *                              ENT_COMPAT | ENT_HTML401.
2644
   *                              <table>
2645
   *                              Available <i>flags</i> constants
2646
   *                              <tr valign="top">
2647
   *                              <td>Constant Name</td>
2648
   *                              <td>Description</td>
2649
   *                              </tr>
2650
   *                              <tr valign="top">
2651
   *                              <td><b>ENT_COMPAT</b></td>
2652
   *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2653
   *                              </tr>
2654
   *                              <tr valign="top">
2655
   *                              <td><b>ENT_QUOTES</b></td>
2656
   *                              <td>Will convert both double and single quotes.</td>
2657
   *                              </tr>
2658
   *                              <tr valign="top">
2659
   *                              <td><b>ENT_NOQUOTES</b></td>
2660
   *                              <td>Will leave both double and single quotes unconverted.</td>
2661
   *                              </tr>
2662
   *                              <tr valign="top">
2663
   *                              <td><b>ENT_IGNORE</b></td>
2664
   *                              <td>
2665
   *                              Silently discard invalid code unit sequences instead of returning
2666
   *                              an empty string. Using this flag is discouraged as it
2667
   *                              may have security implications.
2668
   *                              </td>
2669
   *                              </tr>
2670
   *                              <tr valign="top">
2671
   *                              <td><b>ENT_SUBSTITUTE</b></td>
2672
   *                              <td>
2673
   *                              Replace invalid code unit sequences with a Unicode Replacement Character
2674
   *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty string.
2675
   *                              </td>
2676
   *                              </tr>
2677
   *                              <tr valign="top">
2678
   *                              <td><b>ENT_DISALLOWED</b></td>
2679
   *                              <td>
2680
   *                              Replace invalid code points for the given document type with a
2681
   *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2682
   *                              (otherwise) instead of leaving them as is. This may be useful, for
2683
   *                              instance, to ensure the well-formedness of XML documents with
2684
   *                              embedded external content.
2685
   *                              </td>
2686
   *                              </tr>
2687
   *                              <tr valign="top">
2688
   *                              <td><b>ENT_HTML401</b></td>
2689
   *                              <td>
2690
   *                              Handle code as HTML 4.01.
2691
   *                              </td>
2692
   *                              </tr>
2693
   *                              <tr valign="top">
2694
   *                              <td><b>ENT_XML1</b></td>
2695
   *                              <td>
2696
   *                              Handle code as XML 1.
2697
   *                              </td>
2698
   *                              </tr>
2699
   *                              <tr valign="top">
2700
   *                              <td><b>ENT_XHTML</b></td>
2701
   *                              <td>
2702
   *                              Handle code as XHTML.
2703
   *                              </td>
2704
   *                              </tr>
2705
   *                              <tr valign="top">
2706
   *                              <td><b>ENT_HTML5</b></td>
2707
   *                              <td>
2708
   *                              Handle code as HTML 5.
2709
   *                              </td>
2710
   *                              </tr>
2711
   *                              </table>
2712
   *                              </p>
2713
   * @param string $encoding      [optional] <p>
2714
   *                              Defines encoding used in conversion.
2715
   *                              </p>
2716
   *                              <p>
2717
   *                              For the purposes of this function, the encodings
2718
   *                              ISO-8859-1, ISO-8859-15,
2719
   *                              UTF-8, cp866,
2720
   *                              cp1251, cp1252, and
2721
   *                              KOI8-R are effectively equivalent, provided the
2722
   *                              <i>string</i> itself is valid for the encoding, as
2723
   *                              the characters affected by <b>htmlspecialchars</b> occupy
2724
   *                              the same positions in all of these encodings.
2725
   *                              </p>
2726
   * @param bool   $double_encode [optional] <p>
2727
   *                              When <i>double_encode</i> is turned off PHP will not
2728
   *                              encode existing html entities, the default is to convert everything.
2729
   *                              </p>
2730
   *
2731
   * @return string The converted string.
2732
   * </p>
2733
   * <p>
2734
   * If the input <i>string</i> contains an invalid code unit
2735
   * sequence within the given <i>encoding</i> an empty string
2736
   * will be returned, unless either the <b>ENT_IGNORE</b> or
2737
   * <b>ENT_SUBSTITUTE</b> flags are set.
2738
   */
2739 8
  public static function htmlspecialchars(string $str, int $flags = ENT_COMPAT, string $encoding = 'UTF-8', bool $double_encode = true): string
2740
  {
2741 8
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2742 8
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2743
    }
2744
2745 8
    return \htmlspecialchars($str, $flags, $encoding, $double_encode);
2746
  }
2747
2748
  /**
2749
   * Checks whether iconv is available on the server.
2750
   *
2751
   * @return bool
2752
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2753
   */
2754
  public static function iconv_loaded(): bool
2755
  {
2756
    return \extension_loaded('iconv') ? true : false;
2757
  }
2758
2759
  /**
2760
   * alias for "UTF8::decimal_to_chr()"
2761
   *
2762
   * @see UTF8::decimal_to_chr()
2763
   *
2764
   * @param mixed $int
2765
   *
2766
   * @return string
2767
   */
2768 4
  public static function int_to_chr($int): string
2769
  {
2770 4
    return self::decimal_to_chr($int);
2771
  }
2772
2773
  /**
2774
   * Converts Integer to hexadecimal U+xxxx code point representation.
2775
   *
2776
   * INFO: opposite to UTF8::hex_to_int()
2777
   *
2778
   * @param int    $int  <p>The integer to be converted to hexadecimal code point.</p>
2779
   * @param string $pfix [optional]
2780
   *
2781
   * @return string The code point, or empty string on failure.
2782
   */
2783 6
  public static function int_to_hex(int $int, string $pfix = 'U+'): string
2784
  {
2785 6
    $hex = \dechex($int);
2786
2787 6
    $hex = (\strlen($hex) < 4 ? \substr('0000' . $hex, -4) : $hex);
2788
2789 6
    return $pfix . $hex . '';
2790
  }
2791
2792
  /**
2793
   * Checks whether intl-char is available on the server.
2794
   *
2795
   * @return bool
2796
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2797
   */
2798
  public static function intlChar_loaded(): bool
2799
  {
2800
    return \class_exists('IntlChar');
2801
  }
2802
2803
  /**
2804
   * Checks whether intl is available on the server.
2805
   *
2806
   * @return bool
2807
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2808
   */
2809 5
  public static function intl_loaded(): bool
2810
  {
2811 5
    return \extension_loaded('intl');
2812
  }
2813
2814
  /**
2815
   * alias for "UTF8::is_ascii()"
2816
   *
2817
   * @see        UTF8::is_ascii()
2818
   *
2819
   * @param string $str
2820
   *
2821
   * @return bool
2822
   *
2823
   * @deprecated <p>use "UTF8::is_ascii()"</p>
2824
   */
2825 2
  public static function isAscii(string $str): bool
2826
  {
2827 2
    return self::is_ascii($str);
2828
  }
2829
2830
  /**
2831
   * alias for "UTF8::is_base64()"
2832
   *
2833
   * @see        UTF8::is_base64()
2834
   *
2835
   * @param string $str
2836
   *
2837
   * @return bool
2838
   *
2839
   * @deprecated <p>use "UTF8::is_base64()"</p>
2840
   */
2841 2
  public static function isBase64($str): bool
2842
  {
2843 2
    return self::is_base64($str);
2844
  }
2845
2846
  /**
2847
   * alias for "UTF8::is_binary()"
2848
   *
2849
   * @see        UTF8::is_binary()
2850
   *
2851
   * @param mixed $str
2852
   * @param bool  $strict
2853
   *
2854
   * @return bool
2855
   *
2856
   * @deprecated <p>use "UTF8::is_binary()"</p>
2857
   */
2858 4
  public static function isBinary($str, $strict = false): bool
2859
  {
2860 4
    return self::is_binary($str, $strict);
2861
  }
2862
2863
  /**
2864
   * alias for "UTF8::is_bom()"
2865
   *
2866
   * @see        UTF8::is_bom()
2867
   *
2868
   * @param string $utf8_chr
2869
   *
2870
   * @return bool
2871
   *
2872
   * @deprecated <p>use "UTF8::is_bom()"</p>
2873
   */
2874 2
  public static function isBom(string $utf8_chr): bool
2875
  {
2876 2
    return self::is_bom($utf8_chr);
2877
  }
2878
2879
  /**
2880
   * alias for "UTF8::is_html()"
2881
   *
2882
   * @see        UTF8::is_html()
2883
   *
2884
   * @param string $str
2885
   *
2886
   * @return bool
2887
   *
2888
   * @deprecated <p>use "UTF8::is_html()"</p>
2889
   */
2890 2
  public static function isHtml(string $str): bool
2891
  {
2892 2
    return self::is_html($str);
2893
  }
2894
2895
  /**
2896
   * alias for "UTF8::is_json()"
2897
   *
2898
   * @see        UTF8::is_json()
2899
   *
2900
   * @param string $str
2901
   *
2902
   * @return bool
2903
   *
2904
   * @deprecated <p>use "UTF8::is_json()"</p>
2905
   */
2906
  public static function isJson(string $str): bool
2907
  {
2908
    return self::is_json($str);
2909
  }
2910
2911
  /**
2912
   * alias for "UTF8::is_utf16()"
2913
   *
2914
   * @see        UTF8::is_utf16()
2915
   *
2916
   * @param mixed $str
2917
   *
2918
   * @return int|false
2919
   *                    <strong>false</strong> if is't not UTF16,<br>
2920
   *                    <strong>1</strong> for UTF-16LE,<br>
2921
   *                    <strong>2</strong> for UTF-16BE.
2922
   *
2923
   * @deprecated <p>use "UTF8::is_utf16()"</p>
2924
   */
2925 2
  public static function isUtf16($str)
2926
  {
2927 2
    return self::is_utf16($str);
2928
  }
2929
2930
  /**
2931
   * alias for "UTF8::is_utf32()"
2932
   *
2933
   * @see        UTF8::is_utf32()
2934
   *
2935
   * @param mixed $str
2936
   *
2937
   * @return int|false
2938
   *                   <strong>false</strong> if is't not UTF16,
2939
   *                   <strong>1</strong> for UTF-32LE,
2940
   *                   <strong>2</strong> for UTF-32BE.
2941
   *
2942
   * @deprecated <p>use "UTF8::is_utf32()"</p>
2943
   */
2944 2
  public static function isUtf32($str)
2945
  {
2946 2
    return self::is_utf32($str);
2947
  }
2948
2949
  /**
2950
   * alias for "UTF8::is_utf8()"
2951
   *
2952
   * @see        UTF8::is_utf8()
2953
   *
2954
   * @param string $str
2955
   * @param bool   $strict
2956
   *
2957
   * @return bool
2958
   *
2959
   * @deprecated <p>use "UTF8::is_utf8()"</p>
2960
   */
2961 17
  public static function isUtf8($str, $strict = false): bool
2962
  {
2963 17
    return self::is_utf8($str, $strict);
2964
  }
2965
2966
  /**
2967
   * Returns true if the string contains only alphabetic chars, false otherwise.
2968
   *
2969
   * @param string $str
2970
   *
2971
   * @return bool
2972
   *               Whether or not $str contains only alphabetic chars.
2973
   */
2974 10
  public static function is_alpha(string $str): bool
2975
  {
2976 10
    return self::str_matches_pattern($str, '^[[:alpha:]]*$');
2977
  }
2978
2979
  /**
2980
   * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
2981
   *
2982
   * @param string $str
2983
   *
2984
   * @return bool
2985
   *               Whether or not $str contains only alphanumeric chars.
2986
   */
2987 13
  public static function is_alphanumeric(string $str): bool
2988
  {
2989 13
    return self::str_matches_pattern($str, '^[[:alnum:]]*$');
2990
  }
2991
2992
  /**
2993
   * Checks if a string is 7 bit ASCII.
2994
   *
2995
   * @param string $str <p>The string to check.</p>
2996
   *
2997
   * @return bool
2998
   *              <strong>true</strong> if it is ASCII<br>
2999
   *              <strong>false</strong> otherwise
3000
   *
3001
   */
3002 202
  public static function is_ascii(string $str): bool
3003
  {
3004 202
    if ('' === $str) {
3005 10
      return true;
3006
    }
3007
3008 201
    return !\preg_match('/[^\x09\x10\x13\x0A\x0D\x20-\x7E]/', $str);
3009
  }
3010
3011
  /**
3012
   * Returns true if the string is base64 encoded, false otherwise.
3013
   *
3014
   * @param string $str <p>The input string.</p>
3015
   *
3016
   * @return bool Whether or not $str is base64 encoded.
3017
   */
3018 9
  public static function is_base64($str): bool
3019
  {
3020 9
    if ('' === $str) {
3021 3
      return false;
3022
    }
3023
3024 8
    if (\is_string($str) === false) {
0 ignored issues
show
introduced by
The condition is_string($str) === false is always false.
Loading history...
3025 2
      return false;
3026
    }
3027
3028 8
    $base64String = (string)\base64_decode($str, true);
3029
3030 8
    return $base64String && \base64_encode($base64String) === $str;
3031
  }
3032
3033
  /**
3034
   * Check if the input is binary... (is look like a hack).
3035
   *
3036
   * @param mixed $input
3037
   * @param bool  $strict
3038
   *
3039
   * @return bool
3040
   */
3041 38
  public static function is_binary($input, bool $strict = false): bool
3042
  {
3043 38
    $input = (string)$input;
3044 38
    if ('' === $input) {
3045 10
      return false;
3046
    }
3047
3048 38
    if (\preg_match('~^[01]+$~', $input)) {
3049 12
      return true;
3050
    }
3051
3052 38
    $ext = self::get_file_type($input);
3053 38
    if ($ext['type'] === 'binary') {
3054 6
      return true;
3055
    }
3056
3057 36
    $testLength = self::strlen_in_byte($input);
3058 36
    if ($testLength) {
3059 36
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3060
        self::checkForSupport();
3061
      }
3062
3063 36
      $testNull = self::substr_count_in_byte($input, "\x0", 0, $testLength);
3064 36
      if (($testNull / $testLength) > 0.256) {
3065 12
        return true;
3066
      }
3067
    }
3068
3069 34
    if ($strict === true) {
3070
3071 34
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3072
        self::checkForSupport();
3073
      }
3074
3075 34
      if (self::$SUPPORT['finfo'] === false) {
3076
        throw new \RuntimeException('ext-fileinfo: is not installed');
3077
      }
3078
3079
      /** @noinspection PhpComposerExtensionStubsInspection */
3080 34
      $finfo = new \finfo(FILEINFO_MIME_ENCODING);
3081 34
      $finfo_encoding = $finfo->buffer($input);
3082 34
      if ($finfo_encoding && $finfo_encoding === 'binary') {
3083 14
        return true;
3084
      }
3085
3086
    }
3087
3088 30
    return false;
3089
  }
3090
3091
  /**
3092
   * Check if the file is binary.
3093
   *
3094
   * @param string $file
3095
   *
3096
   * @return bool
3097
   */
3098 6
  public static function is_binary_file($file): bool
3099
  {
3100
    // init
3101 6
    $block = '';
3102
3103 6
    $fp = \fopen($file, 'rb');
3104 6
    if (\is_resource($fp)) {
3105 6
      $block = \fread($fp, 512);
3106 6
      \fclose($fp);
3107
    }
3108
3109 6
    if ($block === '') {
3110 2
      return false;
3111
    }
3112
3113 6
    return self::is_binary($block, true);
3114
  }
3115
3116
  /**
3117
   * Returns true if the string contains only whitespace chars, false otherwise.
3118
   *
3119
   * @param string $str
3120
   *
3121
   * @return bool
3122
   *               Whether or not $str contains only whitespace characters.
3123
   */
3124 15
  public static function is_blank(string $str): bool
3125
  {
3126 15
    return self::str_matches_pattern($str, '^[[:space:]]*$');
3127
  }
3128
3129
  /**
3130
   * Checks if the given string is equal to any "Byte Order Mark".
3131
   *
3132
   * WARNING: Use "UTF8::string_has_bom()" if you will check BOM in a string.
3133
   *
3134
   * @param string $str <p>The input string.</p>
3135
   *
3136
   * @return bool
3137
   *              <strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.
3138
   */
3139 2
  public static function is_bom($str): bool
3140
  {
3141 2
    foreach (self::$BOM as $bomString => $bomByteLength) {
3142 2
      if ($str === $bomString) {
3143 2
        return true;
3144
      }
3145
    }
3146
3147 2
    return false;
3148
  }
3149
3150
  /**
3151
   * Determine whether the string is considered to be empty.
3152
   *
3153
   * A variable is considered empty if it does not exist or if its value equals FALSE.
3154
   * empty() does not generate a warning if the variable does not exist.
3155
   *
3156
   * @param mixed $str
3157
   *
3158
   * @return bool Whether or not $str is empty().
3159
   */
3160
  public static function is_empty($str): bool
3161
  {
3162
    return empty($str);
3163
  }
3164
3165
  /**
3166
   * Returns true if the string contains only hexadecimal chars, false otherwise.
3167
   *
3168
   * @param string $str
3169
   *
3170
   * @return bool
3171
   *               Whether or not $str contains only hexadecimal chars.
3172
   */
3173 13
  public static function is_hexadecimal(string $str): bool
3174
  {
3175 13
    return self::str_matches_pattern($str, '^[[:xdigit:]]*$');
3176
  }
3177
3178
  /**
3179
   * Check if the string contains any html-tags <lall>.
3180
   *
3181
   * @param string $str <p>The input string.</p>
3182
   *
3183
   * @return bool
3184
   */
3185 3
  public static function is_html(string $str): bool
3186
  {
3187 3
    if ('' === $str) {
3188 3
      return false;
3189
    }
3190
3191
    // init
3192 3
    $matches = [];
3193
3194 3
    \preg_match("/<\/?\w+(?:(?:\s+\w+(?:\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)*+\s*|\s*)\/?>/", $str, $matches);
3195
3196 3
    return !(\count($matches) === 0);
3197
  }
3198
3199
  /**
3200
   * Try to check if "$str" is an json-string.
3201
   *
3202
   * @param string $str <p>The input string.</p>
3203
   *
3204
   * @return bool
3205
   */
3206 22
  public static function is_json(string $str): bool
3207
  {
3208 22
    if ('' === $str) {
3209 3
      return false;
3210
    }
3211
3212 21
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3213
      self::checkForSupport();
3214
    }
3215
3216 21
    if (self::$SUPPORT['json'] === false) {
3217
      throw new \RuntimeException('ext-json: is not installed');
3218
    }
3219
3220 21
    $json = self::json_decode($str);
3221
3222
    /** @noinspection PhpComposerExtensionStubsInspection */
3223
    return (
3224 21
               \is_object($json) === true
3225
               ||
3226 21
               \is_array($json) === true
3227
           )
3228
           &&
3229 21
           \json_last_error() === JSON_ERROR_NONE;
3230
  }
3231
3232
  /**
3233
   * @param string $str
3234
   *
3235
   * @return bool
3236
   */
3237 8
  public static function is_lowercase(string $str): bool
3238
  {
3239 8
    if (self::str_matches_pattern($str, '^[[:lower:]]*$')) {
3240 3
      return true;
3241
    }
3242
3243 5
    return false;
3244
  }
3245
3246
  /**
3247
   * Returns true if the string is serialized, false otherwise.
3248
   *
3249
   * @param string $str
3250
   *
3251
   * @return bool Whether or not $str is serialized.
3252
   */
3253 7
  public static function is_serialized(string $str): bool
3254
  {
3255 7
    if ('' === $str) {
3256 1
      return false;
3257
    }
3258
3259
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
3260
    /** @noinspection UnserializeExploitsInspection */
3261 6
    return $str === 'b:0;'
3262
           ||
3263 6
           @\unserialize($str) !== false;
3264
  }
3265
3266
  /**
3267
   * Returns true if the string contains only lower case chars, false
3268
   * otherwise.
3269
   *
3270
   * @param string $str <p>The input string.</p>
3271
   *
3272
   * @return bool
3273
   *               Whether or not $str contains only lower case characters.
3274
   */
3275 8
  public static function is_uppercase(string $str): bool
3276
  {
3277 8
    return self::str_matches_pattern($str, '^[[:upper:]]*$');
3278
  }
3279
3280
  /**
3281
   * Check if the string is UTF-16.
3282
   *
3283
   * @param mixed $str <p>The input string.</p>
3284
   * @param bool  $checkIfStringIsBinary
3285
   *
3286
   * @return int|false
3287
   *                   <strong>false</strong> if is't not UTF-16,<br>
3288
   *                   <strong>1</strong> for UTF-16LE,<br>
3289
   *                   <strong>2</strong> for UTF-16BE.
3290
   */
3291 20
  public static function is_utf16($str, $checkIfStringIsBinary = true)
3292
  {
3293
    // init
3294 20
    $str = (string)$str;
3295 20
    $strChars = [];
3296
3297
    if (
3298 20
        $checkIfStringIsBinary === true
3299
        &&
3300 20
        self::is_binary($str, true) === false
3301
    ) {
3302 2
      return false;
3303
    }
3304
3305 20
    if (self::$SUPPORT['mbstring'] === false) {
3306 2
      \trigger_error('UTF8::is_utf16() without mbstring may did not work correctly', E_USER_WARNING);
3307
    }
3308
3309 20
    $str = self::remove_bom($str);
3310
3311 20
    $maybeUTF16LE = 0;
3312 20
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16LE');
3313 20
    if ($test) {
3314 14
      $test2 = \mb_convert_encoding($test, 'UTF-16LE', 'UTF-8');
3315 14
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16LE');
3316 14
      if ($test3 === $test) {
3317 14
        if (\count($strChars) === 0) {
3318 14
          $strChars = self::count_chars($str, true);
3319
        }
3320 14
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3321 14
          if (\in_array($test3char, $strChars, true) === true) {
3322 14
            $maybeUTF16LE++;
3323
          }
3324
        }
3325
      }
3326
    }
3327
3328 20
    $maybeUTF16BE = 0;
3329 20
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
3330 20
    if ($test) {
3331 14
      $test2 = \mb_convert_encoding($test, 'UTF-16BE', 'UTF-8');
3332 14
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16BE');
3333 14
      if ($test3 === $test) {
3334 14
        if (\count($strChars) === 0) {
3335 6
          $strChars = self::count_chars($str, true);
3336
        }
3337 14
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3338 14
          if (\in_array($test3char, $strChars, true) === true) {
3339 14
            $maybeUTF16BE++;
3340
          }
3341
        }
3342
      }
3343
    }
3344
3345 20
    if ($maybeUTF16BE !== $maybeUTF16LE) {
3346 6
      if ($maybeUTF16LE > $maybeUTF16BE) {
3347 4
        return 1;
3348
      }
3349
3350 6
      return 2;
3351
    }
3352
3353 16
    return false;
3354
  }
3355
3356
  /**
3357
   * Check if the string is UTF-32.
3358
   *
3359
   * @param mixed $str <p>The input string.</p>
3360
   * @param bool  $checkIfStringIsBinary
3361
   *
3362
   * @return int|false
3363
   *                   <strong>false</strong> if is't not UTF-32,<br>
3364
   *                   <strong>1</strong> for UTF-32LE,<br>
3365
   *                   <strong>2</strong> for UTF-32BE.
3366
   */
3367 16
  public static function is_utf32($str, $checkIfStringIsBinary = true)
3368
  {
3369
    // init
3370 16
    $str = (string)$str;
3371 16
    $strChars = [];
3372
3373
    if (
3374 16
        $checkIfStringIsBinary === true
3375
        &&
3376 16
        self::is_binary($str, true) === false
3377
    ) {
3378 2
      return false;
3379
    }
3380
3381 16
    if (self::$SUPPORT['mbstring'] === false) {
3382 2
      \trigger_error('UTF8::is_utf32() without mbstring may did not work correctly', E_USER_WARNING);
3383
    }
3384
3385 16
    $str = self::remove_bom($str);
3386
3387 16
    $maybeUTF32LE = 0;
3388 16
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32LE');
3389 16
    if ($test) {
3390 10
      $test2 = \mb_convert_encoding($test, 'UTF-32LE', 'UTF-8');
3391 10
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32LE');
3392 10
      if ($test3 === $test) {
3393 10
        if (\count($strChars) === 0) {
3394 10
          $strChars = self::count_chars($str, true);
3395
        }
3396 10
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3397 10
          if (\in_array($test3char, $strChars, true) === true) {
3398 10
            $maybeUTF32LE++;
3399
          }
3400
        }
3401
      }
3402
    }
3403
3404 16
    $maybeUTF32BE = 0;
3405 16
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32BE');
3406 16
    if ($test) {
3407 10
      $test2 = \mb_convert_encoding($test, 'UTF-32BE', 'UTF-8');
3408 10
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32BE');
3409 10
      if ($test3 === $test) {
3410 10
        if (\count($strChars) === 0) {
3411 6
          $strChars = self::count_chars($str, true);
3412
        }
3413 10
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3414 10
          if (\in_array($test3char, $strChars, true) === true) {
3415 10
            $maybeUTF32BE++;
3416
          }
3417
        }
3418
      }
3419
    }
3420
3421 16
    if ($maybeUTF32BE !== $maybeUTF32LE) {
3422 2
      if ($maybeUTF32LE > $maybeUTF32BE) {
3423 2
        return 1;
3424
      }
3425
3426 2
      return 2;
3427
    }
3428
3429 16
    return false;
3430
  }
3431
3432
  /**
3433
   * Checks whether the passed string contains only byte sequences that appear valid UTF-8 characters.
3434
   *
3435
   * @see    http://hsivonen.iki.fi/php-utf8/
3436
   *
3437
   * @param string|string[] $str    <p>The string to be checked.</p>
3438
   * @param bool            $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
3439
   *
3440
   * @return bool
3441
   */
3442 106
  public static function is_utf8($str, bool $strict = false): bool
3443
  {
3444 106
    if (\is_array($str) === true) {
3445 2
      foreach ($str as $k => $v) {
3446 2
        if (false === self::is_utf8($v, $strict)) {
3447 2
          return false;
3448
        }
3449
      }
3450
3451
      return true;
3452
    }
3453
3454 106
    if ('' === $str) {
3455 12
      return true;
3456
    }
3457
3458 102
    if ($strict === true) {
3459 2
      $isBinary = self::is_binary($str, true);
3460
3461 2
      if ($isBinary && self::is_utf16($str, false) !== false) {
3462 2
        return false;
3463
      }
3464
3465
      if ($isBinary && self::is_utf32($str, false) !== false) {
3466
        return false;
3467
      }
3468
    }
3469
3470 102
    if (self::pcre_utf8_support() !== true) {
3471
3472
      // If even just the first character can be matched, when the /u
3473
      // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow
3474
      // invalid, nothing at all will match, even if the string contains
3475
      // some valid sequences
3476
      return (\preg_match('/^.{1}/us', $str, $ar) === 1);
3477
    }
3478
3479 102
    $mState = 0; // cached expected number of octets after the current octet
3480
    // until the beginning of the next UTF8 character sequence
3481 102
    $mUcs4 = 0; // cached Unicode character
3482 102
    $mBytes = 1; // cached expected number of octets in the current sequence
3483
3484 102
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3485
      self::checkForSupport();
3486
    }
3487
3488 102
    if (self::$ORD === null) {
3489
      self::$ORD = self::getData('ord');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('ord') can also be of type false. However, the property $ORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3490
    }
3491
3492 102
    $len = self::strlen_in_byte((string)$str);
3493
    /** @noinspection ForeachInvariantsInspection */
3494 102
    for ($i = 0; $i < $len; $i++) {
3495 102
      $in = self::$ORD[$str[$i]];
3496 102
      if ($mState === 0) {
3497
        // When mState is zero we expect either a US-ASCII character or a
3498
        // multi-octet sequence.
3499 102
        if (0 === (0x80 & $in)) {
3500
          // US-ASCII, pass straight through.
3501 98
          $mBytes = 1;
3502 83
        } elseif (0xC0 === (0xE0 & $in)) {
3503
          // First octet of 2 octet sequence.
3504 74
          $mUcs4 = $in;
3505 74
          $mUcs4 = ($mUcs4 & 0x1F) << 6;
3506 74
          $mState = 1;
3507 74
          $mBytes = 2;
3508 58
        } elseif (0xE0 === (0xF0 & $in)) {
3509
          // First octet of 3 octet sequence.
3510 41
          $mUcs4 = $in;
3511 41
          $mUcs4 = ($mUcs4 & 0x0F) << 12;
3512 41
          $mState = 2;
3513 41
          $mBytes = 3;
3514 30
        } elseif (0xF0 === (0xF8 & $in)) {
3515
          // First octet of 4 octet sequence.
3516 19
          $mUcs4 = $in;
3517 19
          $mUcs4 = ($mUcs4 & 0x07) << 18;
3518 19
          $mState = 3;
3519 19
          $mBytes = 4;
3520 13
        } elseif (0xF8 === (0xFC & $in)) {
3521
          /* First octet of 5 octet sequence.
3522
          *
3523
          * This is illegal because the encoded codepoint must be either
3524
          * (a) not the shortest form or
3525
          * (b) outside the Unicode range of 0-0x10FFFF.
3526
          * Rather than trying to resynchronize, we will carry on until the end
3527
          * of the sequence and let the later error handling code catch it.
3528
          */
3529 5
          $mUcs4 = $in;
3530 5
          $mUcs4 = ($mUcs4 & 0x03) << 24;
3531 5
          $mState = 4;
3532 5
          $mBytes = 5;
3533 10
        } elseif (0xFC === (0xFE & $in)) {
3534
          // First octet of 6 octet sequence, see comments for 5 octet sequence.
3535 5
          $mUcs4 = $in;
3536 5
          $mUcs4 = ($mUcs4 & 1) << 30;
3537 5
          $mState = 5;
3538 5
          $mBytes = 6;
3539
        } else {
3540
          // Current octet is neither in the US-ASCII range nor a legal first
3541
          // octet of a multi-octet sequence.
3542 102
          return false;
3543
        }
3544
      } else {
3545
        // When mState is non-zero, we expect a continuation of the multi-octet
3546
        // sequence
3547 83
        if (0x80 === (0xC0 & $in)) {
3548
          // Legal continuation.
3549 75
          $shift = ($mState - 1) * 6;
3550 75
          $tmp = $in;
3551 75
          $tmp = ($tmp & 0x0000003F) << $shift;
3552 75
          $mUcs4 |= $tmp;
3553
          // Prefix: End of the multi-octet sequence. mUcs4 now contains the final
3554
          // Unicode code point to be output.
3555 75
          if (0 === --$mState) {
3556
            // Check for illegal sequences and code points.
3557
            //
3558
            // From Unicode 3.1, non-shortest form is illegal
3559
            if (
3560 75
                (2 === $mBytes && $mUcs4 < 0x0080)
3561
                ||
3562 75
                (3 === $mBytes && $mUcs4 < 0x0800)
3563
                ||
3564 75
                (4 === $mBytes && $mUcs4 < 0x10000)
3565
                ||
3566 75
                (4 < $mBytes)
3567
                ||
3568
                // From Unicode 3.2, surrogate characters are illegal.
3569 75
                (($mUcs4 & 0xFFFFF800) === 0xD800)
3570
                ||
3571
                // Code points outside the Unicode range are illegal.
3572 75
                ($mUcs4 > 0x10FFFF)
3573
            ) {
3574 8
              return false;
3575
            }
3576
            // initialize UTF8 cache
3577 75
            $mState = 0;
3578 75
            $mUcs4 = 0;
3579 75
            $mBytes = 1;
3580
          }
3581
        } else {
3582
          // ((0xC0 & (*in) != 0x80) && (mState != 0))
3583
          // Incomplete multi-octet sequence.
3584 36
          return false;
3585
        }
3586
      }
3587
    }
3588
3589 66
    return true;
3590
  }
3591
3592
  /**
3593
   * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3594
   * Decodes a JSON string
3595
   *
3596
   * @link http://php.net/manual/en/function.json-decode.php
3597
   *
3598
   * @param string $json    <p>
3599
   *                        The <i>json</i> string being decoded.
3600
   *                        </p>
3601
   *                        <p>
3602
   *                        This function only works with UTF-8 encoded strings.
3603
   *                        </p>
3604
   *                        <p>PHP implements a superset of
3605
   *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3606
   *                        only supports these values when they are nested inside an array or an object.
3607
   *                        </p>
3608
   * @param bool   $assoc   [optional] <p>
3609
   *                        When <b>TRUE</b>, returned objects will be converted into
3610
   *                        associative arrays.
3611
   *                        </p>
3612
   * @param int    $depth   [optional] <p>
3613
   *                        User specified recursion depth.
3614
   *                        </p>
3615
   * @param int    $options [optional] <p>
3616
   *                        Bitmask of JSON decode options. Currently only
3617
   *                        <b>JSON_BIGINT_AS_STRING</b>
3618
   *                        is supported (default is to cast large integers as floats)
3619
   *                        </p>
3620
   *
3621
   * @return mixed
3622
   *                The value encoded in <i>json</i> in appropriate PHP type. Values true, false and
3623
   *                null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b> and <b>NULL</b> respectively.
3624
   *                <b>NULL</b> is returned if the <i>json</i> cannot be decoded or if the encoded data
3625
   *                is deeper than the recursion limit.
3626
   */
3627 24
  public static function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
3628
  {
3629 24
    $json = self::filter($json);
3630
3631 24
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3632
      self::checkForSupport();
3633
    }
3634
3635 24
    if (self::$SUPPORT['json'] === false) {
3636
      throw new \RuntimeException('ext-json: is not installed');
3637
    }
3638
3639
    /** @noinspection PhpComposerExtensionStubsInspection */
3640 24
    $json = \json_decode($json, $assoc, $depth, $options);
3641
3642 24
    return $json;
3643
  }
3644
3645
  /**
3646
   * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3647
   * Returns the JSON representation of a value.
3648
   *
3649
   * @link http://php.net/manual/en/function.json-encode.php
3650
   *
3651
   * @param mixed $value   <p>
3652
   *                       The <i>value</i> being encoded. Can be any type except
3653
   *                       a resource.
3654
   *                       </p>
3655
   *                       <p>
3656
   *                       All string data must be UTF-8 encoded.
3657
   *                       </p>
3658
   *                       <p>PHP implements a superset of
3659
   *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3660
   *                       only supports these values when they are nested inside an array or an object.
3661
   *                       </p>
3662
   * @param int   $options [optional] <p>
3663
   *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
3664
   *                       <b>JSON_HEX_TAG</b>,
3665
   *                       <b>JSON_HEX_AMP</b>,
3666
   *                       <b>JSON_HEX_APOS</b>,
3667
   *                       <b>JSON_NUMERIC_CHECK</b>,
3668
   *                       <b>JSON_PRETTY_PRINT</b>,
3669
   *                       <b>JSON_UNESCAPED_SLASHES</b>,
3670
   *                       <b>JSON_FORCE_OBJECT</b>,
3671
   *                       <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
3672
   *                       constants is described on
3673
   *                       the JSON constants page.
3674
   *                       </p>
3675
   * @param int   $depth   [optional] <p>
3676
   *                       Set the maximum depth. Must be greater than zero.
3677
   *                       </p>
3678
   *
3679
   * @return string|false
3680
   *                      A JSON encoded <strong>string</strong> on success or<br>
3681
   *                      <strong>FALSE</strong> on failure.
3682
   */
3683 5
  public static function json_encode($value, int $options = 0, int $depth = 512)
3684
  {
3685 5
    $value = self::filter($value);
3686
3687 5
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3688
      self::checkForSupport();
3689
    }
3690
3691 5
    if (self::$SUPPORT['json'] === false) {
3692
      throw new \RuntimeException('ext-json: is not installed');
3693
    }
3694
3695
    /** @noinspection PhpComposerExtensionStubsInspection */
3696 5
    $json = \json_encode($value, $options, $depth);
3697
3698 5
    return $json;
3699
  }
3700
3701
  /**
3702
   * Checks whether JSON is available on the server.
3703
   *
3704
   * @return bool
3705
   *              <strong>true</strong> if available, <strong>false</strong> otherwise
3706
   */
3707
  public static function json_loaded(): bool
3708
  {
3709
    return \function_exists('json_decode');
3710
  }
3711
3712
  /**
3713
   * Makes string's first char lowercase.
3714
   *
3715
   * @param string      $str                   <p>The input string</p>
3716
   * @param string      $encoding              [optional] <p>Set the charset for e.g. "mb_" function</p>
3717
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
3718
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
3719
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
3720
   *
3721
   * @return string The resulting string.
3722
   */
3723 46
  public static function lcfirst(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
3724
  {
3725 46
    $strPartTwo = self::substr($str, 1, null, $encoding, $cleanUtf8);
3726 46
    if ($strPartTwo === false) {
3727
      $strPartTwo = '';
3728
    }
3729
3730 46
    $strPartOne = self::strtolower(
3731 46
        (string)self::substr($str, 0, 1, $encoding, $cleanUtf8),
3732 46
        $encoding,
3733 46
        $cleanUtf8,
3734 46
        $lang,
3735 46
        $tryToKeepStringLength
3736
    );
3737
3738 46
    return $strPartOne . $strPartTwo;
3739
  }
3740
3741
  /**
3742
   * alias for "UTF8::lcfirst()"
3743
   *
3744
   * @see UTF8::lcfirst()
3745
   *
3746
   * @param string      $str
3747
   * @param string      $encoding
3748
   * @param bool        $cleanUtf8
3749
   * @param string|null $lang
3750
   * @param bool        $tryToKeepStringLength
3751
   *
3752
   * @return string
3753
   */
3754 2
  public static function lcword(
3755
      string $str,
3756
      string $encoding = 'UTF-8',
3757
      bool $cleanUtf8 = false,
3758
      string $lang = null,
3759
      bool $tryToKeepStringLength = false
3760
  ): string
3761
  {
3762 2
    return self::lcfirst($str, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
3763
  }
3764
3765
  /**
3766
   * Lowercase for all words in the string.
3767
   *
3768
   * @param string      $str                   <p>The input string.</p>
3769
   * @param string[]    $exceptions            [optional] <p>Exclusion for some words.</p>
3770
   * @param string      $charlist              [optional] <p>Additional chars that contains to words and do not start a
3771
   *                                           new word.</p>
3772
   * @param string      $encoding              [optional] <p>Set the charset.</p>
3773
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
3774
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
3775
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
3776
   *
3777
   * @return string
3778
   */
3779 2
  public static function lcwords(
3780
      string $str,
3781
      array $exceptions = [],
3782
      string $charlist = '',
3783
      string $encoding = 'UTF-8',
3784
      bool $cleanUtf8 = false,
3785
      string $lang = null,
3786
      bool $tryToKeepStringLength = false
3787
  ): string
3788
  {
3789 2
    if (!$str) {
3790 2
      return '';
3791
    }
3792
3793 2
    $words = self::str_to_words($str, $charlist);
3794 2
    $newWords = [];
3795
3796 2
    if (\count($exceptions) > 0) {
3797 2
      $useExceptions = true;
3798
    } else {
3799 2
      $useExceptions = false;
3800
    }
3801
3802 2
    foreach ($words as $word) {
3803
3804 2
      if (!$word) {
3805 2
        continue;
3806
      }
3807
3808
      if (
3809 2
          $useExceptions === false
3810
          ||
3811
          (
3812 2
              $useExceptions === true
3813
              &&
3814 2
              !\in_array($word, $exceptions, true)
3815
          )
3816
      ) {
3817 2
        $word = self::lcfirst($word, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
3818
      }
3819
3820 2
      $newWords[] = $word;
3821
    }
3822
3823 2
    return \implode('', $newWords);
3824
  }
3825
3826
  /**
3827
   * alias for "UTF8::lcfirst()"
3828
   *
3829
   * @see UTF8::lcfirst()
3830
   *
3831
   * @param string      $str
3832
   * @param string      $encoding
3833
   * @param bool        $cleanUtf8
3834
   * @param string|null $lang
3835
   * @param bool        $tryToKeepStringLength
3836
   *
3837
   * @return string
3838
   */
3839 5
  public static function lowerCaseFirst(
3840
      string $str,
3841
      string $encoding = 'UTF-8',
3842
      bool $cleanUtf8 = false,
3843
      string $lang = null,
3844
      bool $tryToKeepStringLength = false
3845
  ): string
3846
  {
3847 5
    return self::lcfirst($str, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
3848
  }
3849
3850
  /**
3851
   * Strip whitespace or other characters from beginning of a UTF-8 string.
3852
   *
3853
   * @param string $str   <p>The string to be trimmed</p>
3854
   * @param mixed  $chars <p>Optional characters to be stripped</p>
3855
   *
3856
   * @return string The string with unwanted characters stripped from the left.
3857
   */
3858 22
  public static function ltrim(string $str = '', $chars = INF): string
3859
  {
3860 22
    if ('' === $str) {
3861 3
      return '';
3862
    }
3863
3864
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
3865 21
    if ($chars === INF || !$chars) {
3866 14
      $pattern = "^[\pZ\pC]+";
3867
    } else {
3868 10
      $chars = \preg_quote($chars, '/');
3869 10
      $pattern = "^[$chars]+";
3870
    }
3871
3872 21
    return self::regex_replace($str, $pattern, '', '', '/');
3873
  }
3874
3875
  /**
3876
   * Returns the UTF-8 character with the maximum code point in the given data.
3877
   *
3878
   * @param string|array<string> $arg <p>A UTF-8 encoded string or an array of such strings.</p>
3879
   *
3880
   * @return string|null The character with the highest code point than others, returns null on failure or empty input.
3881
   */
3882 2
  public static function max($arg)
3883
  {
3884 2
    if (\is_array($arg) === true) {
3885 2
      $arg = \implode('', $arg);
3886
    }
3887
3888 2
    $codepoints = self::codepoints($arg, false);
3889 2
    if (\count($codepoints) === 0) {
3890 2
      return null;
3891
    }
3892
3893 2
    $codepoint_max = \max($codepoints);
3894
3895 2
    return self::chr($codepoint_max);
3896
  }
3897
3898
  /**
3899
   * Calculates and returns the maximum number of bytes taken by any
3900
   * UTF-8 encoded character in the given string.
3901
   *
3902
   * @param string $str <p>The original Unicode string.</p>
3903
   *
3904
   * @return int Max byte lengths of the given chars.
3905
   */
3906 2
  public static function max_chr_width(string $str): int
3907
  {
3908 2
    $bytes = self::chr_size_list($str);
3909 2
    if (\count($bytes) > 0) {
3910 2
      return (int)\max($bytes);
3911
    }
3912
3913 2
    return 0;
3914
  }
3915
3916
  /**
3917
   * Checks whether mbstring is available on the server.
3918
   *
3919
   * @return bool
3920
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
3921
   */
3922 27
  public static function mbstring_loaded(): bool
3923
  {
3924 27
    $return = \extension_loaded('mbstring') ? true : false;
3925
3926 27
    if ($return === true) {
3927 27
      \mb_internal_encoding('UTF-8');
3928
    }
3929
3930 27
    return $return;
3931
  }
3932
3933
  /**
3934
   * Checks whether mbstring "overloaded" is active on the server.
3935
   *
3936
   * @return bool
3937
   */
3938
  private static function mbstring_overloaded(): bool
3939
  {
3940
    /**
3941
     * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2
3942
     */
3943
3944
    /** @noinspection PhpComposerExtensionStubsInspection */
3945
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
3946
    return \defined('MB_OVERLOAD_STRING')
3947
           &&
3948
           (@\ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING);
3949
  }
3950
3951
  /**
3952
   * Returns the UTF-8 character with the minimum code point in the given data.
3953
   *
3954
   * @param mixed $arg <strong>A UTF-8 encoded string or an array of such strings.</strong>
3955
   *
3956
   * @return string|null The character with the lowest code point than others, returns null on failure or empty input.
3957
   */
3958 2
  public static function min($arg)
3959
  {
3960 2
    if (\is_array($arg) === true) {
3961 2
      $arg = \implode('', $arg);
3962
    }
3963
3964 2
    $codepoints = self::codepoints($arg, false);
3965 2
    if (\count($codepoints) === 0) {
3966 2
      return null;
3967
    }
3968
3969 2
    $codepoint_min = \min($codepoints);
3970
3971 2
    return self::chr($codepoint_min);
3972
  }
3973
3974
  /**
3975
   * alias for "UTF8::normalize_encoding()"
3976
   *
3977
   * @see        UTF8::normalize_encoding()
3978
   *
3979
   * @param mixed $encoding
3980
   * @param mixed $fallback
3981
   *
3982
   * @return mixed
3983
   *
3984
   * @deprecated <p>use "UTF8::normalize_encoding()"</p>
3985
   */
3986 2
  public static function normalizeEncoding($encoding, $fallback = '')
3987
  {
3988 2
    return self::normalize_encoding($encoding, $fallback);
3989
  }
3990
3991
  /**
3992
   * Normalize the encoding-"name" input.
3993
   *
3994
   * @param mixed $encoding <p>e.g.: ISO, UTF8, WINDOWS-1251 etc.</p>
3995
   * @param mixed $fallback <p>e.g.: UTF-8</p>
3996
   *
3997
   * @return mixed e.g.: ISO-8859-1, UTF-8, WINDOWS-1251 etc.<br>Will return a empty string as fallback (by default)
3998
   */
3999 341
  public static function normalize_encoding($encoding, $fallback = '')
4000
  {
4001 341
    static $STATIC_NORMALIZE_ENCODING_CACHE = [];
4002
4003
    // init
4004 341
    $encoding = (string)$encoding;
4005
4006
    if (
4007 341
        !$encoding
4008
        ||
4009 50
        $encoding === '1' // only a fallback, for non "strict_types" usage ...
4010
        ||
4011 341
        $encoding === '0' // only a fallback, for non "strict_types" usage ...
4012
    ) {
4013 296
      return $fallback;
4014
    }
4015
4016
    if (
4017 49
        'UTF-8' === $encoding
4018
        ||
4019 49
        'UTF8' === $encoding
4020
    ) {
4021 22
      return 'UTF-8';
4022
    }
4023
4024
    if (
4025 42
        '8BIT' === $encoding
4026
        ||
4027 42
        'BINARY' === $encoding
4028
    ) {
4029
      return 'CP850';
4030
    }
4031
4032
    if (
4033 42
        'HTML' === $encoding
4034
        ||
4035 42
        'HTML-ENTITIES' === $encoding
4036
    ) {
4037 2
      return 'HTML-ENTITIES';
4038
    }
4039
4040 42
    if (isset($STATIC_NORMALIZE_ENCODING_CACHE[$encoding])) {
4041 40
      return $STATIC_NORMALIZE_ENCODING_CACHE[$encoding];
4042
    }
4043
4044 6
    if (self::$ENCODINGS === null) {
4045 1
      self::$ENCODINGS = self::getData('encodings');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('encodings') can also be of type false. However, the property $ENCODINGS is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
4046
    }
4047
4048 6
    if (\in_array($encoding, self::$ENCODINGS, true)) {
0 ignored issues
show
Bug introduced by
It seems like self::ENCODINGS can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4048
    if (\in_array($encoding, /** @scrutinizer ignore-type */ self::$ENCODINGS, true)) {
Loading history...
4049 4
      $STATIC_NORMALIZE_ENCODING_CACHE[$encoding] = $encoding;
4050
4051 4
      return $encoding;
4052
    }
4053
4054 5
    $encodingOrig = $encoding;
4055 5
    $encoding = \strtoupper($encoding);
4056 5
    $encodingUpperHelper = \preg_replace('/[^a-zA-Z0-9\s]/', '', $encoding);
4057
4058
    $equivalences = [
4059 5
        'ISO8859'     => 'ISO-8859-1',
4060
        'ISO88591'    => 'ISO-8859-1',
4061
        'ISO'         => 'ISO-8859-1',
4062
        'LATIN'       => 'ISO-8859-1',
4063
        'LATIN1'      => 'ISO-8859-1', // Western European
4064
        'ISO88592'    => 'ISO-8859-2',
4065
        'LATIN2'      => 'ISO-8859-2', // Central European
4066
        'ISO88593'    => 'ISO-8859-3',
4067
        'LATIN3'      => 'ISO-8859-3', // Southern European
4068
        'ISO88594'    => 'ISO-8859-4',
4069
        'LATIN4'      => 'ISO-8859-4', // Northern European
4070
        'ISO88595'    => 'ISO-8859-5',
4071
        'ISO88596'    => 'ISO-8859-6', // Greek
4072
        'ISO88597'    => 'ISO-8859-7',
4073
        'ISO88598'    => 'ISO-8859-8', // Hebrew
4074
        'ISO88599'    => 'ISO-8859-9',
4075
        'LATIN5'      => 'ISO-8859-9', // Turkish
4076
        'ISO885911'   => 'ISO-8859-11',
4077
        'TIS620'      => 'ISO-8859-11', // Thai
4078
        'ISO885910'   => 'ISO-8859-10',
4079
        'LATIN6'      => 'ISO-8859-10', // Nordic
4080
        'ISO885913'   => 'ISO-8859-13',
4081
        'LATIN7'      => 'ISO-8859-13', // Baltic
4082
        'ISO885914'   => 'ISO-8859-14',
4083
        'LATIN8'      => 'ISO-8859-14', // Celtic
4084
        'ISO885915'   => 'ISO-8859-15',
4085
        'LATIN9'      => 'ISO-8859-15', // Western European (with some extra chars e.g. €)
4086
        'ISO885916'   => 'ISO-8859-16',
4087
        'LATIN10'     => 'ISO-8859-16', // Southeast European
4088
        'CP1250'      => 'WINDOWS-1250',
4089
        'WIN1250'     => 'WINDOWS-1250',
4090
        'WINDOWS1250' => 'WINDOWS-1250',
4091
        'CP1251'      => 'WINDOWS-1251',
4092
        'WIN1251'     => 'WINDOWS-1251',
4093
        'WINDOWS1251' => 'WINDOWS-1251',
4094
        'CP1252'      => 'WINDOWS-1252',
4095
        'WIN1252'     => 'WINDOWS-1252',
4096
        'WINDOWS1252' => 'WINDOWS-1252',
4097
        'CP1253'      => 'WINDOWS-1253',
4098
        'WIN1253'     => 'WINDOWS-1253',
4099
        'WINDOWS1253' => 'WINDOWS-1253',
4100
        'CP1254'      => 'WINDOWS-1254',
4101
        'WIN1254'     => 'WINDOWS-1254',
4102
        'WINDOWS1254' => 'WINDOWS-1254',
4103
        'CP1255'      => 'WINDOWS-1255',
4104
        'WIN1255'     => 'WINDOWS-1255',
4105
        'WINDOWS1255' => 'WINDOWS-1255',
4106
        'CP1256'      => 'WINDOWS-1256',
4107
        'WIN1256'     => 'WINDOWS-1256',
4108
        'WINDOWS1256' => 'WINDOWS-1256',
4109
        'CP1257'      => 'WINDOWS-1257',
4110
        'WIN1257'     => 'WINDOWS-1257',
4111
        'WINDOWS1257' => 'WINDOWS-1257',
4112
        'CP1258'      => 'WINDOWS-1258',
4113
        'WIN1258'     => 'WINDOWS-1258',
4114
        'WINDOWS1258' => 'WINDOWS-1258',
4115
        'UTF16'       => 'UTF-16',
4116
        'UTF32'       => 'UTF-32',
4117
        'UTF8'        => 'UTF-8',
4118
        'UTF'         => 'UTF-8',
4119
        'UTF7'        => 'UTF-7',
4120
        '8BIT'        => 'CP850',
4121
        'BINARY'      => 'CP850',
4122
    ];
4123
4124 5
    if (!empty($equivalences[$encodingUpperHelper])) {
4125 4
      $encoding = $equivalences[$encodingUpperHelper];
4126
    }
4127
4128 5
    $STATIC_NORMALIZE_ENCODING_CACHE[$encodingOrig] = $encoding;
4129
4130 5
    return $encoding;
4131
  }
4132
4133
  /**
4134
   * Standardize line ending to unix-like.
4135
   *
4136
   * @param string $str
4137
   *
4138
   * @return string
4139
   */
4140 5
  public static function normalize_line_ending(string $str): string
4141
  {
4142 5
    return (string)str_replace(["\r\n", "\r"], "\n", $str);
4143
  }
4144
4145
  /**
4146
   * Normalize some MS Word special characters.
4147
   *
4148
   * @param string $str <p>The string to be normalized.</p>
4149
   *
4150
   * @return string
4151
   */
4152 40
  public static function normalize_msword(string $str): string
4153
  {
4154 40
    if ('' === $str) {
4155 2
      return '';
4156
    }
4157
4158 40
    static $UTF8_MSWORD_KEYS_CACHE = null;
4159 40
    static $UTF8_MSWORD_VALUES_CACHE = null;
4160
4161 40
    if ($UTF8_MSWORD_KEYS_CACHE === null) {
4162
4163 1
      if (self::$UTF8_MSWORD === null) {
4164 1
        self::$UTF8_MSWORD = self::getData('utf8_msword');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('utf8_msword') can also be of type false. However, the property $UTF8_MSWORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
4165
      }
4166
4167 1
      $UTF8_MSWORD_KEYS_CACHE = \array_keys(self::$UTF8_MSWORD);
0 ignored issues
show
Bug introduced by
It seems like self::UTF8_MSWORD can also be of type false; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4167
      $UTF8_MSWORD_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$UTF8_MSWORD);
Loading history...
4168 1
      $UTF8_MSWORD_VALUES_CACHE = \array_values(self::$UTF8_MSWORD);
0 ignored issues
show
Bug introduced by
It seems like self::UTF8_MSWORD can also be of type false; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4168
      $UTF8_MSWORD_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$UTF8_MSWORD);
Loading history...
4169
    }
4170
4171 40
    return \str_replace($UTF8_MSWORD_KEYS_CACHE, $UTF8_MSWORD_VALUES_CACHE, $str);
4172
  }
4173
4174
  /**
4175
   * Normalize the whitespace.
4176
   *
4177
   * @param string $str                     <p>The string to be normalized.</p>
4178
   * @param bool   $keepNonBreakingSpace    [optional] <p>Set to true, to keep non-breaking-spaces.</p>
4179
   * @param bool   $keepBidiUnicodeControls [optional] <p>Set to true, to keep non-printable (for the web)
4180
   *                                        bidirectional text chars.</p>
4181
   *
4182
   * @return string
4183
   */
4184 88
  public static function normalize_whitespace(string $str, bool $keepNonBreakingSpace = false, bool $keepBidiUnicodeControls = false): string
4185
  {
4186 88
    if ('' === $str) {
4187 9
      return '';
4188
    }
4189
4190 88
    static $WHITESPACE_CACHE = [];
4191 88
    $cacheKey = (int)$keepNonBreakingSpace;
4192
4193 88
    if (!isset($WHITESPACE_CACHE[$cacheKey])) {
4194
4195 2
      $WHITESPACE_CACHE[$cacheKey] = self::$WHITESPACE_TABLE;
4196
4197 2
      if ($keepNonBreakingSpace === true) {
4198 1
        unset($WHITESPACE_CACHE[$cacheKey]['NO-BREAK SPACE']);
4199
      }
4200
4201 2
      $WHITESPACE_CACHE[$cacheKey] = \array_values($WHITESPACE_CACHE[$cacheKey]);
4202
    }
4203
4204 88
    if ($keepBidiUnicodeControls === false) {
4205 88
      static $BIDI_UNICODE_CONTROLS_CACHE = null;
4206
4207 88
      if ($BIDI_UNICODE_CONTROLS_CACHE === null) {
4208 1
        $BIDI_UNICODE_CONTROLS_CACHE = \array_values(self::$BIDI_UNI_CODE_CONTROLS_TABLE);
4209
      }
4210
4211 88
      $str = \str_replace($BIDI_UNICODE_CONTROLS_CACHE, '', $str);
4212
    }
4213
4214 88
    return \str_replace($WHITESPACE_CACHE[$cacheKey], ' ', $str);
4215
  }
4216
4217
  /**
4218
   * Calculates Unicode code point of the given UTF-8 encoded character.
4219
   *
4220
   * INFO: opposite to UTF8::chr()
4221
   *
4222
   * @param string $chr      <p>The character of which to calculate code point.<p/>
4223
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
4224
   *
4225
   * @return int
4226
   *             Unicode code point of the given character,<br>
4227
   *             0 on invalid UTF-8 byte sequence.
4228
   */
4229 35
  public static function ord($chr, string $encoding = 'UTF-8'): int
4230
  {
4231
    // init
4232 35
    $chr = (string)$chr;
4233
4234 35
    static $CHAR_CACHE = [];
4235
4236
    // save the original string
4237 35
    $chr_orig = $chr;
4238
4239 35
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4240 5
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
4241
    }
4242
4243 35
    $cacheKey = $chr_orig . $encoding;
4244 35
    if (isset($CHAR_CACHE[$cacheKey]) === true) {
4245 26
      return $CHAR_CACHE[$cacheKey];
4246
    }
4247
4248 27
    if (self::$ORD === null) {
4249
      self::$ORD = self::getData('ord');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('ord') can also be of type false. However, the property $ORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
4250
    }
4251
4252 27
    if (isset(self::$ORD[$chr])) {
4253 27
      return self::$ORD[$chr];
4254
    }
4255
4256
    // check again, if it's still not UTF-8
4257 7
    if ($encoding !== 'UTF-8') {
4258 1
      $chr = self::encode($encoding, $chr);
4259
    }
4260
4261 7
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4262
      self::checkForSupport();
4263
    }
4264
4265 7
    if (self::$SUPPORT['intlChar'] === true) {
4266
      /** @noinspection PhpComposerExtensionStubsInspection */
4267 6
      $code = \IntlChar::ord($chr);
4268 6
      if ($code) {
4269 5
        return $CHAR_CACHE[$cacheKey] = $code;
4270
      }
4271
    }
4272
4273
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
4274 2
    $chr = \unpack('C*', (string)self::substr($chr, 0, 4, 'CP850'));
4275 2
    $code = $chr ? $chr[1] : 0;
4276
4277 2
    if (0xF0 <= $code && isset($chr[4])) {
4278
      /** @noinspection UnnecessaryCastingInspection */
4279
      return $CHAR_CACHE[$cacheKey] = (int)((($code - 0xF0) << 18) + (($chr[2] - 0x80) << 12) + (($chr[3] - 0x80) << 6) + $chr[4] - 0x80);
4280
    }
4281
4282 2
    if (0xE0 <= $code && isset($chr[3])) {
4283
      /** @noinspection UnnecessaryCastingInspection */
4284 1
      return $CHAR_CACHE[$cacheKey] = (int)((($code - 0xE0) << 12) + (($chr[2] - 0x80) << 6) + $chr[3] - 0x80);
4285
    }
4286
4287 2
    if (0xC0 <= $code && isset($chr[2])) {
4288
      /** @noinspection UnnecessaryCastingInspection */
4289 1
      return $CHAR_CACHE[$cacheKey] = (int)((($code - 0xC0) << 6) + $chr[2] - 0x80);
4290
    }
4291
4292 1
    return $CHAR_CACHE[$cacheKey] = $code;
4293
  }
4294
4295
  /**
4296
   * Parses the string into an array (into the the second parameter).
4297
   *
4298
   * WARNING: Instead of "parse_str()" this method do not (re-)placing variables in the current scope,
4299
   *          if the second parameter is not set!
4300
   *
4301
   * @link http://php.net/manual/en/function.parse-str.php
4302
   *
4303
   * @param string $str       <p>The input string.</p>
4304
   * @param array  $result    <p>The result will be returned into this reference parameter.</p>
4305
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
4306
   *
4307
   * @return bool
4308
   *              Will return <strong>false</strong> if php can't parse the string and we haven't any $result.
4309
   */
4310 2
  public static function parse_str(string $str, &$result, bool $cleanUtf8 = false): bool
4311
  {
4312 2
    if ($cleanUtf8 === true) {
4313 2
      $str = self::clean($str);
4314
    }
4315
4316 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4317
      self::checkForSupport();
4318
    }
4319
4320 2
    if (self::$SUPPORT['mbstring'] === true) {
4321 2
      $return = \mb_parse_str($str, $result);
4322
4323 2
      return !($return === false || empty($result));
4324
    }
4325
4326
    /** @noinspection PhpVoidFunctionResultUsedInspection */
4327
    \parse_str($str, $result);
4328
4329
    return !empty($result);
4330
  }
4331
4332
  /**
4333
   * Checks if \u modifier is available that enables Unicode support in PCRE.
4334
   *
4335
   * @return bool
4336
   *              <strong>true</strong> if support is available,<br>
4337
   *              <strong>false</strong> otherwise.
4338
   */
4339 102
  public static function pcre_utf8_support(): bool
4340
  {
4341
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
4342 102
    return (bool)@\preg_match('//u', '');
4343
  }
4344
4345
  /**
4346
   * Create an array containing a range of UTF-8 characters.
4347
   *
4348
   * @param mixed $var1 <p>Numeric or hexadecimal code points, or a UTF-8 character to start from.</p>
4349
   * @param mixed $var2 <p>Numeric or hexadecimal code points, or a UTF-8 character to end at.</p>
4350
   *
4351
   * @return string[]
4352
   */
4353 2
  public static function range($var1, $var2): array
4354
  {
4355 2
    if (!$var1 || !$var2) {
4356 2
      return [];
4357
    }
4358
4359 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4360
      self::checkForSupport();
4361
    }
4362
4363 2
    if (self::$SUPPORT['ctype'] === false) {
4364
      throw new \RuntimeException('ext-ctype: is not installed');
4365
    }
4366
4367
    /** @noinspection PhpComposerExtensionStubsInspection */
4368 2
    if (\ctype_digit((string)$var1)) {
4369 2
      $start = (int)$var1;
4370 2
    } /** @noinspection PhpComposerExtensionStubsInspection */ elseif (\ctype_xdigit($var1)) {
4371
      $start = (int)self::hex_to_int($var1);
4372
    } else {
4373 2
      $start = self::ord($var1);
4374
    }
4375
4376 2
    if (!$start) {
4377
      return [];
4378
    }
4379
4380
    /** @noinspection PhpComposerExtensionStubsInspection */
4381 2
    if (\ctype_digit((string)$var2)) {
4382 2
      $end = (int)$var2;
4383 2
    } /** @noinspection PhpComposerExtensionStubsInspection */ elseif (\ctype_xdigit($var2)) {
4384
      $end = (int)self::hex_to_int($var2);
4385
    } else {
4386 2
      $end = self::ord($var2);
4387
    }
4388
4389 2
    if (!$end) {
4390
      return [];
4391
    }
4392
4393 2
    return \array_map(
4394
        [
4395 2
            self::class,
4396
            'chr',
4397
        ],
4398 2
        \range($start, $end)
4399
    );
4400
  }
4401
4402
  /**
4403
   * Multi decode html entity & fix urlencoded-win1252-chars.
4404
   *
4405
   * e.g:
4406
   * 'test+test'                     => 'test+test'
4407
   * 'D&#252;sseldorf'               => 'Düsseldorf'
4408
   * 'D%FCsseldorf'                  => 'Düsseldorf'
4409
   * 'D&#xFC;sseldorf'               => 'Düsseldorf'
4410
   * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
4411
   * 'Düsseldorf'                   => 'Düsseldorf'
4412
   * 'D%C3%BCsseldorf'               => 'Düsseldorf'
4413
   * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
4414
   * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
4415
   *
4416
   * @param string $str          <p>The input string.</p>
4417
   * @param bool   $multi_decode <p>Decode as often as possible.</p>
4418
   *
4419
   * @return string
4420
   */
4421 3
  public static function rawurldecode(string $str, bool $multi_decode = true): string
4422
  {
4423 3
    if ('' === $str) {
4424 2
      return '';
4425
    }
4426
4427 3
    $pattern = '/%u([0-9a-f]{3,4})/i';
4428 3
    if (\preg_match($pattern, $str)) {
4429 2
      $str = (string)\preg_replace($pattern, '&#x\\1;', \rawurldecode($str));
4430
    }
4431
4432 3
    $flags = ENT_QUOTES | ENT_HTML5;
4433
4434
    do {
4435 3
      $str_compare = $str;
4436
4437 3
      $str = self::fix_simple_utf8(
4438 3
          \rawurldecode(
4439 3
              self::html_entity_decode(
4440 3
                  self::to_utf8($str),
4441 3
                  $flags
4442
              )
4443
          )
4444
      );
4445
4446 3
    } while ($multi_decode === true && $str_compare !== $str);
4447
4448 3
    return $str;
4449
  }
4450
4451
  /**
4452
   * @param array $strings
4453
   * @param bool  $removeEmptyValues
4454
   * @param int   $removeShortValues
4455
   *
4456
   * @return array
4457
   */
4458 2
  private static function reduce_string_array(array $strings, bool $removeEmptyValues, int $removeShortValues = null): array
4459
  {
4460
    // init
4461 2
    $return = [];
4462
4463 2
    foreach ($strings as $str) {
4464
      if (
4465 2
          $removeShortValues !== null
4466
          &&
4467 2
          self::strlen($str) <= $removeShortValues
4468
      ) {
4469 2
        continue;
4470
      }
4471
4472
      if (
4473 2
          $removeEmptyValues === true
4474
          &&
4475 2
          \trim($str) === ''
4476
      ) {
4477 2
        continue;
4478
      }
4479
4480 2
      $return[] = $str;
4481
    }
4482
4483 2
    return $return;
4484
  }
4485
4486
  /**
4487
   * Replaces all occurrences of $pattern in $str by $replacement.
4488
   *
4489
   * @param string $str         <p>The input string.</p>
4490
   * @param string $pattern     <p>The regular expression pattern.</p>
4491
   * @param string $replacement <p>The string to replace with.</p>
4492
   * @param string $options     [optional] <p>Matching conditions to be used.</p>
4493
   * @param string $delimiter   [optional] <p>Delimiter the the regex. Default: '/'</p>
4494
   *
4495
   * @return string
4496
   */
4497 291
  public static function regex_replace(string $str, string $pattern, string $replacement, string $options = '', string $delimiter = '/'): string
4498
  {
4499 291
    if ($options === 'msr') {
4500 9
      $options = 'ms';
4501
    }
4502
4503
    // fallback
4504 291
    if (!$delimiter) {
4505
      $delimiter = '/';
4506
    }
4507
4508 291
    $str = (string)\preg_replace(
4509 291
        $delimiter . $pattern . $delimiter . 'u' . $options,
4510 291
        $replacement,
4511 291
        $str
4512
    );
4513
4514 291
    return $str;
4515
  }
4516
4517
  /**
4518
   * alias for "UTF8::remove_bom()"
4519
   *
4520
   * @see        UTF8::remove_bom()
4521
   *
4522
   * @param string $str
4523
   *
4524
   * @return string
4525
   *
4526
   * @deprecated <p>use "UTF8::remove_bom()"</p>
4527
   */
4528
  public static function removeBOM(string $str): string
4529
  {
4530
    return self::remove_bom($str);
4531
  }
4532
4533
  /**
4534
   * Remove the BOM from UTF-8 / UTF-16 / UTF-32 strings.
4535
   *
4536
   * @param string $str <p>The input string.</p>
4537
   *
4538
   * @return string String without UTF-BOM.
4539
   */
4540 80
  public static function remove_bom(string $str): string
4541
  {
4542 80
    if ('' === $str) {
4543 7
      return '';
4544
    }
4545
4546 80
    $strLength = self::strlen_in_byte($str);
4547 80
    foreach (self::$BOM as $bomString => $bomByteLength) {
4548 80
      if (0 === self::strpos_in_byte($str, $bomString, 0)) {
4549 10
        $strTmp = self::substr_in_byte($str, $bomByteLength, $strLength);
4550 10
        if ($strTmp === false) {
4551
          return '';
4552
        }
4553
4554 10
        $strLength -= $bomByteLength;
4555
4556 80
        $str = (string)$strTmp;
4557
      }
4558
    }
4559
4560 80
    return $str;
4561
  }
4562
4563
  /**
4564
   * Removes duplicate occurrences of a string in another string.
4565
   *
4566
   * @param string          $str  <p>The base string.</p>
4567
   * @param string|string[] $what <p>String to search for in the base string.</p>
4568
   *
4569
   * @return string The result string with removed duplicates.
4570
   */
4571 2
  public static function remove_duplicates(string $str, $what = ' '): string
4572
  {
4573 2
    if (\is_string($what) === true) {
4574 2
      $what = [$what];
4575
    }
4576
4577 2
    if (\is_array($what) === true) {
0 ignored issues
show
introduced by
The condition is_array($what) === true is always true.
Loading history...
4578
      /** @noinspection ForeachSourceInspection */
4579 2
      foreach ($what as $item) {
4580 2
        $str = (string)\preg_replace('/(' . \preg_quote($item, '/') . ')+/', $item, $str);
4581
      }
4582
    }
4583
4584 2
    return $str;
4585
  }
4586
4587
  /**
4588
   * Remove html via "strip_tags()" from the string.
4589
   *
4590
   * @param string $str
4591
   * @param string $allowableTags [optional] <p>You can use the optional second parameter to specify tags which should
4592
   *                              not be stripped. Default: null
4593
   *                              </p>
4594
   *
4595
   * @return string
4596
   */
4597 6
  public static function remove_html(string $str, string $allowableTags = ''): string
4598
  {
4599 6
    return \strip_tags($str, $allowableTags);
4600
  }
4601
4602
  /**
4603
   * Remove all breaks [<br> | \r\n | \r | \n | ...] from the string.
4604
   *
4605
   * @param string $str
4606
   * @param string $replacement [optional] <p>Default is a empty string.</p>
4607
   *
4608
   * @return string
4609
   */
4610 6
  public static function remove_html_breaks(string $str, string $replacement = ''): string
4611
  {
4612 6
    return (string)\preg_replace("#/\r\n|\r|\n|<br.*/?>#isU", $replacement, $str);
4613
  }
4614
4615
  /**
4616
   * Remove invisible characters from a string.
4617
   *
4618
   * e.g.: This prevents sandwiching null characters between ascii characters, like Java\0script.
4619
   *
4620
   * copy&past from https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php
4621
   *
4622
   * @param string $str
4623
   * @param bool   $url_encoded
4624
   * @param string $replacement
4625
   *
4626
   * @return string
4627
   */
4628 114
  public static function remove_invisible_characters(string $str, bool $url_encoded = true, string $replacement = ''): string
4629
  {
4630
    // init
4631 114
    $non_displayables = [];
4632
4633
    // every control character except newline (dec 10),
4634
    // carriage return (dec 13) and horizontal tab (dec 09)
4635 114
    if ($url_encoded) {
4636 114
      $non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
4637 114
      $non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
4638
    }
4639
4640 114
    $non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
4641
4642
    do {
4643 114
      $str = (string)\preg_replace($non_displayables, $replacement, $str, -1, $count);
4644 114
    } while ($count !== 0);
4645
4646 114
    return $str;
4647
  }
4648
4649
  /**
4650
   * Returns a new string with the prefix $substring removed, if present.
4651
   *
4652
   * @param string $str
4653
   * @param string $substring <p>The prefix to remove.</p>
4654
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
4655
   *
4656
   * @return string String without the prefix $substring.
4657
   */
4658 12
  public static function remove_left(string $str, string $substring, string $encoding = 'UTF-8'): string
4659
  {
4660 12
    if (self::str_starts_with($str, $substring)) {
4661
4662 6
      return (string)self::substr(
4663 6
          $str,
4664 6
          self::strlen($substring, $encoding),
0 ignored issues
show
Bug introduced by
It seems like self::strlen($substring, $encoding) can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

4664
          /** @scrutinizer ignore-type */ self::strlen($substring, $encoding),
Loading history...
4665 6
          null,
4666 6
          $encoding
4667
      );
4668
    }
4669
4670 6
    return $str;
4671
  }
4672
4673
  /**
4674
   * Returns a new string with the suffix $substring removed, if present.
4675
   *
4676
   * @param string $str
4677
   * @param string $substring <p>The suffix to remove.</p>
4678
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
4679
   *
4680
   * @return string String having a $str without the suffix $substring.
4681
   */
4682 12
  public static function remove_right(string $str, string $substring, string $encoding = 'UTF-8'): string
4683
  {
4684 12
    if (self::str_ends_with($str, $substring)) {
4685
4686 6
      return (string)self::substr(
4687 6
          $str,
4688 6
          0,
4689 6
          self::strlen($str, $encoding) - self::strlen($substring, $encoding)
4690
      );
4691
    }
4692
4693 6
    return $str;
4694
  }
4695
4696
  /**
4697
   * Replaces all occurrences of $search in $str by $replacement.
4698
   *
4699
   * @param string $str           <p>The input string.</p>
4700
   * @param string $search        <p>The needle to search for.</p>
4701
   * @param string $replacement   <p>The string to replace with.</p>
4702
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4703
   *
4704
   * @return string String after the replacements.
4705
   */
4706 29
  public static function replace(string $str, string $search, string $replacement, bool $caseSensitive = true): string
4707
  {
4708 29
    if ($caseSensitive) {
4709 22
      return self::str_replace($search, $replacement, $str);
4710
    }
4711
4712 7
    return self::str_ireplace($search, $replacement, $str);
4713
  }
4714
4715
  /**
4716
   * Replaces all occurrences of $search in $str by $replacement.
4717
   *
4718
   * @param string       $str           <p>The input string.</p>
4719
   * @param array        $search        <p>The elements to search for.</p>
4720
   * @param string|array $replacement   <p>The string to replace with.</p>
4721
   * @param bool         $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4722
   *
4723
   * @return string String after the replacements.
4724
   */
4725 30
  public static function replace_all(string $str, array $search, $replacement, bool $caseSensitive = true): string
4726
  {
4727 30
    if ($caseSensitive) {
4728 23
      return self::str_replace($search, $replacement, $str);
4729
    }
4730
4731 7
    return self::str_ireplace($search, $replacement, $str);
4732
  }
4733
4734
  /**
4735
   * Replace the diamond question mark (�) and invalid-UTF8 chars with the replacement.
4736
   *
4737
   * @param string $str                <p>The input string</p>
4738
   * @param string $replacementChar    <p>The replacement character.</p>
4739
   * @param bool   $processInvalidUtf8 <p>Convert invalid UTF-8 chars </p>
4740
   *
4741
   * @return string
4742
   */
4743 64
  public static function replace_diamond_question_mark(string $str, string $replacementChar = '', bool $processInvalidUtf8 = true): string
4744
  {
4745 64
    if ('' === $str) {
4746 9
      return '';
4747
    }
4748
4749 64
    if ($processInvalidUtf8 === true) {
4750 64
      $replacementCharHelper = $replacementChar;
4751 64
      if ($replacementChar === '') {
4752 64
        $replacementCharHelper = 'none';
4753
      }
4754
4755 64
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4756
        self::checkForSupport();
4757
      }
4758
4759 64
      if (self::$SUPPORT['mbstring'] === false) {
4760
        // if there is no native support for "mbstring",
4761
        // then we need to clean the string before ...
4762
        $str = self::clean($str);
4763
      }
4764
4765
      // always fallback via symfony polyfill
4766 64
      $save = \mb_substitute_character();
4767 64
      \mb_substitute_character($replacementCharHelper);
4768 64
      $strTmp = \mb_convert_encoding($str, 'UTF-8', 'UTF-8');
4769 64
      \mb_substitute_character($save);
4770
4771 64
      if (\is_string($strTmp)) {
0 ignored issues
show
introduced by
The condition is_string($strTmp) is always true.
Loading history...
4772 64
        $str = $strTmp;
4773
      } else {
4774
        $str = '';
4775
      }
4776
    }
4777
4778 64
    return str_replace(
4779
        [
4780 64
            "\xEF\xBF\xBD",
4781
            '�',
4782
        ],
4783
        [
4784 64
            $replacementChar,
4785 64
            $replacementChar,
4786
        ],
4787 64
        $str
4788
    );
4789
  }
4790
4791
  /**
4792
   * Strip whitespace or other characters from end of a UTF-8 string.
4793
   *
4794
   * @param string $str   <p>The string to be trimmed.</p>
4795
   * @param mixed  $chars <p>Optional characters to be stripped.</p>
4796
   *
4797
   * @return string The string with unwanted characters stripped from the right.
4798
   */
4799 22
  public static function rtrim(string $str = '', $chars = INF): string
4800
  {
4801 22
    if ('' === $str) {
4802 3
      return '';
4803
    }
4804
4805
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
4806 21
    if ($chars === INF || !$chars) {
4807 16
      $pattern = "[\pZ\pC]+\$";
4808
    } else {
4809 8
      $chars = \preg_quote($chars, '/');
4810 8
      $pattern = "[$chars]+\$";
4811
    }
4812
4813 21
    return self::regex_replace($str, $pattern, '', '', '/');
4814
  }
4815
4816
  /**
4817
   * rxClass
4818
   *
4819
   * @param string $s
4820
   * @param string $class
4821
   *
4822
   * @return string
4823
   */
4824 47
  private static function rxClass(string $s, string $class = ''): string
4825
  {
4826 47
    static $RX_CLASSS_CACHE = [];
4827
4828 47
    $cacheKey = $s . $class;
4829
4830 47
    if (isset($RX_CLASSS_CACHE[$cacheKey])) {
4831 35
      return $RX_CLASSS_CACHE[$cacheKey];
4832
    }
4833
4834
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
4835 16
    $class = [$class];
4836
4837
    /** @noinspection SuspiciousLoopInspection */
4838 16
    foreach (self::str_split($s) as $s) {
4839 15
      if ('-' === $s) {
4840
        $class[0] = '-' . $class[0];
4841 15
      } elseif (!isset($s[2])) {
4842 15
        $class[0] .= \preg_quote($s, '/');
4843 1
      } elseif (1 === self::strlen($s)) {
4844 1
        $class[0] .= $s;
4845
      } else {
4846 15
        $class[] = $s;
4847
      }
4848
    }
4849
4850 16
    if ($class[0]) {
4851 16
      $class[0] = '[' . $class[0] . ']';
4852
    }
4853
4854 16
    if (1 === \count($class)) {
4855 16
      $return = $class[0];
4856
    } else {
4857
      $return = '(?:' . \implode('|', $class) . ')';
4858
    }
4859
4860 16
    $RX_CLASSS_CACHE[$cacheKey] = $return;
4861
4862 16
    return $return;
4863
  }
4864
4865
  /**
4866
   * WARNING: Print native UTF-8 support (libs), e.g. for debugging.
4867
   */
4868 2
  public static function showSupport()
4869
  {
4870 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4871
      self::checkForSupport();
4872
    }
4873
4874 2
    echo '<pre>';
4875 2
    foreach (self::$SUPPORT as $key => $value) {
4876 2
      echo $key . ' - ' . \print_r($value, true) . "\n<br>";
4877
    }
4878 2
    echo '</pre>';
4879 2
  }
4880
4881
  /**
4882
   * Converts a UTF-8 character to HTML Numbered Entity like "&#123;".
4883
   *
4884
   * @param string $char           <p>The Unicode character to be encoded as numbered entity.</p>
4885
   * @param bool   $keepAsciiChars <p>Set to <strong>true</strong> to keep ASCII chars.</>
4886
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
4887
   *
4888
   * @return string The HTML numbered entity.
4889
   */
4890 2
  public static function single_chr_html_encode(string $char, bool $keepAsciiChars = false, string $encoding = 'UTF-8'): string
4891
  {
4892 2
    if ('' === $char) {
4893 2
      return '';
4894
    }
4895
4896
    if (
4897 2
        $keepAsciiChars === true
4898
        &&
4899 2
        self::is_ascii($char) === true
4900
    ) {
4901 2
      return $char;
4902
    }
4903
4904 2
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4905 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
4906
    }
4907
4908 2
    return '&#' . self::ord($char, $encoding) . ';';
4909
  }
4910
4911
  /**
4912
   * @param string $str
4913
   * @param int    $tabLength
4914
   *
4915
   * @return string
4916
   */
4917 5
  public static function spaces_to_tabs(string $str, int $tabLength = 4): string
4918
  {
4919 5
    return \str_replace(\str_repeat(' ', $tabLength), "\t", $str);
4920
  }
4921
4922
  /**
4923
   * Convert a string to an array of Unicode characters.
4924
   *
4925
   * @param string|int|string[]|int[] $str       <p>The string to split into array.</p>
4926
   * @param int                       $length    [optional] <p>Max character length of each array element.</p>
4927
   * @param bool                      $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
4928
   *
4929
   * @return string[] An array containing chunks of the string.
4930
   */
4931 86
  public static function split($str, int $length = 1, bool $cleanUtf8 = false): array
4932
  {
4933 86
    if ($length <= 0) {
4934 3
      return [];
4935
    }
4936
4937 85
    if (\is_array($str) === true) {
4938 2
      foreach ($str as $k => $v) {
4939 2
        $str[$k] = self::split($v, $length);
4940
      }
4941
4942 2
      return $str;
4943
    }
4944
4945
    // init
4946 85
    $str = (string)$str;
4947
4948 85
    if ('' === $str) {
4949 13
      return [];
4950
    }
4951
4952
    // init
4953 82
    $ret = [];
4954
4955 82
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4956
      self::checkForSupport();
4957
    }
4958
4959 82
    if ($cleanUtf8 === true) {
4960 18
      $str = self::clean($str);
4961
    }
4962
4963 82
    if (self::$SUPPORT['pcre_utf8'] === true) {
4964
4965 78
      \preg_match_all('/./us', $str, $retArray);
4966 78
      if (isset($retArray[0])) {
4967 78
        $ret = $retArray[0];
4968
      }
4969 78
      unset($retArray);
4970
4971
    } else {
4972
4973
      // fallback
4974
4975 8
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4976
        self::checkForSupport();
4977
      }
4978
4979 8
      $len = self::strlen_in_byte($str);
4980
4981
      /** @noinspection ForeachInvariantsInspection */
4982 8
      for ($i = 0; $i < $len; $i++) {
4983
4984 8
        if (($str[$i] & "\x80") === "\x00") {
4985
4986 8
          $ret[] = $str[$i];
4987
4988
        } elseif (
4989 8
            isset($str[$i + 1])
4990
            &&
4991 8
            ($str[$i] & "\xE0") === "\xC0"
4992
        ) {
4993
4994 4
          if (($str[$i + 1] & "\xC0") === "\x80") {
4995 4
            $ret[] = $str[$i] . $str[$i + 1];
4996
4997 4
            $i++;
4998
          }
4999
5000
        } elseif (
5001 6
            isset($str[$i + 2])
5002
            &&
5003 6
            ($str[$i] & "\xF0") === "\xE0"
5004
        ) {
5005
5006
          if (
5007 6
              ($str[$i + 1] & "\xC0") === "\x80"
5008
              &&
5009 6
              ($str[$i + 2] & "\xC0") === "\x80"
5010
          ) {
5011 6
            $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2];
5012
5013 6
            $i += 2;
5014
          }
5015
5016
        } elseif (
5017
            isset($str[$i + 3])
5018
            &&
5019
            ($str[$i] & "\xF8") === "\xF0"
5020
        ) {
5021
5022
          if (
5023
              ($str[$i + 1] & "\xC0") === "\x80"
5024
              &&
5025
              ($str[$i + 2] & "\xC0") === "\x80"
5026
              &&
5027
              ($str[$i + 3] & "\xC0") === "\x80"
5028
          ) {
5029
            $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2] . $str[$i + 3];
5030
5031
            $i += 3;
5032
          }
5033
5034
        }
5035
      }
5036
    }
5037
5038 82
    if ($length > 1) {
5039 11
      $ret = \array_chunk($ret, $length);
5040
5041 11
      return \array_map(
5042
          function ($item) {
5043 11
            return \implode('', $item);
5044 11
          }, $ret
5045
      );
5046
    }
5047
5048 75
    if (isset($ret[0]) && $ret[0] === '') {
5049
      return [];
5050
    }
5051
5052 75
    return $ret;
5053
  }
5054
5055
  /**
5056
   * Returns a camelCase version of the string. Trims surrounding spaces,
5057
   * capitalizes letters following digits, spaces, dashes and underscores,
5058
   * and removes spaces, dashes, as well as underscores.
5059
   *
5060
   * @param string      $str                   <p>The input string.</p>
5061
   * @param string      $encoding              [optional] <p>Default: UTF-8</p>
5062
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
5063
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
5064
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
5065
   *
5066
   * @return string
5067
   */
5068 32
  public static function str_camelize(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
5069
  {
5070 32
    $str = self::lcfirst(self::trim($str), $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
5071 32
    $str = (string)\preg_replace('/^[-_]+/', '', $str);
5072
5073 32
    $str = (string)\preg_replace_callback(
5074 32
        '/[-_\s]+(.)?/u',
5075
        function ($match) use ($encoding, $cleanUtf8, $lang, $tryToKeepStringLength) {
5076 27
          if (isset($match[1])) {
5077 27
            return UTF8::strtoupper($match[1], $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
5078
          }
5079
5080 1
          return '';
5081 32
        },
5082 32
        $str
5083
    );
5084
5085 32
    $str = (string)\preg_replace_callback(
5086 32
        '/[\d]+(.)?/u',
5087
        function ($match) use ($encoding, $cleanUtf8, $lang, $tryToKeepStringLength) {
5088 6
          return UTF8::strtoupper($match[0], $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
5089 32
        },
5090 32
        $str
5091
    );
5092
5093 32
    return $str;
5094
  }
5095
5096
  /**
5097
   * Returns the string with the first letter of each word capitalized,
5098
   * except for when the word is a name which shouldn't be capitalized.
5099
   *
5100
   * @param string $str
5101
   *
5102
   * @return string String with $str capitalized.
5103
   */
5104 1
  public static function str_capitalize_name(string $str): string
5105
  {
5106 1
    $str = self::collapse_whitespace($str);
5107
5108 1
    $str = self::str_capitalize_name_helper($str, ' ');
5109 1
    $str = self::str_capitalize_name_helper($str, '-');
5110
5111 1
    return $str;
5112
  }
5113
5114
  /**
5115
   * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius").
5116
   *
5117
   * @param string $names
5118
   * @param string $delimiter
5119
   * @param string $encoding
5120
   *
5121
   * @return string
5122
   */
5123 1
  private static function str_capitalize_name_helper(string $names, string $delimiter, string $encoding = 'UTF-8'): string
5124
  {
5125
    // init
5126 1
    $namesArray = \explode($delimiter, $names);
5127
5128 1
    if ($namesArray === false) {
5129
      return '';
5130
    }
5131
5132
    $specialCases = [
5133 1
        'names'    => [
5134
            'ab',
5135
            'af',
5136
            'al',
5137
            'and',
5138
            'ap',
5139
            'bint',
5140
            'binte',
5141
            'da',
5142
            'de',
5143
            'del',
5144
            'den',
5145
            'der',
5146
            'di',
5147
            'dit',
5148
            'ibn',
5149
            'la',
5150
            'mac',
5151
            'nic',
5152
            'of',
5153
            'ter',
5154
            'the',
5155
            'und',
5156
            'van',
5157
            'von',
5158
            'y',
5159
            'zu',
5160
        ],
5161
        'prefixes' => [
5162
            'al-',
5163
            "d'",
5164
            'ff',
5165
            "l'",
5166
            'mac',
5167
            'mc',
5168
            'nic',
5169
        ],
5170
    ];
5171
5172 1
    foreach ($namesArray as &$name) {
5173 1
      if (\in_array($name, $specialCases['names'], true)) {
5174 1
        continue;
5175
      }
5176
5177 1
      $continue = false;
5178
5179 1
      if ($delimiter == '-') {
5180 1
        foreach ($specialCases['names'] as $beginning) {
5181 1
          if (self::strpos($name, $beginning, 0, $encoding) === 0) {
5182 1
            $continue = true;
5183
          }
5184
        }
5185
      }
5186
5187 1
      foreach ($specialCases['prefixes'] as $beginning) {
5188 1
        if (self::strpos($name, $beginning, 0, $encoding) === 0) {
5189 1
          $continue = true;
5190
        }
5191
      }
5192
5193 1
      if ($continue) {
5194 1
        continue;
5195
      }
5196
5197 1
      $name = self::str_upper_first($name);
5198
    }
5199
5200 1
    return \implode($delimiter, $namesArray);
5201
  }
5202
5203
  /**
5204
   * Returns true if the string contains $needle, false otherwise. By default
5205
   * the comparison is case-sensitive, but can be made insensitive by setting
5206
   * $caseSensitive to false.
5207
   *
5208
   * @param string $haystack      <p>The input string.</p>
5209
   * @param string $needle        <p>Substring to look for.</p>
5210
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5211
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5212
   *
5213
   * @return bool Whether or not $haystack contains $needle.
5214
   */
5215 106
  public static function str_contains(string $haystack, string $needle, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5216
  {
5217 106
    if ('' === $haystack || '' === $needle) {
5218 1
      return false;
5219
    }
5220
5221
    // only a fallback to prevent BC in the api ...
5222 105
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
5223 2
      $encoding = (string)$caseSensitive;
5224
    }
5225
5226 105
    if ($caseSensitive) {
5227 55
      return (self::strpos($haystack, $needle, 0, $encoding) !== false);
5228
    }
5229
5230 50
    return (self::stripos($haystack, $needle, 0, $encoding) !== false);
5231
  }
5232
5233
  /**
5234
   * Returns true if the string contains all $needles, false otherwise. By
5235
   * default the comparison is case-sensitive, but can be made insensitive by
5236
   * setting $caseSensitive to false.
5237
   *
5238
   * @param string $haystack      <p>The input string.</p>
5239
   * @param array  $needles       <p>SubStrings to look for.</p>
5240
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5241
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5242
   *
5243
   * @return bool Whether or not $haystack contains $needle.
5244
   */
5245 44
  public static function str_contains_all(string $haystack, array $needles, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5246
  {
5247 44
    if ('' === $haystack) {
5248
      return false;
5249
    }
5250
5251 44
    if (empty($needles)) {
5252 1
      return false;
5253
    }
5254
5255
    // only a fallback to prevent BC in the api ...
5256 43
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
5257 1
      $encoding = (string)$caseSensitive;
5258
    }
5259
5260 43
    foreach ($needles as $needle) {
5261 43
      if (!self::str_contains($haystack, $needle, $caseSensitive, $encoding)) {
5262 43
        return false;
5263
      }
5264
    }
5265
5266 24
    return true;
5267
  }
5268
5269
  /**
5270
   * Returns true if the string contains any $needles, false otherwise. By
5271
   * default the comparison is case-sensitive, but can be made insensitive by
5272
   * setting $caseSensitive to false.
5273
   *
5274
   * @param string $haystack      <p>The input string.</p>
5275
   * @param array  $needles       <p>SubStrings to look for.</p>
5276
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5277
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5278
   *
5279
   * @return bool
5280
   *               Whether or not $str contains $needle.
5281
   */
5282 43
  public static function str_contains_any(string $haystack, array $needles, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5283
  {
5284 43
    if (empty($needles)) {
5285 1
      return false;
5286
    }
5287
5288 42
    foreach ($needles as $needle) {
5289 42
      if (self::str_contains($haystack, $needle, $caseSensitive, $encoding)) {
5290 42
        return true;
5291
      }
5292
    }
5293
5294 18
    return false;
5295
  }
5296
5297
  /**
5298
   * Returns a lowercase and trimmed string separated by dashes. Dashes are
5299
   * inserted before uppercase characters (with the exception of the first
5300
   * character of the string), and in place of spaces as well as underscores.
5301
   *
5302
   * @param string $str      <p>The input string.</p>
5303
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5304
   *
5305
   * @return string
5306
   */
5307 19
  public static function str_dasherize(string $str, string $encoding = 'UTF-8'): string
5308
  {
5309 19
    return self::str_delimit($str, '-', $encoding);
5310
  }
5311
5312
  /**
5313
   * Returns a lowercase and trimmed string separated by the given delimiter.
5314
   * Delimiters are inserted before uppercase characters (with the exception
5315
   * of the first character of the string), and in place of spaces, dashes,
5316
   * and underscores. Alpha delimiters are not converted to lowercase.
5317
   *
5318
   * @param string      $str                           <p>The input string.</p>
5319
   * @param string      $delimiter                     <p>Sequence used to separate parts of the string.</p>
5320
   * @param string      $encoding                      [optional] <p>Set the charset for e.g. "mb_" function</p>
5321
   * @param bool        $cleanUtf8                     [optional] <p>Remove non UTF-8 chars from the string.</p>
5322
   * @param string|null $lang                          [optional] <p>Set the language for special cases: az, el, lt,
5323
   *                                                   tr</p>
5324
   * @param bool        $tryToKeepStringLength         [optional] <p>true === try to keep the string length: e.g. ẞ ->
5325
   *                                                   ß</p>
5326
   *
5327
   * @return string
5328
   */
5329 49
  public static function str_delimit(
5330
      string $str,
5331
      string $delimiter,
5332
      string $encoding = 'UTF-8',
5333
      bool $cleanUtf8 = false,
5334
      string $lang = null,
5335
      bool $tryToKeepStringLength = false
5336
  ): string
5337
  {
5338 49
    $str = self::trim($str);
5339
5340 49
    $str = (string)\preg_replace('/\B([A-Z])/u', '-\1', $str);
5341
5342 49
    $str = self::strtolower($str, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
5343
5344 49
    return (string)\preg_replace('/[-_\s]+/u', $delimiter, $str);
5345
  }
5346
5347
  /**
5348
   * Optimized "mb_detect_encoding()"-function -> with support for UTF-16 and UTF-32.
5349
   *
5350
   * @param string $str <p>The input string.</p>
5351
   *
5352
   * @return false|string
5353
   *                      The detected string-encoding e.g. UTF-8 or UTF-16BE,<br>
5354
   *                      otherwise it will return false e.g. for BINARY or not detected encoding.
5355
   */
5356 30
  public static function str_detect_encoding($str)
5357
  {
5358
    // init
5359 30
    $str = (string)$str;
5360
5361
    //
5362
    // 1.) check binary strings (010001001...) like UTF-16 / UTF-32 / PDF / Images / ...
5363
    //
5364
5365 30
    if (self::is_binary($str, true) === true) {
5366
5367 10
      $isUtf16 = self::is_utf16($str, false);
5368 10
      if ($isUtf16 === 1) {
5369 2
        return 'UTF-16LE';
5370
      }
5371 10
      if ($isUtf16 === 2) {
5372 2
        return 'UTF-16BE';
5373
      }
5374
5375 8
      $isUtf32 = self::is_utf32($str, false);
5376 8
      if ($isUtf32 === 1) {
5377
        return 'UTF-32LE';
5378
      }
5379 8
      if ($isUtf32 === 2) {
5380
        return 'UTF-32BE';
5381
      }
5382
5383
      // is binary but not "UTF-16" or "UTF-32"
5384 8
      return false;
5385
    }
5386
5387
    //
5388
    // 2.) simple check for ASCII chars
5389
    //
5390
5391 26
    if (self::is_ascii($str) === true) {
5392 9
      return 'ASCII';
5393
    }
5394
5395
    //
5396
    // 3.) simple check for UTF-8 chars
5397
    //
5398
5399 26
    if (self::is_utf8($str) === true) {
5400 18
      return 'UTF-8';
5401
    }
5402
5403
    //
5404
    // 4.) check via "mb_detect_encoding()"
5405
    //
5406
    // INFO: UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always with "mb_detect_encoding()"
5407
5408
    $detectOrder = [
5409 16
        'ISO-8859-1',
5410
        'ISO-8859-2',
5411
        'ISO-8859-3',
5412
        'ISO-8859-4',
5413
        'ISO-8859-5',
5414
        'ISO-8859-6',
5415
        'ISO-8859-7',
5416
        'ISO-8859-8',
5417
        'ISO-8859-9',
5418
        'ISO-8859-10',
5419
        'ISO-8859-13',
5420
        'ISO-8859-14',
5421
        'ISO-8859-15',
5422
        'ISO-8859-16',
5423
        'WINDOWS-1251',
5424
        'WINDOWS-1252',
5425
        'WINDOWS-1254',
5426
        'CP932',
5427
        'CP936',
5428
        'CP950',
5429
        'CP866',
5430
        'CP850',
5431
        'CP51932',
5432
        'CP50220',
5433
        'CP50221',
5434
        'CP50222',
5435
        'ISO-2022-JP',
5436
        'ISO-2022-KR',
5437
        'JIS',
5438
        'JIS-ms',
5439
        'EUC-CN',
5440
        'EUC-JP',
5441
    ];
5442
5443 16
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
5444
      self::checkForSupport();
5445
    }
5446
5447 16
    if (self::$SUPPORT['mbstring'] === true) {
5448
      // info: do not use the symfony polyfill here
5449 16
      $encoding = \mb_detect_encoding($str, $detectOrder, true);
5450 16
      if ($encoding) {
5451 16
        return $encoding;
5452
      }
5453
    }
5454
5455
    //
5456
    // 5.) check via "iconv()"
5457
    //
5458
5459
    if (self::$ENCODINGS === null) {
5460
      self::$ENCODINGS = self::getData('encodings');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('encodings') can also be of type false. However, the property $ENCODINGS is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
5461
    }
5462
5463
    foreach (self::$ENCODINGS as $encodingTmp) {
5464
      # INFO: //IGNORE but still throw notice
5465
      /** @noinspection PhpUsageOfSilenceOperatorInspection */
5466
      if ((string)@\iconv($encodingTmp, $encodingTmp . '//IGNORE', $str) === $str) {
5467
        return $encodingTmp;
5468
      }
5469
    }
5470
5471
    return false;
5472
  }
5473
5474
  /**
5475
   * Check if the string ends with the given substring.
5476
   *
5477
   * @param string $haystack <p>The string to search in.</p>
5478
   * @param string $needle   <p>The substring to search for.</p>
5479
   *
5480
   * @return bool
5481
   */
5482 40
  public static function str_ends_with(string $haystack, string $needle): bool
5483
  {
5484 40
    if ('' === $haystack || '' === $needle) {
5485 4
      return false;
5486
    }
5487
5488 38
    return \substr($haystack, -\strlen($needle)) === $needle;
5489
  }
5490
5491
  /**
5492
   * Returns true if the string ends with any of $substrings, false otherwise.
5493
   *
5494
   * - case-sensitive
5495
   *
5496
   * @param string   $str        <p>The input string.</p>
5497
   * @param string[] $substrings <p>Substrings to look for.</p>
5498
   *
5499
   * @return bool Whether or not $str ends with $substring.
5500
   */
5501 7
  public static function str_ends_with_any(string $str, array $substrings): bool
5502
  {
5503 7
    if (empty($substrings)) {
5504
      return false;
5505
    }
5506
5507 7
    foreach ($substrings as $substring) {
5508 7
      if (self::str_ends_with($str, $substring)) {
5509 7
        return true;
5510
      }
5511
    }
5512
5513 6
    return false;
5514
  }
5515
5516
  /**
5517
   * Ensures that the string begins with $substring. If it doesn't, it's
5518
   * prepended.
5519
   *
5520
   * @param string $str       <p>The input string.</p>
5521
   * @param string $substring <p>The substring to add if not present.</p>
5522
   *
5523
   * @return string
5524
   */
5525 10
  public static function str_ensure_left(string $str, string $substring): string
5526
  {
5527 10
    if (!self::str_starts_with($str, $substring)) {
5528 4
      $str = $substring . $str;
5529
    }
5530
5531 10
    return $str;
5532
  }
5533
5534
  /**
5535
   * Ensures that the string ends with $substring. If it doesn't, it's appended.
5536
   *
5537
   * @param string $str       <p>The input string.</p>
5538
   * @param string $substring <p>The substring to add if not present.</p>
5539
   *
5540
   * @return string
5541
   */
5542 10
  public static function str_ensure_right(string $str, string $substring): string
5543
  {
5544 10
    if (!self::str_ends_with($str, $substring)) {
5545 4
      $str .= $substring;
5546
    }
5547
5548 10
    return $str;
5549
  }
5550
5551
  /**
5552
   * Capitalizes the first word of the string, replaces underscores with
5553
   * spaces, and strips '_id'.
5554
   *
5555
   * @param string $str
5556
   *
5557
   * @return string
5558
   */
5559 3
  public static function str_humanize($str): string
5560
  {
5561 3
    $str = self::str_replace(
5562
        [
5563 3
            '_id',
5564
            '_',
5565
        ],
5566
        [
5567 3
            '',
5568
            ' ',
5569
        ],
5570 3
        $str
5571
    );
5572
5573 3
    return self::ucfirst(self::trim($str));
5574
  }
5575
5576
  /**
5577
   * Check if the string ends with the given substring, case insensitive.
5578
   *
5579
   * @param string $haystack <p>The string to search in.</p>
5580
   * @param string $needle   <p>The substring to search for.</p>
5581
   *
5582
   * @return bool
5583
   */
5584 12
  public static function str_iends_with(string $haystack, string $needle): bool
5585
  {
5586 12
    if ('' === $haystack || '' === $needle) {
5587 2
      return false;
5588
    }
5589
5590 12
    if (self::strcasecmp(\substr($haystack, -\strlen($needle)), $needle) === 0) {
5591 12
      return true;
5592
    }
5593
5594 8
    return false;
5595
  }
5596
5597
  /**
5598
   * Returns true if the string ends with any of $substrings, false otherwise.
5599
   *
5600
   * - case-insensitive
5601
   *
5602
   * @param string   $str        <p>The input string.</p>
5603
   * @param string[] $substrings <p>Substrings to look for.</p>
5604
   *
5605
   * @return bool Whether or not $str ends with $substring.
5606
   */
5607 4
  public static function str_iends_with_any(string $str, array $substrings): bool
5608
  {
5609 4
    if (empty($substrings)) {
5610
      return false;
5611
    }
5612
5613 4
    foreach ($substrings as $substring) {
5614 4
      if (self::str_iends_with($str, $substring)) {
5615 4
        return true;
5616
      }
5617
    }
5618
5619
    return false;
5620
  }
5621
5622
  /**
5623
   * Returns the index of the first occurrence of $needle in the string,
5624
   * and false if not found. Accepts an optional offset from which to begin
5625
   * the search.
5626
   *
5627
   * @param string $str      <p>The input string.</p>
5628
   * @param string $needle   <p>Substring to look for.</p>
5629
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5630
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5631
   *
5632
   * @return int|false
5633
   *                    The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5634
   */
5635 2
  public static function str_iindex_first(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5636
  {
5637 2
    return self::stripos(
5638 2
        $str,
5639 2
        $needle,
5640 2
        $offset,
5641 2
        $encoding
5642
    );
5643
  }
5644
5645
  /**
5646
   * Returns the index of the last occurrence of $needle in the string,
5647
   * and false if not found. Accepts an optional offset from which to begin
5648
   * the search. Offsets may be negative to count from the last character
5649
   * in the string.
5650
   *
5651
   * @param string $str      <p>The input string.</p>
5652
   * @param string $needle   <p>Substring to look for.</p>
5653
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5654
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5655
   *
5656
   * @return int|false
5657
   *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5658
   */
5659 2
  public static function str_iindex_last(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5660
  {
5661 2
    return self::strripos(
5662 2
        $str,
5663 2
        $needle,
5664 2
        $offset,
5665 2
        $encoding
5666
    );
5667
  }
5668
5669
  /**
5670
   * Returns the index of the first occurrence of $needle in the string,
5671
   * and false if not found. Accepts an optional offset from which to begin
5672
   * the search.
5673
   *
5674
   * @param string $str      <p>The input string.</p>
5675
   * @param string $needle   <p>Substring to look for.</p>
5676
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5677
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5678
   *
5679
   * @return int|false
5680
   *                   The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5681
   */
5682 12
  public static function str_index_first(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5683
  {
5684 12
    return self::strpos(
5685 12
        $str,
5686 12
        $needle,
5687 12
        $offset,
5688 12
        $encoding
5689
    );
5690
  }
5691
5692
  /**
5693
   * Returns the index of the last occurrence of $needle in the string,
5694
   * and false if not found. Accepts an optional offset from which to begin
5695
   * the search. Offsets may be negative to count from the last character
5696
   * in the string.
5697
   *
5698
   * @param string $str      <p>The input string.</p>
5699
   * @param string $needle   <p>Substring to look for.</p>
5700
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5701
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5702
   *
5703
   * @return int|false
5704
   *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5705
   */
5706 12
  public static function str_index_last(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5707
  {
5708 12
    return self::strrpos(
5709 12
        $str,
5710 12
        $needle,
5711 12
        $offset,
5712 12
        $encoding
5713
    );
5714
  }
5715
5716
  /**
5717
   * Inserts $substring into the string at the $index provided.
5718
   *
5719
   * @param string $str       <p>The input string.</p>
5720
   * @param string $substring <p>String to be inserted.</p>
5721
   * @param int    $index     <p>The index at which to insert the substring.</p>
5722
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5723
   *
5724
   * @return string
5725
   */
5726 8
  public static function str_insert(string $str, string $substring, int $index, string $encoding = 'UTF-8'): string
5727
  {
5728 8
    $len = self::strlen($str, $encoding);
5729
5730 8
    if ($index > $len) {
5731 1
      return $str;
5732
    }
5733
5734 7
    $start = self::substr($str, 0, $index, $encoding);
5735 7
    $end = self::substr($str, $index, $len, $encoding);
0 ignored issues
show
Bug introduced by
It seems like $len can also be of type false; however, parameter $length of voku\helper\UTF8::substr() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5735
    $end = self::substr($str, $index, /** @scrutinizer ignore-type */ $len, $encoding);
Loading history...
5736
5737 7
    return $start . $substring . $end;
0 ignored issues
show
Bug introduced by
Are you sure $start of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5737
    return /** @scrutinizer ignore-type */ $start . $substring . $end;
Loading history...
Bug introduced by
Are you sure $end of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

5737
    return $start . $substring . /** @scrutinizer ignore-type */ $end;
Loading history...
5738
  }
5739
5740
  /**
5741
   * Case-insensitive and UTF-8 safe version of <function>str_replace</function>.
5742
   *
5743
   * @link  http://php.net/manual/en/function.str-ireplace.php
5744
   *
5745
   * @param mixed $search  <p>
5746
   *                       Every replacement with search array is
5747
   *                       performed on the result of previous replacement.
5748
   *                       </p>
5749
   * @param mixed $replace <p>
5750
   *                       </p>
5751
   * @param mixed $subject <p>
5752
   *                       If subject is an array, then the search and
5753
   *                       replace is performed with every entry of
5754
   *                       subject, and the return value is an array as
5755
   *                       well.
5756
   *                       </p>
5757
   * @param int   $count   [optional] <p>
5758
   *                       The number of matched and replaced needles will
5759
   *                       be returned in count which is passed by
5760
   *                       reference.
5761
   *                       </p>
5762
   *
5763
   * @return mixed A string or an array of replacements.
5764
   */
5765 41
  public static function str_ireplace($search, $replace, $subject, &$count = null)
5766
  {
5767 41
    $search = (array)$search;
5768
5769
    /** @noinspection AlterInForeachInspection */
5770 41
    foreach ($search as &$s) {
5771 41
      $s = (string)$s;
5772 41
      if ('' === $s) {
5773 7
        $s = '/^(?<=.)$/';
5774
      } else {
5775 41
        $s = '/' . \preg_quote($s, '/') . '/ui';
5776
      }
5777
    }
5778
5779 41
    $subject = \preg_replace($search, $replace, $subject, -1, $replace);
5780 41
    $count = $replace; // used as reference parameter
5781
5782 41
    return $subject;
5783
  }
5784
5785
  /**
5786
   * Check if the string starts with the given substring, case insensitive.
5787
   *
5788
   * @param string $haystack <p>The string to search in.</p>
5789
   * @param string $needle   <p>The substring to search for.</p>
5790
   *
5791
   * @return bool
5792
   */
5793 12
  public static function str_istarts_with(string $haystack, string $needle): bool
5794
  {
5795 12
    if ('' === $haystack || '' === $needle) {
5796 2
      return false;
5797
    }
5798
5799 12
    if (self::stripos($haystack, $needle) === 0) {
5800 12
      return true;
5801
    }
5802
5803 4
    return false;
5804
  }
5805
5806
  /**
5807
   * Returns true if the string begins with any of $substrings, false otherwise.
5808
   *
5809
   * - case-insensitive
5810
   *
5811
   * @param string $str        <p>The input string.</p>
5812
   * @param array  $substrings <p>Substrings to look for.</p>
5813
   *
5814
   * @return bool Whether or not $str starts with $substring.
5815
   */
5816 4
  public static function str_istarts_with_any(string $str, array $substrings): bool
5817
  {
5818 4
    if ('' === $str) {
5819
      return false;
5820
    }
5821
5822 4
    if (empty($substrings)) {
5823
      return false;
5824
    }
5825
5826 4
    foreach ($substrings as $substring) {
5827 4
      if (self::str_istarts_with($str, $substring)) {
5828 4
        return true;
5829
      }
5830
    }
5831
5832
    return false;
5833
  }
5834
5835
  /**
5836
   * Gets the substring after the first occurrence of a separator.
5837
   *
5838
   * @param string $str       <p>The input string.</p>
5839
   * @param string $separator <p>The string separator.</p>
5840
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5841
   *
5842
   * @return string
5843
   */
5844 1
  public static function str_isubstr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5845
  {
5846
    if (
5847 1
        $separator === ''
5848
        ||
5849 1
        $str === ''
5850
    ) {
5851 1
      return '';
5852
    }
5853
5854 1
    $offset = self::str_iindex_first($str, $separator);
5855 1
    if ($offset === false) {
5856 1
      return '';
5857
    }
5858
5859 1
    return (string)self::substr(
5860 1
        $str,
5861 1
        $offset + self::strlen($separator, $encoding),
5862 1
        null,
5863 1
        $encoding
5864
    );
5865
  }
5866
5867
  /**
5868
   * Gets the substring after the last occurrence of a separator.
5869
   *
5870
   * @param string $str       <p>The input string.</p>
5871
   * @param string $separator <p>The string separator.</p>
5872
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5873
   *
5874
   * @return string
5875
   */
5876 1
  public static function str_isubstr_after_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5877
  {
5878
    if (
5879 1
        $separator === ''
5880
        ||
5881 1
        $str === ''
5882
    ) {
5883 1
      return '';
5884
    }
5885
5886 1
    $offset = self::str_iindex_last($str, $separator);
5887 1
    if ($offset === false) {
5888 1
      return '';
5889
    }
5890
5891 1
    return (string)self::substr(
5892 1
        $str,
5893 1
        $offset + self::strlen($separator, $encoding),
5894 1
        null,
5895 1
        $encoding
5896
    );
5897
  }
5898
5899
  /**
5900
   * Gets the substring before the first occurrence of a separator.
5901
   *
5902
   * @param string $str       <p>The input string.</p>
5903
   * @param string $separator <p>The string separator.</p>
5904
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5905
   *
5906
   * @return string
5907
   */
5908 1
  public static function str_isubstr_before_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5909
  {
5910
    if (
5911 1
        $separator === ''
5912
        ||
5913 1
        $str === ''
5914
    ) {
5915 1
      return '';
5916
    }
5917
5918 1
    $offset = self::str_iindex_first($str, $separator);
5919 1
    if ($offset === false) {
5920 1
      return '';
5921
    }
5922
5923 1
    return (string)self::substr($str, 0, $offset, $encoding);
5924
  }
5925
5926
  /**
5927
   * Gets the substring before the last occurrence of a separator.
5928
   *
5929
   * @param string $str       <p>The input string.</p>
5930
   * @param string $separator <p>The string separator.</p>
5931
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5932
   *
5933
   * @return string
5934
   */
5935 1
  public static function str_isubstr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5936
  {
5937
    if (
5938 1
        $separator === ''
5939
        ||
5940 1
        $str === ''
5941
    ) {
5942 1
      return '';
5943
    }
5944
5945 1
    $offset = self::str_iindex_last($str, $separator);
5946 1
    if ($offset === false) {
5947 1
      return '';
5948
    }
5949
5950 1
    return (string)self::substr($str, 0, $offset, $encoding);
5951
  }
5952
5953
  /**
5954
   * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
5955
   *
5956
   * @param string $str          <p>The input string.</p>
5957
   * @param string $needle       <p>The string to look for.</p>
5958
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
5959
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
5960
   *
5961
   * @return string
5962
   */
5963 2
  public static function str_isubstr_first(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
5964
  {
5965
    if (
5966 2
        '' === $needle
5967
        ||
5968 2
        '' === $str
5969
    ) {
5970 2
      return '';
5971
    }
5972
5973 2
    $part = self::stristr(
5974 2
        $str,
5975 2
        $needle,
5976 2
        $beforeNeedle,
5977 2
        $encoding
5978
    );
5979 2
    if (false === $part) {
5980 2
      return '';
5981
    }
5982
5983 2
    return $part;
5984
  }
5985
5986
  /**
5987
   * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
5988
   *
5989
   * @param string $str          <p>The input string.</p>
5990
   * @param string $needle       <p>The string to look for.</p>
5991
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
5992
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
5993
   *
5994
   * @return string
5995
   */
5996 1
  public static function str_isubstr_last(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
5997
  {
5998
    if (
5999 1
        '' === $needle
6000
        ||
6001 1
        '' === $str
6002
    ) {
6003 1
      return '';
6004
    }
6005
6006 1
    $part = self::strrichr($str, $needle, $beforeNeedle, $encoding);
6007 1
    if (false === $part) {
6008 1
      return '';
6009
    }
6010
6011 1
    return $part;
6012
  }
6013
6014
  /**
6015
   * Returns the last $n characters of the string.
6016
   *
6017
   * @param string $str      <p>The input string.</p>
6018
   * @param int    $n        <p>Number of characters to retrieve from the end.</p>
6019
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6020
   *
6021
   * @return string
6022
   */
6023 12
  public static function str_last_char(string $str, int $n = 1, string $encoding = 'UTF-8'): string
6024
  {
6025 12
    if ($n <= 0) {
6026 4
      return '';
6027
    }
6028
6029 8
    $returnTmp = self::substr($str, -$n, null, $encoding);
6030
6031 8
    return ($returnTmp === false ? '' : $returnTmp);
6032
  }
6033
6034
  /**
6035
   * Limit the number of characters in a string.
6036
   *
6037
   * @param string $str      <p>The input string.</p>
6038
   * @param int    $length   [optional] <p>Default: 100</p>
6039
   * @param string $strAddOn [optional] <p>Default: …</p>
6040
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6041
   *
6042
   * @return string
6043
   */
6044 2
  public static function str_limit(string $str, int $length = 100, string $strAddOn = '…', string $encoding = 'UTF-8'): string
6045
  {
6046 2
    if ('' === $str) {
6047 2
      return '';
6048
    }
6049
6050 2
    if ($length <= 0) {
6051 2
      return '';
6052
    }
6053
6054 2
    if (self::strlen($str, $encoding) <= $length) {
6055 2
      return $str;
6056
    }
6057
6058 2
    return self::substr($str, 0, $length - self::strlen($strAddOn), $encoding) . $strAddOn;
0 ignored issues
show
Bug introduced by
Are you sure self::substr($str, 0, $l...($strAddOn), $encoding) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6058
    return /** @scrutinizer ignore-type */ self::substr($str, 0, $length - self::strlen($strAddOn), $encoding) . $strAddOn;
Loading history...
6059
  }
6060
6061
  /**
6062
   * Limit the number of characters in a string, but also after the next word.
6063
   *
6064
   * @param string $str      <p>The input string.</p>
6065
   * @param int    $length   [optional] <p>Default: 100</p>
6066
   * @param string $strAddOn [optional] <p>Default: …</p>
6067
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6068
   *
6069
   * @return string
6070
   */
6071 6
  public static function str_limit_after_word(string $str, int $length = 100, string $strAddOn = '…', string $encoding = 'UTF-8'): string
6072
  {
6073 6
    if ('' === $str) {
6074 2
      return '';
6075
    }
6076
6077 6
    if ($length <= 0) {
6078 2
      return '';
6079
    }
6080
6081 6
    if (self::strlen($str, $encoding) <= $length) {
6082 2
      return $str;
6083
    }
6084
6085 6
    if (self::substr($str, $length - 1, 1, $encoding) === ' ') {
6086 5
      return self::substr($str, 0, $length - 1, $encoding) . $strAddOn;
0 ignored issues
show
Bug introduced by
Are you sure self::substr($str, 0, $length - 1, $encoding) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6086
      return /** @scrutinizer ignore-type */ self::substr($str, 0, $length - 1, $encoding) . $strAddOn;
Loading history...
6087
    }
6088
6089 3
    $str = (string)self::substr($str, 0, $length, $encoding);
6090 3
    $array = \explode(' ', $str);
6091 3
    \array_pop($array);
6092 3
    $new_str = \implode(' ', $array);
6093
6094 3
    if ($new_str === '') {
6095 2
      $str = self::substr($str, 0, $length - 1, $encoding) . $strAddOn;
6096
    } else {
6097 3
      $str = $new_str . $strAddOn;
6098
    }
6099
6100 3
    return $str;
6101
  }
6102
6103
  /**
6104
   * Returns the longest common prefix between the string and $otherStr.
6105
   *
6106
   * @param string $str      <p>The input sting.</p>
6107
   * @param string $otherStr <p>Second string for comparison.</p>
6108
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6109
   *
6110
   * @return string
6111
   */
6112 10
  public static function str_longest_common_prefix(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6113
  {
6114 10
    $maxLength = \min(self::strlen($str, $encoding), self::strlen($otherStr, $encoding));
6115
6116 10
    $longestCommonPrefix = '';
6117 10
    for ($i = 0; $i < $maxLength; $i++) {
6118 8
      $char = self::substr($str, $i, 1, $encoding);
6119
6120 8
      if ($char == self::substr($otherStr, $i, 1, $encoding)) {
6121 6
        $longestCommonPrefix .= $char;
6122
      } else {
6123 6
        break;
6124
      }
6125
    }
6126
6127 10
    return $longestCommonPrefix;
6128
  }
6129
6130
  /**
6131
   * Returns the longest common substring between the string and $otherStr.
6132
   * In the case of ties, it returns that which occurs first.
6133
   *
6134
   * @param string $str
6135
   * @param string $otherStr <p>Second string for comparison.</p>
6136
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6137
   *
6138
   * @return string String with its $str being the longest common substring.
6139
   */
6140 11
  public static function str_longest_common_substring(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6141
  {
6142
    // Uses dynamic programming to solve
6143
    // http://en.wikipedia.org/wiki/Longest_common_substring_problem
6144 11
    $strLength = self::strlen($str, $encoding);
6145 11
    $otherLength = self::strlen($otherStr, $encoding);
6146
6147
    // Return if either string is empty
6148 11
    if ($strLength == 0 || $otherLength == 0) {
6149 2
      return '';
6150
    }
6151
6152 9
    $len = 0;
6153 9
    $end = 0;
6154 9
    $table = \array_fill(
6155 9
        0,
6156 9
        $strLength + 1,
6157 9
        \array_fill(0, $otherLength + 1, 0)
6158
    );
6159
6160 9
    for ($i = 1; $i <= $strLength; $i++) {
6161 9
      for ($j = 1; $j <= $otherLength; $j++) {
6162 9
        $strChar = self::substr($str, $i - 1, 1, $encoding);
6163 9
        $otherChar = self::substr($otherStr, $j - 1, 1, $encoding);
6164
6165 9
        if ($strChar == $otherChar) {
6166 8
          $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
6167 8
          if ($table[$i][$j] > $len) {
6168 8
            $len = $table[$i][$j];
6169 8
            $end = $i;
6170
          }
6171
        } else {
6172 9
          $table[$i][$j] = 0;
6173
        }
6174
      }
6175
    }
6176
6177 9
    $returnTmp = self::substr($str, $end - $len, $len, $encoding);
6178
6179 9
    return ($returnTmp === false ? '' : $returnTmp);
6180
  }
6181
6182
  /**
6183
   * Returns the longest common suffix between the string and $otherStr.
6184
   *
6185
   * @param string $str
6186
   * @param string $otherStr <p>Second string for comparison.</p>
6187
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6188
   *
6189
   * @return string
6190
   */
6191 10
  public static function str_longest_common_suffix(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6192
  {
6193 10
    $maxLength = \min(self::strlen($str, $encoding), self::strlen($otherStr, $encoding));
6194
6195 10
    $longestCommonSuffix = '';
6196 10
    for ($i = 1; $i <= $maxLength; $i++) {
6197 8
      $char = self::substr($str, -$i, 1, $encoding);
6198
6199 8
      if ($char == self::substr($otherStr, -$i, 1, $encoding)) {
6200 6
        $longestCommonSuffix = $char . $longestCommonSuffix;
0 ignored issues
show
Bug introduced by
Are you sure $char of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6200
        $longestCommonSuffix = /** @scrutinizer ignore-type */ $char . $longestCommonSuffix;
Loading history...
6201
      } else {
6202 6
        break;
6203
      }
6204
    }
6205
6206 10
    return $longestCommonSuffix;
6207
  }
6208
6209
  /**
6210
   * Returns true if $str matches the supplied pattern, false otherwise.
6211
   *
6212
   * @param string $str     <p>The input string.</p>
6213
   * @param string $pattern <p>Regex pattern to match against.</p>
6214
   *
6215
   * @return bool Whether or not $str matches the pattern.
6216
   */
6217 126
  public static function str_matches_pattern(string $str, string $pattern): bool
6218
  {
6219 126
    if (\preg_match('/' . $pattern . '/u', $str)) {
6220 87
      return true;
6221
    }
6222
6223 39
    return false;
6224
  }
6225
6226
  /**
6227
   * Returns whether or not a character exists at an index. Offsets may be
6228
   * negative to count from the last character in the string. Implements
6229
   * part of the ArrayAccess interface.
6230
   *
6231
   * @param string $str      <p>The input string.</p>
6232
   * @param int    $offset   <p>The index to check.</p>
6233
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6234
   *
6235
   *
6236
   * @return bool Whether or not the index exists.
6237
   */
6238 6
  public static function str_offset_exists(string $str, int $offset, string $encoding = 'UTF-8'): bool
6239
  {
6240
    // init
6241 6
    $length = self::strlen($str, $encoding);
6242
6243 6
    if ($offset >= 0) {
6244 3
      return ($length > $offset);
6245
    }
6246
6247 3
    return ($length >= \abs($offset));
6248
  }
6249
6250
  /**
6251
   * Returns the character at the given index. Offsets may be negative to
6252
   * count from the last character in the string. Implements part of the
6253
   * ArrayAccess interface, and throws an OutOfBoundsException if the index
6254
   * does not exist.
6255
   *
6256
   * @param string $str      <p>The input string.</p>
6257
   * @param int    $index    <p>The <strong>index</strong> from which to retrieve the char.</p>
6258
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6259
   *
6260
   * @return string The character at the specified index.
6261
   *
6262
   * @throws \OutOfBoundsException If the positive or negative offset does not exist.
6263
   */
6264 2
  public static function str_offset_get(string $str, int $index, string $encoding = 'UTF-8'): string
6265
  {
6266
    // init
6267 2
    $length = self::strlen($str);
6268
6269
    if (
6270 2
        ($index >= 0 && $length <= $index)
6271
        ||
6272 2
        $length < \abs($index)
6273
    ) {
6274 1
      throw new \OutOfBoundsException('No character exists at the index');
6275
    }
6276
6277 1
    return self::char_at($str, $index, $encoding);
6278
  }
6279
6280
  /**
6281
   * Pad a UTF-8 string to given length with another string.
6282
   *
6283
   * @param string $str        <p>The input string.</p>
6284
   * @param int    $pad_length <p>The length of return string.</p>
6285
   * @param string $pad_string [optional] <p>String to use for padding the input string.</p>
6286
   * @param int    $pad_type   [optional] <p>
6287
   *                           Can be <strong>STR_PAD_RIGHT</strong> (default),
6288
   *                           <strong>STR_PAD_LEFT</strong> or <strong>STR_PAD_BOTH</strong>
6289
   *                           </p>
6290
   * @param string $encoding   [optional] <p>Default: UTF-8</p>
6291
   *
6292
   * @return string Returns the padded string.
6293
   */
6294 41
  public static function str_pad(string $str, int $pad_length, string $pad_string = ' ', $pad_type = STR_PAD_RIGHT, string $encoding = 'UTF-8'): string
6295
  {
6296 41
    if ('' === $str) {
6297
      return '';
6298
    }
6299
6300 41
    if ($pad_type !== (int)$pad_type) {
6301 13
      if ($pad_type == 'left') {
6302 3
        $pad_type = STR_PAD_LEFT;
6303 10
      } elseif ($pad_type == 'right') {
6304 6
        $pad_type = STR_PAD_RIGHT;
6305 4
      } elseif ($pad_type == 'both') {
6306 3
        $pad_type = STR_PAD_BOTH;
6307
      } else {
6308 1
        throw new \InvalidArgumentException(
6309 1
            'Pad expects $padType to be "STR_PAD_*" or ' . "to be one of 'left', 'right' or 'both'"
6310
        );
6311
      }
6312
    }
6313
6314 40
    $str_length = self::strlen($str, $encoding);
6315
6316
    if (
6317 40
        $pad_length > 0
6318
        &&
6319 40
        $pad_length >= $str_length
6320
    ) {
6321 39
      $ps_length = self::strlen($pad_string, $encoding);
6322
6323 39
      $diff = ($pad_length - $str_length);
6324
6325
      switch ($pad_type) {
6326 39
        case STR_PAD_LEFT:
6327 13
          $pre = \str_repeat($pad_string, (int)\ceil($diff / $ps_length));
6328 13
          $pre = (string)self::substr($pre, 0, $diff, $encoding);
6329 13
          $post = '';
6330 13
          break;
6331
6332 29
        case STR_PAD_BOTH:
6333 14
          $pre = \str_repeat($pad_string, (int)\ceil($diff / $ps_length / 2));
6334 14
          $pre = (string)self::substr($pre, 0, (int)\floor($diff / 2), $encoding);
6335 14
          $post = \str_repeat($pad_string, (int)\ceil($diff / $ps_length / 2));
6336 14
          $post = (string)self::substr($post, 0, (int)\ceil($diff / 2), $encoding);
6337 14
          break;
6338
6339 18
        case STR_PAD_RIGHT:
6340
        default:
6341 18
          $post = \str_repeat($pad_string, (int)\ceil($diff / $ps_length));
6342 18
          $post = (string)self::substr($post, 0, $diff, $encoding);
6343 18
          $pre = '';
6344
      }
6345
6346 39
      return $pre . $str . $post;
6347
    }
6348
6349 4
    return $str;
6350
  }
6351
6352
  /**
6353
   * Returns a new string of a given length such that both sides of the
6354
   * string are padded. Alias for pad() with a $padType of 'both'.
6355
   *
6356
   * @param string $str
6357
   * @param int    $length   <p>Desired string length after padding.</p>
6358
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6359
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6360
   *
6361
   * @return string String with padding applied.
6362
   */
6363 11
  public static function str_pad_both(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6364
  {
6365 11
    $padding = $length - self::strlen($str, $encoding);
6366
6367 11
    return self::apply_padding($str, (int)\floor($padding / 2), (int)\ceil($padding / 2), $padStr, $encoding);
6368
  }
6369
6370
  /**
6371
   * Returns a new string of a given length such that the beginning of the
6372
   * string is padded. Alias for pad() with a $padType of 'left'.
6373
   *
6374
   * @param string $str
6375
   * @param int    $length   <p>Desired string length after padding.</p>
6376
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6377
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6378
   *
6379
   * @return string String with left padding.
6380
   */
6381 7
  public static function str_pad_left(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6382
  {
6383 7
    return self::apply_padding($str, $length - self::strlen($str), 0, $padStr, $encoding);
6384
  }
6385
6386
  /**
6387
   * Returns a new string of a given length such that the end of the string
6388
   * is padded. Alias for pad() with a $padType of 'right'.
6389
   *
6390
   * @param string $str
6391
   * @param int    $length   <p>Desired string length after padding.</p>
6392
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6393
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6394
   *
6395
   * @return string String with right padding.
6396
   */
6397 7
  public static function str_pad_right(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6398
  {
6399 7
    return self::apply_padding($str, 0, $length - self::strlen($str), $padStr, $encoding);
6400
  }
6401
6402
  /**
6403
   * Repeat a string.
6404
   *
6405
   * @param string $str        <p>
6406
   *                           The string to be repeated.
6407
   *                           </p>
6408
   * @param int    $multiplier <p>
6409
   *                           Number of time the input string should be
6410
   *                           repeated.
6411
   *                           </p>
6412
   *                           <p>
6413
   *                           multiplier has to be greater than or equal to 0.
6414
   *                           If the multiplier is set to 0, the function
6415
   *                           will return an empty string.
6416
   *                           </p>
6417
   *
6418
   * @return string The repeated string.
6419
   */
6420 9
  public static function str_repeat(string $str, int $multiplier): string
6421
  {
6422 9
    $str = self::filter($str);
6423
6424 9
    return \str_repeat($str, $multiplier);
6425
  }
6426
6427
  /**
6428
   * INFO: This is only a wrapper for "str_replace()"  -> the original functions is already UTF-8 safe.
6429
   *
6430
   * Replace all occurrences of the search string with the replacement string
6431
   *
6432
   * @link http://php.net/manual/en/function.str-replace.php
6433
   *
6434
   * @param mixed $search  <p>
6435
   *                       The value being searched for, otherwise known as the needle.
6436
   *                       An array may be used to designate multiple needles.
6437
   *                       </p>
6438
   * @param mixed $replace <p>
6439
   *                       The replacement value that replaces found search
6440
   *                       values. An array may be used to designate multiple replacements.
6441
   *                       </p>
6442
   * @param mixed $subject <p>
6443
   *                       The string or array being searched and replaced on,
6444
   *                       otherwise known as the haystack.
6445
   *                       </p>
6446
   *                       <p>
6447
   *                       If subject is an array, then the search and
6448
   *                       replace is performed with every entry of
6449
   *                       subject, and the return value is an array as
6450
   *                       well.
6451
   *                       </p>
6452
   * @param int   $count   [optional] If passed, this will hold the number of matched and replaced needles.
6453
   *
6454
   * @return mixed This function returns a string or an array with the replaced values.
6455
   */
6456 92
  public static function str_replace($search, $replace, $subject, int &$count = null)
6457
  {
6458 92
    return \str_replace($search, $replace, $subject, $count);
6459
  }
6460
6461
  /**
6462
   * Replaces all occurrences of $search from the beginning of string with $replacement.
6463
   *
6464
   * @param string $str         <p>The input string.</p>
6465
   * @param string $search      <p>The string to search for.</p>
6466
   * @param string $replacement <p>The replacement.</p>
6467
   *
6468
   * @return string String after the replacements.
6469
   */
6470 16
  public static function str_replace_beginning(string $str, string $search, string $replacement): string
6471
  {
6472 16
    return self::regex_replace(
6473 16
        $str,
6474 16
        '^' . \preg_quote($search, '/'),
6475 16
        self::str_replace('\\', '\\\\', $replacement)
6476
    );
6477
  }
6478
6479
  /**
6480
   * Replaces all occurrences of $search from the ending of string with $replacement.
6481
   *
6482
   * @param string $str         <p>The input string.</p>
6483
   * @param string $search      <p>The string to search for.</p>
6484
   * @param string $replacement <p>The replacement.</p>
6485
   *
6486
   * @return string String after the replacements.
6487
   */
6488 16
  public static function str_replace_ending(string $str, string $search, string $replacement): string
6489
  {
6490 16
    return self::regex_replace(
6491 16
        $str,
6492 16
        \preg_quote($search, '/') . '$',
6493 16
        self::str_replace('\\', '\\\\', $replacement)
6494
    );
6495
  }
6496
6497
  /**
6498
   * Replace the first "$search"-term with the "$replace"-term.
6499
   *
6500
   * @param string $search
6501
   * @param string $replace
6502
   * @param string $subject
6503
   *
6504
   * @return string
6505
   */
6506 2
  public static function str_replace_first(string $search, string $replace, string $subject): string
6507
  {
6508 2
    $pos = self::strpos($subject, $search);
6509 2
    if ($pos !== false) {
6510 2
      return self::substr_replace($subject, $replace, $pos, self::strlen($search));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($search) can also be of type false; however, parameter $length of voku\helper\UTF8::substr_replace() does only seem to accept integer|integer[]|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6510
      return self::substr_replace($subject, $replace, $pos, /** @scrutinizer ignore-type */ self::strlen($search));
Loading history...
Bug Best Practice introduced by
The expression return self::substr_repl... self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
6511
    }
6512
6513 2
    return $subject;
6514
  }
6515
6516
  /**
6517
   * Replace the last "$search"-term with the "$replace"-term.
6518
   *
6519
   * @param string $search
6520
   * @param string $replace
6521
   * @param string $subject
6522
   *
6523
   * @return string
6524
   */
6525 2
  public static function str_replace_last(string $search, string $replace, string $subject): string
6526
  {
6527 2
    $pos = self::strrpos($subject, $search);
6528 2
    if ($pos !== false) {
6529 2
      return self::substr_replace($subject, $replace, $pos, self::strlen($search));
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::substr_repl... self::strlen($search)) could return the type string[] which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
Bug introduced by
It seems like self::strlen($search) can also be of type false; however, parameter $length of voku\helper\UTF8::substr_replace() does only seem to accept integer|integer[]|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6529
      return self::substr_replace($subject, $replace, $pos, /** @scrutinizer ignore-type */ self::strlen($search));
Loading history...
6530
    }
6531
6532 2
    return $subject;
6533
  }
6534
6535
  /**
6536
   * Shuffles all the characters in the string.
6537
   *
6538
   * PS: uses random algorithm which is weak for cryptography purposes
6539
   *
6540
   * @param string $str <p>The input string</p>
6541
   *
6542
   * @return string The shuffled string.
6543
   */
6544 5
  public static function str_shuffle(string $str): string
6545
  {
6546 5
    $indexes = \range(0, self::strlen($str) - 1);
6547
    /** @noinspection NonSecureShuffleUsageInspection */
6548 5
    \shuffle($indexes);
6549
6550 5
    $shuffledStr = '';
6551 5
    foreach ($indexes as $i) {
6552 5
      $shuffledStr .= self::substr($str, $i, 1);
6553
    }
6554
6555 5
    return $shuffledStr;
6556
  }
6557
6558
  /**
6559
   * Returns the substring beginning at $start, and up to, but not including
6560
   * the index specified by $end. If $end is omitted, the function extracts
6561
   * the remaining string. If $end is negative, it is computed from the end
6562
   * of the string.
6563
   *
6564
   * @param string $str
6565
   * @param int    $start    <p>Initial index from which to begin extraction.</p>
6566
   * @param int    $end      [optional] <p>Index at which to end extraction. Default: null</p>
6567
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6568
   *
6569
   * @return string|false
6570
   *                     <p>The extracted substring.</p><p>If <i>str</i> is shorter than <i>start</i>
6571
   *                     characters long, <b>FALSE</b> will be returned.
6572
   */
6573 18
  public static function str_slice(string $str, int $start, int $end = null, string $encoding = 'UTF-8')
6574
  {
6575 18
    if ($end === null) {
6576 6
      $length = self::strlen($str);
6577 12
    } elseif ($end >= 0 && $end <= $start) {
6578 4
      return '';
6579 8
    } elseif ($end < 0) {
6580 2
      $length = self::strlen($str) + $end - $start;
6581
    } else {
6582 6
      $length = $end - $start;
6583
    }
6584
6585 14
    return self::substr($str, $start, $length, $encoding);
0 ignored issues
show
Bug introduced by
It seems like $length can also be of type false; however, parameter $length of voku\helper\UTF8::substr() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6585
    return self::substr($str, $start, /** @scrutinizer ignore-type */ $length, $encoding);
Loading history...
6586
  }
6587
6588
  /**
6589
   * Convert a string to e.g.: "snake_case"
6590
   *
6591
   * @param string $str
6592
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6593
   *
6594
   * @return string String in snake_case.
6595
   */
6596 20
  public static function str_snakeize(string $str, string $encoding = 'UTF-8'): string
6597
  {
6598 20
    $str = self::normalize_whitespace($str);
6599 20
    $str = \str_replace('-', '_', $str);
6600
6601 20
    $str = (string)\preg_replace_callback(
6602 20
        '/([\d|A-Z])/u',
6603
        function ($matches) use ($encoding) {
6604 8
          $match = $matches[1];
6605 8
          $matchInt = (int)$match;
6606
6607 8
          if ((string)$matchInt == $match) {
6608 4
            return '_' . $match . '_';
6609
          }
6610
6611 4
          return '_' . UTF8::strtolower($match, $encoding);
6612 20
        },
6613 20
        $str
6614
    );
6615
6616 20
    $str = (string)\preg_replace(
6617
        [
6618 20
            '/\s+/',        // convert spaces to "_"
6619
            '/^\s+|\s+$/',  // trim leading & trailing spaces
6620
            '/_+/',         // remove double "_"
6621
        ],
6622
        [
6623 20
            '_',
6624
            '',
6625
            '_',
6626
        ],
6627 20
        $str
6628
    );
6629
6630 20
    $str = self::trim($str, '_'); // trim leading & trailing "_"
6631 20
    $str = self::trim($str); // trim leading & trailing whitespace
6632
6633 20
    return $str;
6634
  }
6635
6636
  /**
6637
   * Sort all characters according to code points.
6638
   *
6639
   * @param string $str    <p>A UTF-8 string.</p>
6640
   * @param bool   $unique <p>Sort unique. If <strong>true</strong>, repeated characters are ignored.</p>
6641
   * @param bool   $desc   <p>If <strong>true</strong>, will sort characters in reverse code point order.</p>
6642
   *
6643
   * @return string String of sorted characters.
6644
   */
6645 2
  public static function str_sort(string $str, bool $unique = false, bool $desc = false): string
6646
  {
6647 2
    $array = self::codepoints($str);
6648
6649 2
    if ($unique) {
6650 2
      $array = \array_flip(\array_flip($array));
6651
    }
6652
6653 2
    if ($desc) {
6654 2
      \arsort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of arsort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6654
      \arsort(/** @scrutinizer ignore-type */ $array);
Loading history...
6655
    } else {
6656 2
      \asort($array);
0 ignored issues
show
Bug introduced by
It seems like $array can also be of type null; however, parameter $array of asort() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

6656
      \asort(/** @scrutinizer ignore-type */ $array);
Loading history...
6657
    }
6658
6659 2
    return self::string($array);
6660
  }
6661
6662
  /**
6663
   * alias for "UTF8::split()"
6664
   *
6665
   * @see UTF8::split()
6666
   *
6667
   * @param string|string[] $str
6668
   * @param int             $len
6669
   *
6670
   * @return string[]
6671
   */
6672 25
  public static function str_split($str, int $len = 1): array
6673
  {
6674 25
    return self::split($str, $len);
6675
  }
6676
6677
  /**
6678
   * Splits the string with the provided regular expression, returning an
6679
   * array of Stringy objects. An optional integer $limit will truncate the
6680
   * results.
6681
   *
6682
   * @param string $str
6683
   * @param string $pattern <p>The regex with which to split the string.</p>
6684
   * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
6685
   *
6686
   * @return string[] An array of strings.
6687
   */
6688 16
  public static function str_split_pattern(string $str, string $pattern, int $limit = -1): array
6689
  {
6690 16
    if ($limit === 0) {
6691 2
      return [];
6692
    }
6693
6694
    // this->split errors when supplied an empty pattern in < PHP 5.4.13
6695
    // and current versions of HHVM (3.8 and below)
6696 14
    if ($pattern === '') {
6697 1
      return [$str];
6698
    }
6699
6700
    // this->split returns the remaining unsplit string in the last index when
6701
    // supplying a limit
6702 13
    if ($limit > 0) {
6703 8
      ++$limit;
6704
    } else {
6705 5
      $limit = -1;
6706
    }
6707
6708 13
    $array = \preg_split('/' . \preg_quote($pattern, '/') . '/u', $str, $limit);
6709
6710 13
    if ($array === false) {
6711
      return [];
6712
    }
6713
6714 13
    if ($limit > 0 && \count($array) === $limit) {
6715 4
      \array_pop($array);
6716
    }
6717
6718 13
    return $array;
6719
  }
6720
6721
  /**
6722
   * Check if the string starts with the given substring.
6723
   *
6724
   * @param string $haystack <p>The string to search in.</p>
6725
   * @param string $needle   <p>The substring to search for.</p>
6726
   *
6727
   * @return bool
6728
   */
6729 41
  public static function str_starts_with(string $haystack, string $needle): bool
6730
  {
6731 41
    if ('' === $haystack || '' === $needle) {
6732 4
      return false;
6733
    }
6734
6735 39
    if (\strpos($haystack, $needle) === 0) {
6736 19
      return true;
6737
    }
6738
6739 24
    return false;
6740
  }
6741
6742
  /**
6743
   * Returns true if the string begins with any of $substrings, false otherwise.
6744
   *
6745
   * - case-sensitive
6746
   *
6747
   * @param string $str        <p>The input string.</p>
6748
   * @param array  $substrings <p>Substrings to look for.</p>
6749
   *
6750
   * @return bool Whether or not $str starts with $substring.
6751
   */
6752 8
  public static function str_starts_with_any(string $str, array $substrings): bool
6753
  {
6754 8
    if ('' === $str) {
6755
      return false;
6756
    }
6757
6758 8
    if (empty($substrings)) {
6759
      return false;
6760
    }
6761
6762 8
    foreach ($substrings as $substring) {
6763 8
      if (self::str_starts_with($str, $substring)) {
6764 8
        return true;
6765
      }
6766
    }
6767
6768 6
    return false;
6769
  }
6770
6771
  /**
6772
   * Gets the substring after the first occurrence of a separator.
6773
   *
6774
   * @param string $str       <p>The input string.</p>
6775
   * @param string $separator <p>The string separator.</p>
6776
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6777
   *
6778
   * @return string
6779
   */
6780 1
  public static function str_substr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6781
  {
6782
    if (
6783 1
        $separator === ''
6784
        ||
6785 1
        $str === ''
6786
    ) {
6787 1
      return '';
6788
    }
6789
6790 1
    $offset = self::str_index_first($str, $separator);
6791 1
    if ($offset === false) {
6792 1
      return '';
6793
    }
6794
6795 1
    return (string)self::substr(
6796 1
        $str,
6797 1
        $offset + self::strlen($separator, $encoding),
6798 1
        null,
6799 1
        $encoding
6800
    );
6801
  }
6802
6803
  /**
6804
   * Gets the substring after the last occurrence of a separator.
6805
   *
6806
   * @param string $str       <p>The input string.</p>
6807
   * @param string $separator <p>The string separator.</p>
6808
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6809
   *
6810
   * @return string
6811
   */
6812 1
  public static function str_substr_after_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6813
  {
6814
    if (
6815 1
        $separator === ''
6816
        ||
6817 1
        $str === ''
6818
    ) {
6819 1
      return '';
6820
    }
6821
6822 1
    $offset = self::str_index_last($str, $separator);
6823 1
    if ($offset === false) {
6824 1
      return '';
6825
    }
6826
6827 1
    return (string)self::substr(
6828 1
        $str,
6829 1
        $offset + self::strlen($separator, $encoding),
6830 1
        null,
6831 1
        $encoding
6832
    );
6833
  }
6834
6835
  /**
6836
   * Gets the substring before the first occurrence of a separator.
6837
   *
6838
   * @param string $str       <p>The input string.</p>
6839
   * @param string $separator <p>The string separator.</p>
6840
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6841
   *
6842
   * @return string
6843
   */
6844 1
  public static function str_substr_before_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6845
  {
6846
    if (
6847 1
        $separator === ''
6848
        ||
6849 1
        $str === ''
6850
    ) {
6851 1
      return '';
6852
    }
6853
6854 1
    $offset = self::str_index_first($str, $separator);
6855 1
    if ($offset === false) {
6856 1
      return '';
6857
    }
6858
6859 1
    return (string)self::substr(
6860 1
        $str,
6861 1
        0,
6862 1
        $offset,
6863 1
        $encoding
6864
    );
6865
  }
6866
6867
  /**
6868
   * Gets the substring before the last occurrence of a separator.
6869
   *
6870
   * @param string $str       <p>The input string.</p>
6871
   * @param string $separator <p>The string separator.</p>
6872
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6873
   *
6874
   * @return string
6875
   */
6876 1
  public static function str_substr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6877
  {
6878
    if (
6879 1
        $separator === ''
6880
        ||
6881 1
        $str === ''
6882
    ) {
6883 1
      return '';
6884
    }
6885
6886 1
    $offset = self::str_index_last($str, $separator);
6887 1
    if ($offset === false) {
6888 1
      return '';
6889
    }
6890
6891 1
    return (string)self::substr(
6892 1
        $str,
6893 1
        0,
6894 1
        $offset,
6895 1
        $encoding
6896
    );
6897
  }
6898
6899
  /**
6900
   * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
6901
   *
6902
   * @param string $str          <p>The input string.</p>
6903
   * @param string $needle       <p>The string to look for.</p>
6904
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
6905
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
6906
   *
6907
   * @return string
6908
   */
6909 2
  public static function str_substr_first(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
6910
  {
6911
    if (
6912 2
        '' === $str
6913
        ||
6914 2
        '' === $needle
6915
    ) {
6916 2
      return '';
6917
    }
6918
6919 2
    $part = self::strstr(
6920 2
        $str,
6921 2
        $needle,
6922 2
        $beforeNeedle,
6923 2
        $encoding
6924
    );
6925 2
    if (false === $part) {
6926 2
      return '';
6927
    }
6928
6929 2
    return $part;
6930
  }
6931
6932
  /**
6933
   * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
6934
   *
6935
   * @param string $str          <p>The input string.</p>
6936
   * @param string $needle       <p>The string to look for.</p>
6937
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
6938
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
6939
   *
6940
   * @return string
6941
   */
6942 2
  public static function str_substr_last(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
6943
  {
6944
    if (
6945 2
        '' === $str
6946
        ||
6947 2
        '' === $needle
6948
    ) {
6949 2
      return '';
6950
    }
6951
6952 2
    $part = self::strrchr($str, $needle, $beforeNeedle, $encoding);
6953 2
    if (false === $part) {
6954 2
      return '';
6955
    }
6956
6957 2
    return $part;
6958
  }
6959
6960
  /**
6961
   * Surrounds $str with the given substring.
6962
   *
6963
   * @param string $str
6964
   * @param string $substring <p>The substring to add to both sides.</P>
6965
   *
6966
   * @return string String with the substring both prepended and appended.
6967
   */
6968 5
  public static function str_surround(string $str, string $substring): string
6969
  {
6970 5
    return \implode('', [$substring, $str, $substring]);
6971
  }
6972
6973
  /**
6974
   * Returns a trimmed string with the first letter of each word capitalized.
6975
   * Also accepts an array, $ignore, allowing you to list words not to be
6976
   * capitalized.
6977
   *
6978
   * @param string              $str
6979
   * @param string[]|array|null $ignore                [optional] <p>An array of words not to capitalize or null.
6980
   *                                                   Default: null</p>
6981
   * @param string              $encoding              [optional] <p>Default: UTF-8</p>
6982
   * @param bool                $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
6983
   * @param string|null         $lang                  [optional] <p>Set the language for special cases: az, el, lt,
6984
   *                                                   tr</p>
6985
   * @param bool                $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ ->
6986
   *                                                   ß</p>
6987
   * @param bool                $useTrimFirst          [optional] <p>true === trim the input string, first</p>
6988
   *
6989
   * @return string The titleized string.
6990
   */
6991 10
  public static function str_titleize(
6992
      string $str,
6993
      array $ignore = null,
6994
      string $encoding = 'UTF-8',
6995
      bool $cleanUtf8 = false,
6996
      string $lang = null,
6997
      bool $tryToKeepStringLength = false,
6998
      bool $useTrimFirst = true
6999
  ): string
7000
  {
7001 10
    if ($useTrimFirst === true) {
7002 5
      $str = self::trim($str);
7003
    }
7004
7005 10
    $str_array = self::str_to_words($str);
7006
7007 10
    foreach ($str_array as &$str_tmp) {
7008
7009 10
      if ($ignore && \in_array($str_tmp, $ignore, true)) {
7010 2
        continue;
7011
      }
7012
7013 10
      $str_tmp = self::str_upper_first(
7014 10
          self::strtolower(
7015 10
              $str_tmp,
7016 10
              $encoding,
7017 10
              $cleanUtf8,
7018 10
              $lang,
7019 10
              $tryToKeepStringLength
7020
          ),
7021 10
          $encoding,
7022 10
          $cleanUtf8,
7023 10
          $lang,
7024 10
          $tryToKeepStringLength
7025
      );
7026
    }
7027
7028 10
    return \implode('', $str_array);
7029
  }
7030
7031
  /**
7032
   * Returns a trimmed string in proper title case.
7033
   *
7034
   * Also accepts an array, $ignore, allowing you to list words not to be
7035
   * capitalized.
7036
   *
7037
   * Adapted from John Gruber's script.
7038
   *
7039
   * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
7040
   *
7041
   * @param string $str
7042
   * @param array  $ignore   <p>An array of words not to capitalize.</p>
7043
   * @param string $encoding [optional] <p>Default: UTF-8</p>
7044
   *
7045
   * @return string The titleized string.
7046
   */
7047 35
  public static function str_titleize_for_humans(string $str, array $ignore = [], string $encoding = 'UTF-8'): string
7048
  {
7049 35
    $smallWords = \array_merge(
7050
        [
7051 35
            '(?<!q&)a',
7052
            'an',
7053
            'and',
7054
            'as',
7055
            'at(?!&t)',
7056
            'but',
7057
            'by',
7058
            'en',
7059
            'for',
7060
            'if',
7061
            'in',
7062
            'of',
7063
            'on',
7064
            'or',
7065
            'the',
7066
            'to',
7067
            'v[.]?',
7068
            'via',
7069
            'vs[.]?',
7070
        ],
7071 35
        $ignore
7072
    );
7073
7074 35
    $smallWordsRx = \implode('|', $smallWords);
7075 35
    $apostropheRx = '(?x: [\'’] [[:lower:]]* )?';
7076
7077 35
    $str = self::trim($str);
7078
7079 35
    if (self::has_lowercase($str) === false) {
7080 2
      $str = self::strtolower($str);
7081
    }
7082
7083
    // The main substitutions
7084 35
    $str = (string)\preg_replace_callback(
7085
        '~\b (_*) (?:                                                              # 1. Leading underscore and
7086
                        ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ |              # 2. file path or 
7087 35
                          [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ ' . $apostropheRx . ' ) #    URL, domain, or email
7088
                        |
7089 35
                        ( (?i: ' . $smallWordsRx . ' ) ' . $apostropheRx . ' )            # 3. or small word (case-insensitive)
7090
                        |
7091 35
                        ( [[:alpha:]] [[:lower:]\'’()\[\]{}]* ' . $apostropheRx . ' )     # 4. or word w/o internal caps
7092
                        |
7093 35
                        ( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* ' . $apostropheRx . ' )     # 5. or some other word
7094
                      ) (_*) \b                                                           # 6. With trailing underscore
7095
                    ~ux',
7096
        function ($matches) use ($encoding) {
7097
          // Preserve leading underscore
7098 35
          $str = $matches[1];
7099 35
          if ($matches[2]) {
7100
            // Preserve URLs, domains, emails and file paths
7101 5
            $str .= $matches[2];
7102 35
          } elseif ($matches[3]) {
7103
            // Lower-case small words
7104 25
            $str .= self::strtolower($matches[3], $encoding);
7105 35
          } elseif ($matches[4]) {
7106
            // Capitalize word w/o internal caps
7107 34
            $str .= static::str_upper_first($matches[4], $encoding);
7108
          } else {
7109
            // Preserve other kinds of word (iPhone)
7110 7
            $str .= $matches[5];
7111
          }
7112
          // Preserve trailing underscore
7113 35
          $str .= $matches[6];
7114
7115 35
          return $str;
7116 35
        },
7117 35
        $str
7118
    );
7119
7120
    // Exceptions for small words: capitalize at start of title...
7121 35
    $str = (string)\preg_replace_callback(
7122
        '~(  \A [[:punct:]]*                # start of title...
7123
                      |  [:.;?!][ ]+               # or of subsentence...
7124
                      |  [ ][\'"“‘(\[][ ]* )       # or of inserted subphrase...
7125 35
                      ( ' . $smallWordsRx . ' ) \b # ...followed by small word
7126
                     ~uxi',
7127
        function ($matches) use ($encoding) {
7128 11
          return $matches[1] . static::str_upper_first($matches[2], $encoding);
7129 35
        },
7130 35
        $str
7131
    );
7132
7133
    // ...and end of title
7134 35
    $str = (string)\preg_replace_callback(
7135 35
        '~\b ( ' . $smallWordsRx . ' ) # small word...
7136
                      (?= [[:punct:]]* \Z     # ...at the end of the title...
7137
                      |   [\'"’”)\]] [ ] )    # ...or of an inserted subphrase?
7138
                     ~uxi',
7139
        function ($matches) use ($encoding) {
7140 3
          return static::str_upper_first($matches[1], $encoding);
7141 35
        },
7142 35
        $str
7143
    );
7144
7145
    // Exceptions for small words in hyphenated compound words
7146
    // e.g. "in-flight" -> In-Flight
7147 35
    $str = (string)\preg_replace_callback(
7148
        '~\b
7149
                        (?<! -)                   # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
7150 35
                        ( ' . $smallWordsRx . ' )
7151
                        (?= -[[:alpha:]]+)        # lookahead for "-someword"
7152
                       ~uxi',
7153
        function ($matches) use ($encoding) {
7154
          return static::str_upper_first($matches[1], $encoding);
7155 35
        },
7156 35
        $str
7157
    );
7158
7159
    // e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
7160 35
    $str = (string)\preg_replace_callback(
7161
        '~\b
7162
                      (?<!…)                    # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
7163
                      ( [[:alpha:]]+- )         # $1 = first word and hyphen, should already be properly capped
7164 35
                      ( ' . $smallWordsRx . ' ) # ...followed by small word
7165
                      (?!	- )                   # Negative lookahead for another -
7166
                     ~uxi',
7167
        function ($matches) use ($encoding) {
7168
          return $matches[1] . static::str_upper_first($matches[2], $encoding);
7169 35
        },
7170 35
        $str
7171
    );
7172
7173 35
    return $str;
7174
  }
7175
7176
  /**
7177
   * Get a binary representation of a specific string.
7178
   *
7179
   * @param string $str <p>The input string.</p>
7180
   *
7181
   * @return string
7182
   */
7183 2
  public static function str_to_binary(string $str): string
7184
  {
7185 2
    $value = \unpack('H*', $str);
7186
7187 2
    return \base_convert($value[1], 16, 2);
7188
  }
7189
7190
  /**
7191
   * @param string   $str
7192
   * @param bool     $removeEmptyValues <p>Remove empty values.</p>
7193
   * @param null|int $removeShortValues <p>The min. string length or null to disable</p>
7194
   *
7195
   * @return string[]
7196
   */
7197 17
  public static function str_to_lines(string $str, bool $removeEmptyValues = false, int $removeShortValues = null): array
7198
  {
7199 17
    if ('' === $str) {
7200 1
      return ($removeEmptyValues === true ? [] : ['']);
7201
    }
7202
7203 16
    $return = \preg_split("/[\r\n]{1,2}/u", $str);
7204
7205 16
    if ($return === false) {
7206
      return ($removeEmptyValues === true ? [] : ['']);
7207
    }
7208
7209
    if (
7210 16
        $removeShortValues === null
7211
        &&
7212 16
        $removeEmptyValues === false
7213
    ) {
7214 16
      return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
7215
    }
7216
7217
    $tmpReturn = self::reduce_string_array(
7218
        $return,
7219
        $removeEmptyValues,
7220
        $removeShortValues
7221
    );
7222
7223
    return $tmpReturn;
7224
  }
7225
7226
  /**
7227
   * Convert a string into an array of words.
7228
   *
7229
   * @param string   $str
7230
   * @param string   $charList          <p>Additional chars for the definition of "words".</p>
7231
   * @param bool     $removeEmptyValues <p>Remove empty values.</p>
7232
   * @param null|int $removeShortValues <p>The min. string length or null to disable</p>
7233
   *
7234
   * @return string[]
7235
   */
7236 24
  public static function str_to_words(string $str, string $charList = '', bool $removeEmptyValues = false, int $removeShortValues = null): array
7237
  {
7238 24
    if ('' === $str) {
7239 4
      return ($removeEmptyValues === true ? [] : ['']);
7240
    }
7241
7242 24
    $charList = self::rxClass($charList, '\pL');
7243
7244 24
    $return = \preg_split("/({$charList}+(?:[\p{Pd}’']{$charList}+)*)/u", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
7245
7246 24
    if ($return === false) {
7247
      return ($removeEmptyValues === true ? [] : ['']);
7248
    }
7249
7250
    if (
7251 24
        $removeShortValues === null
7252
        &&
7253 24
        $removeEmptyValues === false
7254
    ) {
7255 24
      return $return;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $return returns an array which contains values of type array which are incompatible with the documented value type string.
Loading history...
7256
    }
7257
7258 2
    $tmpReturn = self::reduce_string_array(
7259 2
        $return,
7260 2
        $removeEmptyValues,
7261 2
        $removeShortValues
7262
    );
7263
7264 2
    foreach ($tmpReturn as &$item) {
7265 2
      $item = (string)$item;
7266
    }
7267
7268 2
    return $tmpReturn;
7269
  }
7270
7271
  /**
7272
   * alias for "UTF8::to_ascii()"
7273
   *
7274
   * @see UTF8::to_ascii()
7275
   *
7276
   * @param string $str
7277
   * @param string $unknown
7278
   * @param bool   $strict
7279
   *
7280
   * @return string
7281
   */
7282 8
  public static function str_transliterate(string $str, string $unknown = '?', bool $strict = false): string
7283
  {
7284 8
    return self::to_ascii($str, $unknown, $strict);
7285
  }
7286
7287
  /**
7288
   * Truncates the string to a given length. If $substring is provided, and
7289
   * truncating occurs, the string is further truncated so that the substring
7290
   * may be appended without exceeding the desired length.
7291
   *
7292
   * @param string $str
7293
   * @param int    $length    <p>Desired length of the truncated string.</p>
7294
   * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
7295
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
7296
   *
7297
   * @return string String after truncating.
7298
   */
7299 22
  public static function str_truncate($str, int $length, string $substring = '', string $encoding = 'UTF-8'): string
7300
  {
7301
    // init
7302 22
    $str = (string)$str;
7303
7304 22
    if ('' === $str) {
7305
      return '';
7306
    }
7307
7308 22
    if ($length >= self::strlen($str, $encoding)) {
7309 4
      return $str;
7310
    }
7311
7312
    // Need to further trim the string so we can append the substring
7313 18
    $substringLength = self::strlen($substring, $encoding);
7314 18
    $length -= $substringLength;
7315
7316 18
    $truncated = self::substr($str, 0, $length, $encoding);
7317
7318 18
    return $truncated . $substring;
0 ignored issues
show
Bug introduced by
Are you sure $truncated of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7318
    return /** @scrutinizer ignore-type */ $truncated . $substring;
Loading history...
7319
  }
7320
7321
  /**
7322
   * Truncates the string to a given length, while ensuring that it does not
7323
   * split words. If $substring is provided, and truncating occurs, the
7324
   * string is further truncated so that the substring may be appended without
7325
   * exceeding the desired length.
7326
   *
7327
   * @param string $str
7328
   * @param int    $length    <p>Desired length of the truncated string.</p>
7329
   * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
7330
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
7331
   *
7332
   * @return string String after truncating.
7333
   */
7334 23
  public static function str_truncate_safe(string $str, int $length, string $substring = '', string $encoding = 'UTF-8'): string
7335
  {
7336 23
    if ($length >= self::strlen($str, $encoding)) {
7337 4
      return $str;
7338
    }
7339
7340
    // need to further trim the string so we can append the substring
7341 19
    $substringLength = self::strlen($substring, $encoding);
7342 19
    $length -= $substringLength;
7343
7344 19
    $truncated = self::substr($str, 0, $length, $encoding);
7345 19
    if ($truncated === false) {
7346
      return '';
7347
    }
7348
7349
    // if the last word was truncated
7350 19
    $strPosSpace = self::strpos($str, ' ', $length - 1, $encoding);
7351 19
    if ($strPosSpace != $length) {
7352
      // find pos of the last occurrence of a space, get up to that
7353 12
      $lastPos = self::strrpos($truncated, ' ', 0, $encoding);
7354
7355 12
      if ($lastPos !== false || $strPosSpace !== false) {
7356 11
        $truncated = self::substr($truncated, 0, (int)$lastPos, $encoding);
7357
      }
7358
    }
7359
7360 19
    $str = $truncated . $substring;
0 ignored issues
show
Bug introduced by
Are you sure $truncated of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7360
    $str = /** @scrutinizer ignore-type */ $truncated . $substring;
Loading history...
7361
7362 19
    return $str;
7363
  }
7364
7365
  /**
7366
   * Returns a lowercase and trimmed string separated by underscores.
7367
   * Underscores are inserted before uppercase characters (with the exception
7368
   * of the first character of the string), and in place of spaces as well as
7369
   * dashes.
7370
   *
7371
   * @param string $str
7372
   *
7373
   * @return string The underscored string.
7374
   */
7375 16
  public static function str_underscored(string $str): string
7376
  {
7377 16
    return self::str_delimit($str, '_');
7378
  }
7379
7380
  /**
7381
   * Returns an UpperCamelCase version of the supplied string. It trims
7382
   * surrounding spaces, capitalizes letters following digits, spaces, dashes
7383
   * and underscores, and removes spaces, dashes, underscores.
7384
   *
7385
   * @param string      $str                   <p>The input string.</p>
7386
   * @param string      $encoding              [optional] <p>Default: UTF-8</p>
7387
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
7388
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
7389
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
7390
   *
7391
   * @return string String in UpperCamelCase.
7392
   */
7393 13
  public static function str_upper_camelize(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
7394
  {
7395 13
    return self::str_upper_first(self::str_camelize($str, $encoding), $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
7396
  }
7397
7398
  /**
7399
   * alias for "UTF8::ucfirst()"
7400
   *
7401
   * @see UTF8::ucfirst()
7402
   *
7403
   * @param string      $str
7404
   * @param string      $encoding
7405
   * @param bool        $cleanUtf8
7406
   * @param string|null $lang
7407
   * @param bool        $tryToKeepStringLength
7408
   *
7409
   *
7410
   * @return string
7411
   */
7412 63
  public static function str_upper_first(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
7413
  {
7414 63
    return self::ucfirst($str, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength);
7415
  }
7416
7417
  /**
7418
   * Counts number of words in the UTF-8 string.
7419
   *
7420
   * @param string $str      <p>The input string.</p>
7421
   * @param int    $format   [optional] <p>
7422
   *                         <strong>0</strong> => return a number of words (default)<br>
7423
   *                         <strong>1</strong> => return an array of words<br>
7424
   *                         <strong>2</strong> => return an array of words with word-offset as key
7425
   *                         </p>
7426
   * @param string $charlist [optional] <p>Additional chars that contains to words and do not start a new word.</p>
7427
   *
7428
   * @return string[]|int The number of words in the string
7429
   */
7430 2
  public static function str_word_count(string $str, int $format = 0, string $charlist = '')
7431
  {
7432 2
    $strParts = self::str_to_words($str, $charlist);
7433
7434 2
    $len = \count($strParts);
7435
7436 2
    if ($format === 1) {
7437
7438 2
      $numberOfWords = [];
7439 2
      for ($i = 1; $i < $len; $i += 2) {
7440 2
        $numberOfWords[] = $strParts[$i];
7441
      }
7442
7443 2
    } elseif ($format === 2) {
7444
7445 2
      $numberOfWords = [];
7446 2
      $offset = self::strlen($strParts[0]);
7447 2
      for ($i = 1; $i < $len; $i += 2) {
7448 2
        $numberOfWords[$offset] = $strParts[$i];
7449 2
        $offset += self::strlen($strParts[$i]) + self::strlen($strParts[$i + 1]);
7450
      }
7451
7452
    } else {
7453
7454 2
      $numberOfWords = (int)(($len - 1) / 2);
7455
7456
    }
7457
7458 2
    return $numberOfWords;
7459
  }
7460
7461
  /**
7462
   * Case-insensitive string comparison.
7463
   *
7464
   * INFO: Case-insensitive version of UTF8::strcmp()
7465
   *
7466
   * @param string $str1     <p>The first string.</p>
7467
   * @param string $str2     <p>The second string.</p>
7468
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7469
   *
7470
   * @return int
7471
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
7472
   *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
7473
   *             <strong>0</strong> if they are equal.
7474
   */
7475 23
  public static function strcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
7476
  {
7477 23
    return self::strcmp(
7478 23
        self::strtocasefold($str1, true, false, $encoding, null, false),
7479 23
        self::strtocasefold($str2, true, false, $encoding, null, false)
7480
    );
7481
  }
7482
7483
  /**
7484
   * alias for "UTF8::strstr()"
7485
   *
7486
   * @see UTF8::strstr()
7487
   *
7488
   * @param string $haystack
7489
   * @param string $needle
7490
   * @param bool   $before_needle
7491
   * @param string $encoding
7492
   * @param bool   $cleanUtf8
7493
   *
7494
   * @return string|false
7495
   */
7496 2
  public static function strchr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7497
  {
7498 2
    return self::strstr($haystack, $needle, $before_needle, $encoding, $cleanUtf8);
7499
  }
7500
7501
  /**
7502
   * Case-sensitive string comparison.
7503
   *
7504
   * @param string $str1 <p>The first string.</p>
7505
   * @param string $str2 <p>The second string.</p>
7506
   *
7507
   * @return int
7508
   *              <strong>&lt; 0</strong> if str1 is less than str2<br>
7509
   *              <strong>&gt; 0</strong> if str1 is greater than str2<br>
7510
   *              <strong>0</strong> if they are equal.
7511
   */
7512 29
  public static function strcmp(string $str1, string $str2): int
7513
  {
7514
    /** @noinspection PhpUndefinedClassInspection */
7515 29
    return $str1 . '' === $str2 . '' ? 0 : \strcmp(
7516 24
        \Normalizer::normalize($str1, \Normalizer::NFD),
7517 29
        \Normalizer::normalize($str2, \Normalizer::NFD)
7518
    );
7519
  }
7520
7521
  /**
7522
   * Find length of initial segment not matching mask.
7523
   *
7524
   * @param string $str
7525
   * @param string $charList
7526
   * @param int    $offset
7527
   * @param int    $length
7528
   *
7529
   * @return int|null
7530
   */
7531 15
  public static function strcspn(string $str, string $charList, int $offset = 0, int $length = null)
7532
  {
7533 15
    if ('' === $charList) {
7534 1
      return null;
7535
    }
7536
7537 14
    if ($offset || $length !== null) {
7538 2
      $strTmp = self::substr($str, $offset, $length);
7539 2
      if ($strTmp === false) {
7540
        return null;
7541
      }
7542 2
      $str = $strTmp;
7543
    }
7544
7545 14
    if ('' === $str) {
7546 1
      return null;
7547
    }
7548
7549 13
    if (\preg_match('/^(.*?)' . self::rxClass($charList) . '/us', $str, $length)) {
0 ignored issues
show
Bug introduced by
It seems like $length can also be of type integer; however, parameter $matches of preg_match() does only seem to accept array|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7549
    if (\preg_match('/^(.*?)' . self::rxClass($charList) . '/us', $str, /** @scrutinizer ignore-type */ $length)) {
Loading history...
7550 13
      return self::strlen($length[1]);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::strlen($length[1]) could also return false which is incompatible with the documented return type integer|null. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
7551
    }
7552
7553 1
    return self::strlen($str);
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::strlen($str) could also return false which is incompatible with the documented return type integer|null. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
7554
  }
7555
7556
  /**
7557
   * alias for "UTF8::stristr()"
7558
   *
7559
   * @see UTF8::stristr()
7560
   *
7561
   * @param string $haystack
7562
   * @param string $needle
7563
   * @param bool   $before_needle
7564
   * @param string $encoding
7565
   * @param bool   $cleanUtf8
7566
   *
7567
   * @return string|false
7568
   */
7569 1
  public static function strichr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7570
  {
7571 1
    return self::stristr($haystack, $needle, $before_needle, $encoding, $cleanUtf8);
7572
  }
7573
7574
  /**
7575
   * Create a UTF-8 string from code points.
7576
   *
7577
   * INFO: opposite to UTF8::codepoints()
7578
   *
7579
   * @param array $array <p>Integer or Hexadecimal codepoints.</p>
7580
   *
7581
   * @return string UTF-8 encoded string.
7582
   */
7583 4
  public static function string(array $array): string
7584
  {
7585 4
    return \implode(
7586 4
        '',
7587 4
        \array_map(
7588
            [
7589 4
                self::class,
7590
                'chr',
7591
            ],
7592 4
            $array
7593
        )
7594
    );
7595
  }
7596
7597
  /**
7598
   * Checks if string starts with "BOM" (Byte Order Mark Character) character.
7599
   *
7600
   * @param string $str <p>The input string.</p>
7601
   *
7602
   * @return bool
7603
   *              <strong>true</strong> if the string has BOM at the start,<br>
7604
   *              <strong>false</strong> otherwise.
7605
   */
7606 6
  public static function string_has_bom(string $str): bool
7607
  {
7608 6
    foreach (self::$BOM as $bomString => $bomByteLength) {
7609 6
      if (0 === \strpos($str, $bomString)) {
7610 6
        return true;
7611
      }
7612
    }
7613
7614 6
    return false;
7615
  }
7616
7617
  /**
7618
   * Strip HTML and PHP tags from a string + clean invalid UTF-8.
7619
   *
7620
   * @link http://php.net/manual/en/function.strip-tags.php
7621
   *
7622
   * @param string $str             <p>
7623
   *                                The input string.
7624
   *                                </p>
7625
   * @param string $allowable_tags  [optional] <p>
7626
   *                                You can use the optional second parameter to specify tags which should
7627
   *                                not be stripped.
7628
   *                                </p>
7629
   *                                <p>
7630
   *                                HTML comments and PHP tags are also stripped. This is hardcoded and
7631
   *                                can not be changed with allowable_tags.
7632
   *                                </p>
7633
   * @param bool   $cleanUtf8       [optional] <p>Remove non UTF-8 chars from the string.</p>
7634
   *
7635
   * @return string The stripped string.
7636
   */
7637 4
  public static function strip_tags(string $str, string $allowable_tags = null, bool $cleanUtf8 = false): string
7638
  {
7639 4
    if ('' === $str) {
7640 1
      return '';
7641
    }
7642
7643 4
    if ($cleanUtf8 === true) {
7644 2
      $str = self::clean($str);
7645
    }
7646
7647 4
    return \strip_tags($str, $allowable_tags);
7648
  }
7649
7650
  /**
7651
   * Strip all whitespace characters. This includes tabs and newline
7652
   * characters, as well as multibyte whitespace such as the thin space
7653
   * and ideographic space.
7654
   *
7655
   * @param string $str
7656
   *
7657
   * @return string
7658
   */
7659 36
  public static function strip_whitespace(string $str): string
7660
  {
7661 36
    if ('' === $str) {
7662 3
      return '';
7663
    }
7664
7665 33
    return (string)\preg_replace('/[[:space:]]+/u', '', $str);
7666
  }
7667
7668
  /**
7669
   * Finds position of first occurrence of a string within another, case insensitive.
7670
   *
7671
   * @link http://php.net/manual/en/function.mb-stripos.php
7672
   *
7673
   * @param string $haystack  <p>The string from which to get the position of the first occurrence of needle.</p>
7674
   * @param string $needle    <p>The string to find in haystack.</p>
7675
   * @param int    $offset    [optional] <p>The position in haystack to start searching.</p>
7676
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
7677
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
7678
   *
7679
   * @return int|false
7680
   *                   Return the <strong>(int)</strong> numeric position of the first occurrence of needle in the
7681
   *                   haystack string,<br> or <strong>false</strong> if needle is not found.
7682
   */
7683 75
  public static function stripos(string $haystack, string $needle, int $offset = 0, $encoding = 'UTF-8', bool $cleanUtf8 = false)
7684
  {
7685 75
    if ('' === $haystack || '' === $needle) {
7686 5
      return false;
7687
    }
7688
7689 74
    if ($cleanUtf8 === true) {
7690
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
7691
      // if invalid characters are found in $haystack before $needle
7692 1
      $haystack = self::clean($haystack);
7693 1
      $needle = self::clean($needle);
7694
    }
7695
7696 74
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7697 23
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7698
    }
7699
7700 74
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7701
      self::checkForSupport();
7702
    }
7703
7704 74
    if (self::$SUPPORT['mbstring'] === true) {
7705 74
      $returnTmp = \mb_stripos($haystack, $needle, $offset, $encoding);
7706 74
      if ($returnTmp !== false) {
7707 54
        return $returnTmp;
7708
      }
7709
    }
7710
7711
    if (
7712 31
        $encoding === 'UTF-8' // INFO: "grapheme_stripos()" can't handle other encodings
7713
        &&
7714 31
        $offset >= 0 // grapheme_stripos() can't handle negative offset
7715
        &&
7716 31
        self::$SUPPORT['intl'] === true
7717
    ) {
7718 31
      $returnTmp = \grapheme_stripos($haystack, $needle, $offset);
7719 31
      if ($returnTmp !== false) {
7720
        return $returnTmp;
7721
      }
7722
    }
7723
7724
    //
7725
    // fallback for ascii only
7726
    //
7727
7728 31
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
7729 15
      return \stripos($haystack, $needle, $offset);
7730
    }
7731
7732
    //
7733
    // fallback via vanilla php
7734
    //
7735
7736 20
    $haystack = self::strtocasefold($haystack, true, false, $encoding, null, false);
7737 20
    $needle = self::strtocasefold($needle, true, false, $encoding, null, false);
7738
7739 20
    return self::strpos($haystack, $needle, $offset, $encoding);
7740
  }
7741
7742
  /**
7743
   * Returns all of haystack starting from and including the first occurrence of needle to the end.
7744
   *
7745
   * @param string $haystack       <p>The input string. Must be valid UTF-8.</p>
7746
   * @param string $needle         <p>The string to look for. Must be valid UTF-8.</p>
7747
   * @param bool   $before_needle  [optional] <p>
7748
   *                               If <b>TRUE</b>, it returns the part of the
7749
   *                               haystack before the first occurrence of the needle (excluding the needle).
7750
   *                               </p>
7751
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
7752
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
7753
   *
7754
   * @return false|string A sub-string,<br>or <strong>false</strong> if needle is not found.
7755
   */
7756 19
  public static function stristr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7757
  {
7758 19
    if ('' === $haystack || '' === $needle) {
7759 6
      return false;
7760
    }
7761
7762 13
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7763 1
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7764
    }
7765
7766 13
    if ($cleanUtf8 === true) {
7767
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
7768
      // if invalid characters are found in $haystack before $needle
7769 1
      $needle = self::clean($needle);
7770 1
      $haystack = self::clean($haystack);
7771
    }
7772
7773 13
    if (!$needle) {
7774
      return $haystack;
7775
    }
7776
7777 13
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7778
      self::checkForSupport();
7779
    }
7780
7781
    if (
7782 13
        $encoding !== 'UTF-8'
7783
        &&
7784 13
        self::$SUPPORT['mbstring'] === false
7785
    ) {
7786
      \trigger_error('UTF8::stristr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
7787
    }
7788
7789 13
    if (self::$SUPPORT['mbstring'] === true) {
7790 13
      return \mb_stristr($haystack, $needle, $before_needle, $encoding);
7791
    }
7792
7793
    if (
7794
        $encoding === 'UTF-8' // INFO: "grapheme_stristr()" can't handle other encodings
7795
        &&
7796
        self::$SUPPORT['intl'] === true
7797
    ) {
7798
      $returnTmp = \grapheme_stristr($haystack, $needle, $before_needle);
7799
      if ($returnTmp !== false) {
7800
        return $returnTmp;
7801
      }
7802
    }
7803
7804
    if (self::is_ascii($needle) && self::is_ascii($haystack)) {
7805
      return \stristr($haystack, $needle, $before_needle);
7806
    }
7807
7808
    \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/usi', $haystack, $match);
7809
7810
    if (!isset($match[1])) {
7811
      return false;
7812
    }
7813
7814
    if ($before_needle) {
7815
      return $match[1];
7816
    }
7817
7818
    return self::substr($haystack, self::strlen($match[1]));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($match[1]) can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

7818
    return self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($match[1]));
Loading history...
7819
  }
7820
7821
  /**
7822
   * Get the string length, not the byte-length!
7823
   *
7824
   * @link     http://php.net/manual/en/function.mb-strlen.php
7825
   *
7826
   * @param string $str       <p>The string being checked for length.</p>
7827
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
7828
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
7829
   *
7830
   * @return int|false
7831
   *             The number <strong>(int)</strong> of characters in the string $str having character encoding $encoding.
7832
   *             (One multi-byte character counted as +1).
7833
   *             <br>
7834
   *             Can return <strong>false</strong>, if e.g. mbstring is not installed and we process invalid chars.
7835
   */
7836 263
  public static function strlen(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7837
  {
7838 263
    if ('' === $str) {
7839 37
      return 0;
7840
    }
7841
7842 261
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7843 83
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7844
    }
7845
7846
    //
7847
    // fallback for binary || ascii only
7848
    //
7849
7850
    if (
7851 261
        $encoding === 'CP850'
7852
        ||
7853 261
        $encoding === 'ASCII'
7854
    ) {
7855 2
      return self::strlen_in_byte($str);
7856
    }
7857
7858 261
    if ($cleanUtf8 === true) {
7859
      // "mb_strlen" and "\iconv_strlen" returns wrong length,
7860
      // if invalid characters are found in $str
7861 4
      $str = self::clean($str);
7862
    }
7863
7864 261
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7865
      self::checkForSupport();
7866
    }
7867
7868
    if (
7869 261
        $encoding !== 'UTF-8'
7870
        &&
7871 261
        self::$SUPPORT['mbstring'] === false
7872
        &&
7873 261
        self::$SUPPORT['iconv'] === false
7874
    ) {
7875 2
      \trigger_error('UTF8::strlen() without mbstring / iconv cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
7876
    }
7877
7878
    //
7879
    // fallback via mbstring
7880
    //
7881
7882 261
    if (self::$SUPPORT['mbstring'] === true) {
7883 255
      $returnTmp = \mb_strlen($str, $encoding);
7884 255
      if ($returnTmp !== false) {
7885 255
        return $returnTmp;
7886
      }
7887
    }
7888
7889
    //
7890
    // fallback via iconv
7891
    //
7892
7893 8
    if (self::$SUPPORT['iconv'] === true) {
7894
      $returnTmp = \iconv_strlen($str, $encoding);
7895
      if ($returnTmp !== false) {
7896
        return $returnTmp;
7897
      }
7898
    }
7899
7900
    //
7901
    // fallback via intl
7902
    //
7903
7904
    if (
7905 8
        $encoding === 'UTF-8' // INFO: "grapheme_strlen()" can't handle other encodings
7906
        &&
7907 8
        self::$SUPPORT['intl'] === true
7908
    ) {
7909
      $returnTmp = \grapheme_strlen($str);
7910
      if ($returnTmp !== null) {
7911
        return $returnTmp;
7912
      }
7913
    }
7914
7915
    //
7916
    // fallback for ascii only
7917
    //
7918
7919 8
    if (self::is_ascii($str)) {
7920 4
      return \strlen($str);
7921
    }
7922
7923
    //
7924
    // fallback via vanilla php
7925
    //
7926
7927 8
    \preg_match_all('/./us', $str, $parts);
7928
7929 8
    $returnTmp = \count($parts[0]);
7930 8
    if ($returnTmp === 0 && isset($str[0])) {
7931
      return false;
7932
    }
7933
7934 8
    return $returnTmp;
7935
  }
7936
7937
  /**
7938
   * Get string length in byte.
7939
   *
7940
   * @param string $str
7941
   *
7942
   * @return int
7943
   */
7944 193
  public static function strlen_in_byte(string $str): int
7945
  {
7946 193
    if ($str === '') {
7947
      return 0;
7948
    }
7949
7950 193
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7951
      self::checkForSupport();
7952
    }
7953
7954 193
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
7955
      // "mb_" is available if overload is used, so use it ...
7956
      return \mb_strlen($str, 'CP850'); // 8-BIT
7957
    }
7958
7959 193
    return \strlen($str);
7960
  }
7961
7962
  /**
7963
   * Case insensitive string comparisons using a "natural order" algorithm.
7964
   *
7965
   * INFO: natural order version of UTF8::strcasecmp()
7966
   *
7967
   * @param string $str1     <p>The first string.</p>
7968
   * @param string $str2     <p>The second string.</p>
7969
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7970
   *
7971
   * @return int
7972
   *             <strong>&lt; 0</strong> if str1 is less than str2<br>
7973
   *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
7974
   *             <strong>0</strong> if they are equal
7975
   */
7976 2
  public static function strnatcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
7977
  {
7978 2
    return self::strnatcmp(
7979 2
        self::strtocasefold($str1, true, false, $encoding, null, false),
7980 2
        self::strtocasefold($str2, true, false, $encoding, null, false)
7981
    );
7982
  }
7983
7984
  /**
7985
   * String comparisons using a "natural order" algorithm
7986
   *
7987
   * INFO: natural order version of UTF8::strcmp()
7988
   *
7989
   * @link  http://php.net/manual/en/function.strnatcmp.php
7990
   *
7991
   * @param string $str1 <p>The first string.</p>
7992
   * @param string $str2 <p>The second string.</p>
7993
   *
7994
   * @return int
7995
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
7996
   *             <strong>&gt; 0</strong> if str1 is greater than str2;<br>
7997
   *             <strong>0</strong> if they are equal
7998
   */
7999 4
  public static function strnatcmp(string $str1, string $str2): int
8000
  {
8001 4
    return $str1 . '' === $str2 . '' ? 0 : \strnatcmp(self::strtonatfold($str1), self::strtonatfold($str2));
8002
  }
8003
8004
  /**
8005
   * Case-insensitive string comparison of the first n characters.
8006
   *
8007
   * @link  http://php.net/manual/en/function.strncasecmp.php
8008
   *
8009
   * @param string $str1     <p>The first string.</p>
8010
   * @param string $str2     <p>The second string.</p>
8011
   * @param int    $len      <p>The length of strings to be used in the comparison.</p>
8012
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
8013
   *
8014
   * @return int
8015
   *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
8016
   *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
8017
   *             <strong>0</strong> if they are equal
8018
   */
8019 2
  public static function strncasecmp(string $str1, string $str2, int $len, string $encoding = 'UTF-8'): int
8020
  {
8021 2
    return self::strncmp(
8022 2
        self::strtocasefold($str1, true, false, $encoding, null, false),
8023 2
        self::strtocasefold($str2, true, false, $encoding, null, false),
8024 2
        $len
8025
    );
8026
  }
8027
8028
  /**
8029
   * String comparison of the first n characters.
8030
   *
8031
   * @link  http://php.net/manual/en/function.strncmp.php
8032
   *
8033
   * @param string $str1 <p>The first string.</p>
8034
   * @param string $str2 <p>The second string.</p>
8035
   * @param int    $len  <p>Number of characters to use in the comparison.</p>
8036
   *
8037
   * @return int
8038
   *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
8039
   *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
8040
   *             <strong>0</strong> if they are equal
8041
   */
8042 4
  public static function strncmp(string $str1, string $str2, int $len): int
8043
  {
8044 4
    $str1 = (string)self::substr($str1, 0, $len);
8045 4
    $str2 = (string)self::substr($str2, 0, $len);
8046
8047 4
    return self::strcmp($str1, $str2);
8048
  }
8049
8050
  /**
8051
   * Search a string for any of a set of characters.
8052
   *
8053
   * @link  http://php.net/manual/en/function.strpbrk.php
8054
   *
8055
   * @param string $haystack  <p>The string where char_list is looked for.</p>
8056
   * @param string $char_list <p>This parameter is case sensitive.</p>
8057
   *
8058
   * @return string|false String starting from the character found, or false if it is not found.
8059
   */
8060 2
  public static function strpbrk(string $haystack, string $char_list)
8061
  {
8062 2
    if ('' === $haystack || '' === $char_list) {
8063 2
      return false;
8064
    }
8065
8066 2
    if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) {
8067 2
      return \substr($haystack, (int)\strpos($haystack, $m[0]));
8068
    }
8069
8070 2
    return false;
8071
  }
8072
8073
  /**
8074
   * Find position of first occurrence of string in a string.
8075
   *
8076
   * @link http://php.net/manual/en/function.mb-strpos.php
8077
   *
8078
   * @param string     $haystack  <p>The string from which to get the position of the first occurrence of needle.</p>
8079
   * @param string|int $needle    <p>The string to find in haystack.<br>Or a code point as int.</p>
8080
   * @param int        $offset    [optional] <p>The search offset. If it is not specified, 0 is used.</p>
8081
   * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
8082
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8083
   *
8084
   * @return int|false
8085
   *                   The <strong>(int)</strong> numeric position of the first occurrence of needle in the haystack
8086
   *                   string.<br> If needle is not found it returns false.
8087
   */
8088 142
  public static function strpos(string $haystack, $needle, int $offset = 0, $encoding = 'UTF-8', bool $cleanUtf8 = false)
8089
  {
8090 142
    if ('' === $haystack) {
8091 4
      return false;
8092
    }
8093
8094
    // iconv and mbstring do not support integer $needle
8095 141
    if ((int)$needle === $needle && $needle >= 0) {
8096
      $needle = (string)self::chr($needle);
8097
    }
8098 141
    $needle = (string)$needle;
8099
8100 141
    if ('' === $needle) {
8101 2
      return false;
8102
    }
8103
8104 141
    if ($cleanUtf8 === true) {
8105
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8106
      // if invalid characters are found in $haystack before $needle
8107 3
      $needle = self::clean($needle);
8108 3
      $haystack = self::clean($haystack);
8109
    }
8110
8111 141
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8112 55
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8113
    }
8114
8115 141
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8116
      self::checkForSupport();
8117
    }
8118
8119
    //
8120
    // fallback for binary || ascii only
8121
    //
8122
8123
    if (
8124 141
        $encoding === 'CP850'
8125
        ||
8126 141
        $encoding === 'ASCII'
8127
    ) {
8128 2
      return self::strpos_in_byte($haystack, $needle, $offset);
8129
    }
8130
8131
    if (
8132 141
        $encoding !== 'UTF-8'
8133
        &&
8134 141
        self::$SUPPORT['iconv'] === false
8135
        &&
8136 141
        self::$SUPPORT['mbstring'] === false
8137
    ) {
8138 2
      \trigger_error('UTF8::strpos() without mbstring / iconv cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8139
    }
8140
8141
    //
8142
    // fallback via mbstring
8143
    //
8144
8145 141
    if (self::$SUPPORT['mbstring'] === true) {
8146 141
      $returnTmp = \mb_strpos($haystack, $needle, $offset, $encoding);
8147 141
      if ($returnTmp !== false) {
8148 86
        return $returnTmp;
8149
      }
8150
    }
8151
8152
    //
8153
    // fallback via intl
8154
    //
8155
8156
    if (
8157 69
        $encoding === 'UTF-8' // INFO: "grapheme_strpos()" can't handle other encodings
8158
        &&
8159 69
        $offset >= 0 // grapheme_strpos() can't handle negative offset
8160
        &&
8161 69
        self::$SUPPORT['intl'] === true
8162
    ) {
8163 69
      $returnTmp = \grapheme_strpos($haystack, $needle, $offset);
8164 69
      if ($returnTmp !== false) {
8165
        return $returnTmp;
8166
      }
8167
    }
8168
8169
    //
8170
    // fallback via iconv
8171
    //
8172
8173
    if (
8174 69
        $offset >= 0 // iconv_strpos() can't handle negative offset
8175
        &&
8176 69
        self::$SUPPORT['iconv'] === true
8177
    ) {
8178
      // ignore invalid negative offset to keep compatibility
8179
      // with php < 5.5.35, < 5.6.21, < 7.0.6
8180 69
      $returnTmp = \iconv_strpos($haystack, $needle, $offset > 0 ? $offset : 0, $encoding);
8181 69
      if ($returnTmp !== false) {
8182
        return $returnTmp;
8183
      }
8184
    }
8185
8186
    //
8187
    // fallback for ascii only
8188
    //
8189
8190 69
    if (($haystackIsAscii = self::is_ascii($haystack)) && self::is_ascii($needle)) {
8191 35
      return \strpos($haystack, $needle, $offset);
8192
    }
8193
8194
    //
8195
    // fallback via vanilla php
8196
    //
8197
8198 39
    if ($haystackIsAscii) {
8199
      $haystackTmp = \substr($haystack, $offset);
8200
    } else {
8201 39
      $haystackTmp = self::substr($haystack, $offset, null, $encoding);
8202
    }
8203 39
    if ($haystackTmp === false) {
8204
      $haystackTmp = '';
8205
    }
8206 39
    $haystack = (string)$haystackTmp;
8207
8208 39
    if ($offset < 0) {
8209 2
      $offset = 0;
8210
    }
8211
8212 39
    $pos = \strpos($haystack, $needle);
8213 39
    if ($pos === false) {
8214 39
      return false;
8215
    }
8216
8217 4
    if ($pos) {
8218 4
      return ($offset + (self::strlen(substr($haystack, 0, $pos), $encoding)));
8219
    }
8220
8221 2
    return ($offset + 0);
8222
  }
8223
8224
  /**
8225
   * Find position of first occurrence of string in a string.
8226
   *
8227
   * @param string $haystack <p>
8228
   *                         The string being checked.
8229
   *                         </p>
8230
   * @param string $needle   <p>
8231
   *                         The position counted from the beginning of haystack.
8232
   *                         </p>
8233
   * @param int    $offset   [optional] <p>
8234
   *                         The search offset. If it is not specified, 0 is used.
8235
   *                         </p>
8236
   *
8237
   * @return int|false The numeric position of the first occurrence of needle in the
8238
   *                   haystack string. If needle is not found, it returns false.
8239
   */
8240 82
  public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0)
8241
  {
8242 82
    if ($haystack === '' || $needle === '') {
8243
      return false;
8244
    }
8245
8246 82
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8247
      self::checkForSupport();
8248
    }
8249
8250 82
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8251
      // "mb_" is available if overload is used, so use it ...
8252
      return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8253
    }
8254
8255 82
    return \strpos($haystack, $needle, $offset);
8256
  }
8257
8258
  /**
8259
   * Finds the last occurrence of a character in a string within another.
8260
   *
8261
   * @link http://php.net/manual/en/function.mb-strrchr.php
8262
   *
8263
   * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
8264
   * @param string $needle        <p>The string to find in haystack</p>
8265
   * @param bool   $before_needle [optional] <p>
8266
   *                              Determines which portion of haystack
8267
   *                              this function returns.
8268
   *                              If set to true, it returns all of haystack
8269
   *                              from the beginning to the last occurrence of needle.
8270
   *                              If set to false, it returns all of haystack
8271
   *                              from the last occurrence of needle to the end,
8272
   *                              </p>
8273
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
8274
   * @param bool   $cleanUtf8     [optional] <p>Remove non UTF-8 chars from the string.</p>
8275
   *
8276
   * @return string|false The portion of haystack or false if needle is not found.
8277
   */
8278 4
  public static function strrchr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8279
  {
8280 4
    if ('' === $haystack || '' === $needle) {
8281 2
      return false;
8282
    }
8283
8284 4
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8285 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8286
    }
8287
8288 4
    if ($cleanUtf8 === true) {
8289
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8290
      // if invalid characters are found in $haystack before $needle
8291 2
      $needle = self::clean($needle);
8292 2
      $haystack = self::clean($haystack);
8293
    }
8294
8295 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8296
      self::checkForSupport();
8297
    }
8298
8299
    if (
8300 4
        $encoding !== 'UTF-8'
8301
        &&
8302 4
        self::$SUPPORT['mbstring'] === false
8303
    ) {
8304
      \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8305
    }
8306
8307 4
    if (self::$SUPPORT['mbstring'] === true) {
8308 4
      return \mb_strrchr($haystack, $needle, $before_needle, $encoding);
8309
    }
8310
8311
    //
8312
    // fallback for binary || ascii only
8313
    //
8314
8315
    if (
8316
        $before_needle === false
8317
        &&
8318
        (
8319
            $encoding === 'CP850'
8320
            ||
8321
            $encoding === 'ASCII'
8322
        )
8323
    ) {
8324
      return \strrchr($haystack, $needle);
8325
    }
8326
8327
    //
8328
    // fallback via iconv
8329
    //
8330
8331
    if (self::$SUPPORT['iconv'] === true) {
8332
      $needleTmp = self::substr($needle, 0, 1, $encoding);
8333
      if ($needleTmp === false) {
8334
        return false;
8335
      }
8336
      $needle = (string)$needleTmp;
8337
8338
      $pos = \iconv_strrpos($haystack, $needle, $encoding);
8339
      if (false === $pos) {
8340
        return false;
8341
      }
8342
8343
      if ($before_needle) {
8344
        return self::substr($haystack, 0, $pos, $encoding);
8345
      }
8346
8347
      return self::substr($haystack, $pos, null, $encoding);
8348
    }
8349
8350
    //
8351
    // fallback via vanilla php
8352
    //
8353
8354
    $needleTmp = self::substr($needle, 0, 1, $encoding);
8355
    if ($needleTmp === false) {
8356
      return false;
8357
    }
8358
    $needle = (string)$needleTmp;
8359
8360
    $pos = self::strrpos($haystack, $needle, null, $encoding);
8361
    if ($pos === false) {
8362
      return false;
8363
    }
8364
8365
    if ($before_needle) {
8366
      return self::substr($haystack, 0, $pos, $encoding);
8367
    }
8368
8369
    return self::substr($haystack, $pos, null, $encoding);
8370
  }
8371
8372
  /**
8373
   * Reverses characters order in the string.
8374
   *
8375
   * @param string $str <p>The input string.</p>
8376
   *
8377
   * @return string The string with characters in the reverse sequence.
8378
   */
8379 10
  public static function strrev(string $str): string
8380
  {
8381 10
    if ('' === $str) {
8382 4
      return '';
8383
    }
8384
8385 8
    $reversed = '';
8386 8
    $i = self::strlen($str);
8387 8
    while ($i--) {
8388 8
      $reversed .= self::substr($str, $i, 1);
0 ignored issues
show
Bug introduced by
It seems like $i can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8388
      $reversed .= self::substr($str, /** @scrutinizer ignore-type */ $i, 1);
Loading history...
8389
    }
8390
8391 8
    return $reversed;
8392
  }
8393
8394
  /**
8395
   * Finds the last occurrence of a character in a string within another, case insensitive.
8396
   *
8397
   * @link http://php.net/manual/en/function.mb-strrichr.php
8398
   *
8399
   * @param string $haystack       <p>The string from which to get the last occurrence of needle.</p>
8400
   * @param string $needle         <p>The string to find in haystack.</p>
8401
   * @param bool   $before_needle  [optional] <p>
8402
   *                               Determines which portion of haystack
8403
   *                               this function returns.
8404
   *                               If set to true, it returns all of haystack
8405
   *                               from the beginning to the last occurrence of needle.
8406
   *                               If set to false, it returns all of haystack
8407
   *                               from the last occurrence of needle to the end,
8408
   *                               </p>
8409
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
8410
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
8411
   *
8412
   * @return string|false The portion of haystack or<br>false if needle is not found.
8413
   */
8414 3
  public static function strrichr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8415
  {
8416 3
    if ('' === $haystack || '' === $needle) {
8417 2
      return false;
8418
    }
8419
8420 3
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8421 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8422
    }
8423
8424 3
    if ($cleanUtf8 === true) {
8425
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8426
      // if invalid characters are found in $haystack before $needle
8427 2
      $needle = self::clean($needle);
8428 2
      $haystack = self::clean($haystack);
8429
    }
8430
8431 3
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8432
      self::checkForSupport();
8433
    }
8434
8435
    //
8436
    // fallback via mbstring
8437
    //
8438
8439 3
    if (self::$SUPPORT['mbstring'] === true) {
8440 3
      return \mb_strrichr($haystack, $needle, $before_needle, $encoding);
8441
    }
8442
8443
    //
8444
    // fallback via vanilla php
8445
    //
8446
8447
    $needleTmp = self::substr($needle, 0, 1, $encoding);
8448
    if ($needleTmp === false) {
8449
      return false;
8450
    }
8451
    $needle = (string)$needleTmp;
8452
8453
    $pos = self::strripos($haystack, $needle, 0, $encoding);
8454
    if ($pos === false) {
8455
      return false;
8456
    }
8457
8458
    if ($before_needle) {
8459
      return self::substr($haystack, 0, $pos, $encoding);
8460
    }
8461
8462
    return self::substr($haystack, $pos, null, $encoding);
8463
  }
8464
8465
  /**
8466
   * Find position of last occurrence of a case-insensitive string.
8467
   *
8468
   * @param string     $haystack  <p>The string to look in.</p>
8469
   * @param string|int $needle    <p>The string to look for.</p>
8470
   * @param int        $offset    [optional] <p>Number of characters to ignore in the beginning or end.</p>
8471
   * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
8472
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8473
   *
8474
   * @return int|false
8475
   *                   The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
8476
   *                   string.<br>If needle is not found, it returns false.
8477
   */
8478 4
  public static function strripos(string $haystack, $needle, int $offset = 0, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8479
  {
8480 4
    if ('' === $haystack) {
8481
      return false;
8482
    }
8483
8484
    // iconv and mbstring do not support integer $needle
8485 4
    if ((int)$needle === $needle && $needle >= 0) {
8486
      $needle = (string)self::chr($needle);
8487
    }
8488 4
    $needle = (string)$needle;
8489
8490 4
    if ('' === $needle) {
8491
      return false;
8492
    }
8493
8494 4
    if ($cleanUtf8 === true) {
8495
      // mb_strripos() && iconv_strripos() is not tolerant to invalid characters
8496 2
      $needle = self::clean($needle);
8497 2
      $haystack = self::clean($haystack);
8498
    }
8499
8500 4
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8501 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8502
    }
8503
8504
    //
8505
    // fallback for binary || ascii only
8506
    //
8507
8508
    if (
8509 4
        $encoding === 'CP850'
8510
        ||
8511 4
        $encoding === 'ASCII'
8512
    ) {
8513
      return self::strripos_in_byte($haystack, $needle, $offset);
8514
    }
8515
8516 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8517
      self::checkForSupport();
8518
    }
8519
8520
    if (
8521 4
        $encoding !== 'UTF-8'
8522
        &&
8523 4
        self::$SUPPORT['mbstring'] === false
8524
    ) {
8525
      \trigger_error('UTF8::strripos() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8526
    }
8527
8528
    //
8529
    // fallback via mbstrig
8530
    //
8531
8532 4
    if (self::$SUPPORT['mbstring'] === true) {
8533 4
      return \mb_strripos($haystack, $needle, $offset, $encoding);
8534
    }
8535
8536
    //
8537
    // fallback via intl
8538
    //
8539
8540
    if (
8541
        $encoding === 'UTF-8' // INFO: "grapheme_strripos()" can't handle other encodings
8542
        &&
8543
        $offset >= 0 // grapheme_strripos() can't handle negative offset
8544
        &&
8545
        self::$SUPPORT['intl'] === true
8546
    ) {
8547
      $returnTmp = \grapheme_strripos($haystack, $needle, $offset);
8548
      if ($returnTmp !== false) {
8549
        return $returnTmp;
8550
      }
8551
    }
8552
8553
    //
8554
    // fallback for ascii only
8555
    //
8556
8557
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
8558
      return self::strripos_in_byte($haystack, $needle, $offset);
8559
    }
8560
8561
    //
8562
    // fallback via vanilla php
8563
    //
8564
8565
    $haystack = self::strtocasefold($haystack, true, false, $encoding);
8566
    $needle = self::strtocasefold($needle, true, false, $encoding);
8567
8568
    return self::strrpos($haystack, $needle, $offset, $encoding, $cleanUtf8);
8569
  }
8570
8571
  /**
8572
   * Finds position of last occurrence of a string within another, case insensitive.
8573
   *
8574
   * @param string $haystack <p>
8575
   *                         The string from which to get the position of the last occurrence
8576
   *                         of needle.
8577
   *                         </p>
8578
   * @param string $needle   <p>
8579
   *                         The string to find in haystack.
8580
   *                         </p>
8581
   * @param int    $offset   [optional] <p>
8582
   *                         The position in haystack
8583
   *                         to start searching.
8584
   *                         </p>
8585
   *
8586
   * @return int|false Return the numeric position of the last occurrence of needle in the
8587
   *                   haystack string, or false if needle is not found.
8588
   */
8589
  public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0)
8590
  {
8591
    if ($haystack === '' || $needle === '') {
8592
      return false;
8593
    }
8594
8595
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8596
      self::checkForSupport();
8597
    }
8598
8599
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8600
      // "mb_" is available if overload is used, so use it ...
8601
      return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8602
    }
8603
8604
    return \strripos($haystack, $needle, $offset);
8605
  }
8606
8607
  /**
8608
   * Find position of last occurrence of a string in a string.
8609
   *
8610
   * @link http://php.net/manual/en/function.mb-strrpos.php
8611
   *
8612
   * @param string     $haystack  <p>The string being checked, for the last occurrence of needle</p>
8613
   * @param string|int $needle    <p>The string to find in haystack.<br>Or a code point as int.</p>
8614
   * @param int        $offset    [optional] <p>May be specified to begin searching an arbitrary number of characters
8615
   *                              into the string. Negative values will stop searching at an arbitrary point prior to
8616
   *                              the end of the string.
8617
   *                              </p>
8618
   * @param string     $encoding  [optional] <p>Set the charset.</p>
8619
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8620
   *
8621
   * @return int|false
8622
   *                   The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
8623
   *                   string.<br>If needle is not found, it returns false.
8624
   */
8625 38
  public static function strrpos(string $haystack, $needle, int $offset = null, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8626
  {
8627 38
    if ('' === $haystack) {
8628 3
      return false;
8629
    }
8630
8631
    // iconv and mbstring do not support integer $needle
8632 37
    if ((int)$needle === $needle && $needle >= 0) {
8633 2
      $needle = (string)self::chr($needle);
8634
    }
8635 37
    $needle = (string)$needle;
8636
8637 37
    if ('' === $needle) {
8638 2
      return false;
8639
    }
8640
8641 37
    if ($cleanUtf8 === true) {
8642
      // \mb_strrpos && iconv_strrpos is not tolerant to invalid characters
8643 4
      $needle = self::clean($needle);
8644 4
      $haystack = self::clean($haystack);
8645
    }
8646
8647 37
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8648 14
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8649
    }
8650
8651
    //
8652
    // fallback for binary || ascii only
8653
    //
8654
8655
    if (
8656 37
        $encoding === 'CP850'
8657
        ||
8658 37
        $encoding === 'ASCII'
8659
    ) {
8660 2
      return self::strrpos_in_byte($haystack, $needle, $offset);
0 ignored issues
show
Bug introduced by
It seems like $offset can also be of type null; however, parameter $offset of voku\helper\UTF8::strrpos_in_byte() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8660
      return self::strrpos_in_byte($haystack, $needle, /** @scrutinizer ignore-type */ $offset);
Loading history...
8661
    }
8662
8663 37
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8664
      self::checkForSupport();
8665
    }
8666
8667
    if (
8668 37
        $encoding !== 'UTF-8'
8669
        &&
8670 37
        self::$SUPPORT['mbstring'] === false
8671
    ) {
8672
      \trigger_error('UTF8::strrpos() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8673
    }
8674
8675
    //
8676
    // fallback via mbstring
8677
    //
8678
8679 37
    if (self::$SUPPORT['mbstring'] === true) {
8680 37
      return \mb_strrpos($haystack, $needle, $offset, $encoding);
8681
    }
8682
8683
    //
8684
    // fallback via intl
8685
    //
8686
8687
    if (
8688
        $offset !== null
8689
        &&
8690
        $offset >= 0 // grapheme_strrpos() can't handle negative offset
8691
        &&
8692
        $encoding === 'UTF-8' // INFO: "grapheme_strrpos()" can't handle other encodings
8693
        &&
8694
        self::$SUPPORT['intl'] === true
8695
    ) {
8696
      $returnTmp = \grapheme_strrpos($haystack, $needle, $offset);
8697
      if ($returnTmp !== false) {
8698
        return $returnTmp;
8699
      }
8700
    }
8701
8702
    //
8703
    // fallback for ascii only
8704
    //
8705
8706
    if (
8707
        $offset !== null
8708
        &&
8709
        self::is_ascii($haystack)
8710
        &&
8711
        self::is_ascii($needle)
8712
    ) {
8713
      return self::strrpos_in_byte($haystack, $needle, $offset);
8714
    }
8715
8716
    //
8717
    // fallback via vanilla php
8718
    //
8719
8720
    $haystackTmp = null;
8721
    if ($offset > 0) {
8722
      $haystackTmp = self::substr($haystack, $offset);
0 ignored issues
show
Bug introduced by
It seems like $offset can also be of type null; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8722
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ $offset);
Loading history...
8723
    } elseif ($offset < 0) {
8724
      $haystackTmp = self::substr($haystack, 0, $offset);
8725
      $offset = 0;
8726
    }
8727
8728
    if ($haystackTmp !== null) {
8729
      if ($haystackTmp === false) {
8730
        $haystackTmp = '';
8731
      }
8732
      $haystack = (string)$haystackTmp;
8733
    }
8734
8735
    $pos = self::strrpos_in_byte($haystack, $needle);
8736
    if ($pos === false) {
8737
      return false;
8738
    }
8739
8740
    return $offset + self::strlen(self::substr_in_byte($haystack, 0, $pos));
8741
  }
8742
8743
  /**
8744
   * Find position of last occurrence of a string in a string.
8745
   *
8746
   * @param string $haystack <p>
8747
   *                         The string being checked, for the last occurrence
8748
   *                         of needle.
8749
   *                         </p>
8750
   * @param string $needle   <p>
8751
   *                         The string to find in haystack.
8752
   *                         </p>
8753
   * @param int    $offset   [optional] May be specified to begin searching an arbitrary number of characters into
8754
   *                         the string. Negative values will stop searching at an arbitrary point
8755
   *                         prior to the end of the string.
8756
   *
8757
   * @return int|false The numeric position of the last occurrence of needle in the
8758
   *                   haystack string. If needle is not found, it returns false.
8759
   */
8760 2
  public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0)
8761
  {
8762 2
    if ($haystack === '' || $needle === '') {
8763
      return false;
8764
    }
8765
8766 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8767
      self::checkForSupport();
8768
    }
8769
8770 2
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8771
      // "mb_" is available if overload is used, so use it ...
8772
      return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8773
    }
8774
8775 2
    return \strrpos($haystack, $needle, $offset);
8776
  }
8777
8778
  /**
8779
   * Finds the length of the initial segment of a string consisting entirely of characters contained within a given
8780
   * mask.
8781
   *
8782
   * @param string $str    <p>The input string.</p>
8783
   * @param string $mask   <p>The mask of chars</p>
8784
   * @param int    $offset [optional]
8785
   * @param int    $length [optional]
8786
   *
8787
   * @return int
8788
   */
8789 10
  public static function strspn(string $str, string $mask, int $offset = 0, int $length = null): int
8790
  {
8791 10
    if ($offset || $length !== null) {
8792 2
      $strTmp = self::substr($str, $offset, $length);
8793 2
      if ($strTmp === false) {
8794
        $strTmp = '';
8795
      }
8796 2
      $str = (string)$strTmp;
8797
    }
8798
8799 10
    if ('' === $str || '' === $mask) {
8800 2
      return 0;
8801
    }
8802
8803 8
    return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, $str) ? self::strlen($str[0]) : 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return preg_match('/^' ....lf::strlen($str[0]) : 0 could return the type false which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
Bug introduced by
$str of type string is incompatible with the type array|null expected by parameter $matches of preg_match(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8803
    return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, /** @scrutinizer ignore-type */ $str) ? self::strlen($str[0]) : 0;
Loading history...
8804
  }
8805
8806
  /**
8807
   * Returns part of haystack string from the first occurrence of needle to the end of haystack.
8808
   *
8809
   * @param string $haystack       <p>The input string. Must be valid UTF-8.</p>
8810
   * @param string $needle         <p>The string to look for. Must be valid UTF-8.</p>
8811
   * @param bool   $before_needle  [optional] <p>
8812
   *                               If <b>TRUE</b>, strstr() returns the part of the
8813
   *                               haystack before the first occurrence of the needle (excluding the needle).
8814
   *                               </p>
8815
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
8816
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
8817
   *
8818
   * @return string|false
8819
   *                       A sub-string,<br>or <strong>false</strong> if needle is not found.
8820
   */
8821 5
  public static function strstr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', $cleanUtf8 = false)
8822
  {
8823 5
    if ('' === $haystack || '' === $needle) {
8824 2
      return false;
8825
    }
8826
8827 5
    if ($cleanUtf8 === true) {
8828
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8829
      // if invalid characters are found in $haystack before $needle
8830
      $needle = self::clean($needle);
8831
      $haystack = self::clean($haystack);
8832
    }
8833
8834 5
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8835 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8836
    }
8837
8838
    //
8839
    // fallback for binary || ascii only
8840
    //
8841
8842
    if (
8843 5
        $encoding === 'CP850'
8844
        ||
8845 5
        $encoding === 'ASCII'
8846
    ) {
8847
      return self::strstr_in_byte($haystack, $needle, $before_needle);
8848
    }
8849
8850 5
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8851
      self::checkForSupport();
8852
    }
8853
8854
    if (
8855 5
        $encoding !== 'UTF-8'
8856
        &&
8857 5
        self::$SUPPORT['mbstring'] === false
8858
    ) {
8859
      \trigger_error('UTF8::strstr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8860
    }
8861
8862
    //
8863
    // fallback via mbstring
8864
    //
8865
8866 5
    if (self::$SUPPORT['mbstring'] === true) {
8867 5
      return \mb_strstr($haystack, $needle, $before_needle, $encoding);
8868
    }
8869
8870
    //
8871
    // fallback via intl
8872
    //
8873
8874
    if (
8875
        $encoding === 'UTF-8' // INFO: "grapheme_strstr()" can't handle other encodings
8876
        &&
8877
        self::$SUPPORT['intl'] === true
8878
    ) {
8879
      $returnTmp = \grapheme_strstr($haystack, $needle, $before_needle);
8880
      if ($returnTmp !== false) {
8881
        return $returnTmp;
8882
      }
8883
    }
8884
8885
    //
8886
    // fallback for ascii only
8887
    //
8888
8889
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
8890
      return self::strstr_in_byte($haystack, $needle, $before_needle);
8891
    }
8892
8893
    //
8894
    // fallback via vanilla php
8895
    //
8896
8897
    \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/us', $haystack, $match);
8898
8899
    if (!isset($match[1])) {
8900
      return false;
8901
    }
8902
8903
    if ($before_needle) {
8904
      return $match[1];
8905
    }
8906
8907
    return self::substr($haystack, self::strlen($match[1]));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($match[1]) can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

8907
    return self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($match[1]));
Loading history...
8908
  }
8909
8910
  /**
8911
   *  * Finds first occurrence of a string within another.
8912
   *
8913
   * @param string $haystack      <p>
8914
   *                              The string from which to get the first occurrence
8915
   *                              of needle.
8916
   *                              </p>
8917
   * @param string $needle        <p>
8918
   *                              The string to find in haystack.
8919
   *                              </p>
8920
   * @param bool   $before_needle [optional] <p>
8921
   *                              Determines which portion of haystack
8922
   *                              this function returns.
8923
   *                              If set to true, it returns all of haystack
8924
   *                              from the beginning to the first occurrence of needle.
8925
   *                              If set to false, it returns all of haystack
8926
   *                              from the first occurrence of needle to the end,
8927
   *                              </p>
8928
   *
8929
   * @return string|false The portion of haystack,
8930
   *                      or false if needle is not found.
8931
   */
8932
  public static function strstr_in_byte(string $haystack, string $needle, bool $before_needle = false)
8933
  {
8934
    if ($haystack === '' || $needle === '') {
8935
      return false;
8936
    }
8937
8938
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8939
      self::checkForSupport();
8940
    }
8941
8942
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8943
      // "mb_" is available if overload is used, so use it ...
8944
      return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT
8945
    }
8946
8947
    return \strstr($haystack, $needle, $before_needle);
8948
  }
8949
8950
  /**
8951
   * Unicode transformation for case-less matching.
8952
   *
8953
   * @link http://unicode.org/reports/tr21/tr21-5.html
8954
   *
8955
   * @param string      $str       <p>The input string.</p>
8956
   * @param bool        $full      [optional] <p>
8957
   *                               <b>true</b>, replace full case folding chars (default)<br>
8958
   *                               <b>false</b>, use only limited static array [UTF8::$COMMON_CASE_FOLD]
8959
   *                               </p>
8960
   * @param bool        $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8961
   * @param string      $encoding  [optional] <p>Set the charset.</p>
8962
   * @param string|null $lang      [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8963
   * @param bool        $lower     [optional] <p>Use lowercase string, otherwise use uppercase string. PS: uppercase is
8964
   *                               for some languages better ...</p>
8965
   *
8966
   * @return string
8967
   */
8968 53
  public static function strtocasefold(
8969
      string $str,
8970
      bool $full = true,
8971
      bool $cleanUtf8 = false,
8972
      string $encoding = 'UTF-8',
8973
      string $lang = null,
8974
      $lower = true
8975
  ): string
8976
  {
8977 53
    if ('' === $str) {
8978 5
      return '';
8979
    }
8980
8981 52
    $str = self::fixStrCaseHelper($str, $lower, $full);
8982
8983 52
    if ($lower === true) {
8984 2
      return self::strtolower($str, $encoding, $cleanUtf8, $lang);
8985
    }
8986
8987 50
    return self::strtoupper($str, $encoding, $cleanUtf8, $lang);
8988
  }
8989
8990
  /**
8991
   * Make a string lowercase.
8992
   *
8993
   * @link http://php.net/manual/en/function.mb-strtolower.php
8994
   *
8995
   * @param string      $str                   <p>The string being lowercased.</p>
8996
   * @param string      $encoding              [optional] <p>Set the charset for e.g. "mb_" function</p>
8997
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
8998
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8999
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
9000
   *
9001
   * @return string String with all alphabetic characters converted to lowercase.
9002
   */
9003 156
  public static function strtolower($str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
9004
  {
9005
    // init
9006 156
    $str = (string)$str;
9007
9008 156
    if ('' === $str) {
9009 12
      return '';
9010
    }
9011
9012 154
    if ($cleanUtf8 === true) {
9013
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9014
      // if invalid characters are found in $haystack before $needle
9015 4
      $str = self::clean($str);
9016
    }
9017
9018 154
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9019 94
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9020
    }
9021
9022
    // hack for old php version or for the polyfill ...
9023 154
    if ($tryToKeepStringLength === true) {
9024
      $str = self::fixStrCaseHelper($str, true);
9025
    }
9026
9027 154
    if ($lang !== null) {
9028
9029 2
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9030
        self::checkForSupport();
9031
      }
9032
9033 2
      if (self::$SUPPORT['intl'] === true) {
9034
9035 2
        $langCode = $lang . '-Lower';
9036 2
        if (!\in_array($langCode, self::$SUPPORT['intl__transliterator_list_ids'], true)) {
9037
          \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang, E_USER_WARNING);
9038
9039
          $langCode = 'Any-Lower';
9040
        }
9041
9042
        /** @noinspection PhpComposerExtensionStubsInspection */
9043 2
        return transliterator_transliterate($langCode, $str);
9044
      }
9045
9046
      \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, E_USER_WARNING);
9047
    }
9048
9049
    // always fallback via symfony polyfill
9050 154
    return \mb_strtolower($str, $encoding);
9051
  }
9052
9053
  /**
9054
   * Generic case sensitive transformation for collation matching.
9055
   *
9056
   * @param string $str <p>The input string</p>
9057
   *
9058
   * @return string
9059
   */
9060 6
  private static function strtonatfold(string $str): string
9061
  {
9062
    /** @noinspection PhpUndefinedClassInspection */
9063 6
    return \preg_replace('/\p{Mn}+/u', '', \Normalizer::normalize($str, \Normalizer::NFD));
9064
  }
9065
9066
  /**
9067
   * Make a string uppercase.
9068
   *
9069
   * @link http://php.net/manual/en/function.mb-strtoupper.php
9070
   *
9071
   * @param string      $str                   <p>The string being uppercased.</p>
9072
   * @param string      $encoding              [optional] <p>Set the charset.</p>
9073
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
9074
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
9075
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
9076
   *
9077
   * @return string String with all alphabetic characters converted to uppercase.
9078
   */
9079 165
  public static function strtoupper($str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
9080
  {
9081
    // init
9082 165
    $str = (string)$str;
9083
9084 165
    if ('' === $str) {
9085 12
      return '';
9086
    }
9087
9088 163
    if ($cleanUtf8 === true) {
9089
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9090
      // if invalid characters are found in $haystack before $needle
9091 3
      $str = self::clean($str);
9092
    }
9093
9094 163
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9095 76
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9096
    }
9097
9098
    // hack for old php version or for the polyfill ...
9099 163
    if ($tryToKeepStringLength === true) {
9100 2
      $str = self::fixStrCaseHelper($str, false);
9101
    }
9102
9103 163
    if ($lang !== null) {
9104
9105 2
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9106
        self::checkForSupport();
9107
      }
9108
9109 2
      if (self::$SUPPORT['intl'] === true) {
9110
9111 2
        $langCode = $lang . '-Upper';
9112 2
        if (!\in_array($langCode, self::$SUPPORT['intl__transliterator_list_ids'], true)) {
9113
          \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, E_USER_WARNING);
9114
9115
          $langCode = 'Any-Upper';
9116
        }
9117
9118
        /** @noinspection PhpComposerExtensionStubsInspection */
9119 2
        return transliterator_transliterate($langCode, $str);
9120
      }
9121
9122
      \trigger_error('UTF8::strtolower() without intl + PHP >= 5.4 cannot handle the "lang"-parameter: ' . $lang, E_USER_WARNING);
9123
    }
9124
9125
    // always fallback via symfony polyfill
9126 163
    return \mb_strtoupper($str, $encoding);
9127
  }
9128
9129
  /**
9130
   * Translate characters or replace sub-strings.
9131
   *
9132
   * @link  http://php.net/manual/en/function.strtr.php
9133
   *
9134
   * @param string          $str  <p>The string being translated.</p>
9135
   * @param string|string[] $from <p>The string replacing from.</p>
9136
   * @param string|string[] $to   <p>The string being translated to to.</p>
9137
   *
9138
   * @return string
9139
   *                This function returns a copy of str, translating all occurrences of each character in from to the
9140
   *                corresponding character in to.
9141
   */
9142 2
  public static function strtr(string $str, $from, $to = INF): string
9143
  {
9144 2
    if ('' === $str) {
9145
      return '';
9146
    }
9147
9148 2
    if ($from === $to) {
9149
      return $str;
9150
    }
9151
9152 2
    if (INF !== $to) {
9153 2
      $from = self::str_split($from);
9154 2
      $to = self::str_split($to);
9155 2
      $countFrom = \count($from);
9156 2
      $countTo = \count($to);
9157
9158 2
      if ($countFrom > $countTo) {
9159 2
        $from = \array_slice($from, 0, $countTo);
9160 2
      } elseif ($countFrom < $countTo) {
9161 2
        $to = \array_slice($to, 0, $countFrom);
9162
      }
9163
9164 2
      $from = \array_combine($from, $to);
9165
    }
9166
9167 2
    if (\is_string($from)) {
9168 2
      return \str_replace($from, '', $str);
9169
    }
9170
9171 2
    return \strtr($str, $from);
9172
  }
9173
9174
  /**
9175
   * Return the width of a string.
9176
   *
9177
   * @param string $str       <p>The input string.</p>
9178
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9179
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9180
   *
9181
   * @return int
9182
   */
9183 2
  public static function strwidth(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): int
9184
  {
9185 2
    if ('' === $str) {
9186 2
      return 0;
9187
    }
9188
9189 2
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9190 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9191
    }
9192
9193 2
    if ($cleanUtf8 === true) {
9194
      // iconv and mbstring are not tolerant to invalid encoding
9195
      // further, their behaviour is inconsistent with that of PHP's substr
9196 2
      $str = self::clean($str);
9197
    }
9198
9199 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9200
      self::checkForSupport();
9201
    }
9202
9203
    //
9204
    // fallback via mbstring
9205
    //
9206
9207 2
    if (self::$SUPPORT['mbstring'] === true) {
9208 2
      return \mb_strwidth($str, $encoding);
9209
    }
9210
9211
    //
9212
    // fallback via vanilla php
9213
    //
9214
9215
    if ('UTF-8' !== $encoding) {
9216
      $str = self::encode('UTF-8', $str, false, $encoding);
9217
    }
9218
9219
    $wide = 0;
9220
    $str = (string)preg_replace('/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u', '', $str, -1, $wide);
9221
9222
    return ($wide << 1) + self::strlen($str, 'UTF-8');
9223
  }
9224
9225
  /**
9226
   * Get part of a string.
9227
   *
9228
   * @link http://php.net/manual/en/function.mb-substr.php
9229
   *
9230
   * @param string $str       <p>The string being checked.</p>
9231
   * @param int    $offset    <p>The first position used in str.</p>
9232
   * @param int    $length    [optional] <p>The maximum length of the returned string.</p>
9233
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9234
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9235
   *
9236
   * @return string|false
9237
   *                      The portion of <i>str</i> specified by the <i>offset</i> and
9238
   *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
9239
   *                      characters long, <b>FALSE</b> will be returned.
9240
   */
9241 403
  public static function substr(string $str, int $offset = 0, int $length = null, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
9242
  {
9243 403
    if ('' === $str) {
9244 26
      return '';
9245
    }
9246
9247
    // Empty string
9248 398
    if ($length === 0) {
9249 20
      return '';
9250
    }
9251
9252 395
    if ($cleanUtf8 === true) {
9253
      // iconv and mbstring are not tolerant to invalid encoding
9254
      // further, their behaviour is inconsistent with that of PHP's substr
9255 2
      $str = self::clean($str);
9256
    }
9257
9258
    // Whole string
9259 395
    if (!$offset && $length === null) {
9260 40
      return $str;
9261
    }
9262
9263 366
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9264 161
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9265
    }
9266
9267 366
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9268
      self::checkForSupport();
9269
    }
9270
9271
    //
9272
    // fallback for binary || ascii only
9273
    //
9274
9275
    if (
9276 366
        $encoding === 'CP850'
9277
        ||
9278 366
        $encoding === 'ASCII'
9279
    ) {
9280 2
      return self::substr_in_byte($str, $offset, $length);
9281
    }
9282
9283
    //
9284
    // fallback via mbstring
9285
    //
9286
9287 364
    if (self::$SUPPORT['mbstring'] === true) {
9288 364
      $return = \mb_substr($str, $offset, $length ?? 2147483647, $encoding);
9289 364
      if ($return !== false) {
9290 364
        return $return;
9291
      }
9292
    }
9293
9294
    // otherwise we need the string-length and can't fake it via "2147483647"
9295 4
    $str_length = 0;
9296 4
    if ($offset || $length === null) {
9297 4
      $str_length = self::strlen($str, $encoding);
9298
    }
9299
9300
    // e.g.: invalid chars + mbstring not installed
9301 4
    if ($str_length === false) {
9302
      return false;
9303
    }
9304
9305
    // Empty string
9306 4
    if ($offset === $str_length && !$length) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $length of type integer|null is loosely compared to false; this is ambiguous if the integer can be 0. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
9307
      return '';
9308
    }
9309
9310
    // Impossible
9311 4
    if ($offset && $offset > $str_length) {
9312
      // "false" is the php native return type here,
9313
      //  but we optimized this for performance ... see "2147483647" instead of "strlen"
9314
      return '';
9315
9316
    }
9317
9318 4
    if ($length === null) {
9319 4
      $length = (int)$str_length;
9320
    } else {
9321 2
      $length = (int)$length;
9322
    }
9323
9324
    if (
9325 4
        $encoding !== 'UTF-8'
9326
        &&
9327 4
        self::$SUPPORT['mbstring'] === false
9328
    ) {
9329 2
      \trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
9330
    }
9331
9332
    //
9333
    // fallback via intl
9334
    //
9335
9336
    if (
9337 4
        $encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
9338
        &&
9339 4
        $offset >= 0 // grapheme_substr() can't handle negative offset
9340
        &&
9341 4
        self::$SUPPORT['intl'] === true
9342
    ) {
9343
      $returnTmp = \grapheme_substr($str, $offset, $length);
9344
      if ($returnTmp !== false) {
9345
        return $returnTmp;
9346
      }
9347
    }
9348
9349
    //
9350
    // fallback via iconv
9351
    //
9352
9353
    if (
9354 4
        $length >= 0 // "iconv_substr()" can't handle negative length
9355
        &&
9356 4
        self::$SUPPORT['iconv'] === true
9357
    ) {
9358
      $returnTmp = \iconv_substr($str, $offset, $length);
9359
      if ($returnTmp !== false) {
9360
        return $returnTmp;
9361
      }
9362
    }
9363
9364
    //
9365
    // fallback for ascii only
9366
    //
9367
9368 4
    if (self::is_ascii($str)) {
9369
      return \substr($str, $offset, $length);
9370
    }
9371
9372
    //
9373
    // fallback via vanilla php
9374
    //
9375
9376
    // split to array, and remove invalid characters
9377 4
    $array = self::split($str);
9378
9379
    // extract relevant part, and join to make sting again
9380 4
    return \implode('', \array_slice($array, $offset, $length));
9381
  }
9382
9383
  /**
9384
   * Binary safe comparison of two strings from an offset, up to length characters.
9385
   *
9386
   * @param string   $str1               <p>The main string being compared.</p>
9387
   * @param string   $str2               <p>The secondary string being compared.</p>
9388
   * @param int      $offset             [optional] <p>The start position for the comparison. If negative, it starts
9389
   *                                     counting from the end of the string.</p>
9390
   * @param int|null $length             [optional] <p>The length of the comparison. The default value is the largest of
9391
   *                                     the length of the str compared to the length of main_str less the offset.</p>
9392
   * @param bool     $case_insensitivity [optional] <p>If case_insensitivity is TRUE, comparison is case
9393
   *                                     insensitive.</p>
9394
   *
9395
   * @return int
9396
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
9397
   *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
9398
   *             <strong>0</strong> if they are equal.
9399
   */
9400 2
  public static function substr_compare(string $str1, string $str2, int $offset = 0, int $length = null, bool $case_insensitivity = false): int
9401
  {
9402
    if (
9403 2
        $offset !== 0
9404
        ||
9405 2
        $length !== null
9406
    ) {
9407 2
      $str1Tmp = self::substr($str1, $offset, $length);
9408 2
      if ($str1Tmp === false) {
9409
        $str1Tmp = '';
9410
      }
9411 2
      $str1 = (string)$str1Tmp;
9412
9413 2
      $str2Tmp = self::substr($str2, 0, self::strlen($str1));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($str1) can also be of type false; however, parameter $length of voku\helper\UTF8::substr() does only seem to accept integer|null, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9413
      $str2Tmp = self::substr($str2, 0, /** @scrutinizer ignore-type */ self::strlen($str1));
Loading history...
9414 2
      if ($str2Tmp === false) {
9415
        $str2Tmp = '';
9416
      }
9417 2
      $str2 = (string)$str2Tmp;
9418
    }
9419
9420 2
    if ($case_insensitivity === true) {
9421 2
      return self::strcasecmp($str1, $str2);
9422
    }
9423
9424 2
    return self::strcmp($str1, $str2);
9425
  }
9426
9427
  /**
9428
   * Count the number of substring occurrences.
9429
   *
9430
   * @link  http://php.net/manual/en/function.substr-count.php
9431
   *
9432
   * @param string $haystack   <p>The string to search in.</p>
9433
   * @param string $needle     <p>The substring to search for.</p>
9434
   * @param int    $offset     [optional] <p>The offset where to start counting.</p>
9435
   * @param int    $length     [optional] <p>
9436
   *                           The maximum length after the specified offset to search for the
9437
   *                           substring. It outputs a warning if the offset plus the length is
9438
   *                           greater than the haystack length.
9439
   *                           </p>
9440
   * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
9441
   * @param bool   $cleanUtf8  [optional] <p>Remove non UTF-8 chars from the string.</p>
9442
   *
9443
   * @return int|false This functions returns an integer or false if there isn't a string.
9444
   */
9445 18
  public static function substr_count(
9446
      string $haystack,
9447
      string $needle,
9448
      int $offset = 0,
9449
      int $length = null,
9450
      string $encoding = 'UTF-8',
9451
      bool $cleanUtf8 = false
9452
  )
9453
  {
9454 18
    if ('' === $haystack || '' === $needle) {
9455 2
      return false;
9456
    }
9457
9458 18
    if ($offset || $length !== null) {
9459
9460 2
      if ($length === null) {
9461 2
        $lengthTmp = self::strlen($haystack);
9462 2
        if ($lengthTmp === false) {
9463
          return false;
9464
        }
9465 2
        $length = (int)$lengthTmp;
9466
      }
9467
9468
      if (
9469
          (
9470 2
              $length !== 0
9471
              &&
9472 2
              $offset !== 0
9473
          )
9474
          &&
9475 2
          ($length + $offset) <= 0
9476
          &&
9477 2
          Bootup::is_php('7.1') === false // output from "substr_count()" have changed in PHP 7.1
9478
      ) {
9479
        return false;
9480
      }
9481
9482 2
      $haystackTmp = self::substr($haystack, $offset, $length, $encoding);
9483 2
      if ($haystackTmp === false) {
9484
        $haystackTmp = '';
9485
      }
9486 2
      $haystack = (string)$haystackTmp;
9487
    }
9488
9489 18
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9490 8
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9491
    }
9492
9493 18
    if ($cleanUtf8 === true) {
9494
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9495
      // if invalid characters are found in $haystack before $needle
9496
      $needle = self::clean($needle);
9497
      $haystack = self::clean($haystack);
9498
    }
9499
9500 18
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9501
      self::checkForSupport();
9502
    }
9503
9504
    if (
9505 18
        $encoding !== 'UTF-8'
9506
        &&
9507 18
        self::$SUPPORT['mbstring'] === false
9508
    ) {
9509
      \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
9510
    }
9511
9512 18
    if (self::$SUPPORT['mbstring'] === true) {
9513 18
      return \mb_substr_count($haystack, $needle, $encoding);
9514
    }
9515
9516
    \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, PREG_SET_ORDER);
9517
9518
    return \count($matches);
9519
  }
9520
9521
  /**
9522
   * Count the number of substring occurrences.
9523
   *
9524
   * @param string $haystack <p>
9525
   *                         The string being checked.
9526
   *                         </p>
9527
   * @param string $needle   <p>
9528
   *                         The string being found.
9529
   *                         </p>
9530
   * @param int    $offset   [optional] <p>
9531
   *                         The offset where to start counting
9532
   *                         </p>
9533
   * @param int    $length   [optional] <p>
9534
   *                         The maximum length after the specified offset to search for the
9535
   *                         substring. It outputs a warning if the offset plus the length is
9536
   *                         greater than the haystack length.
9537
   *                         </p>
9538
   *
9539
   * @return int|false The number of times the
9540
   *                   needle substring occurs in the
9541
   *                   haystack string.
9542
   */
9543 36
  public static function substr_count_in_byte(string $haystack, string $needle, int $offset = 0, int $length = null)
9544
  {
9545 36
    if ($haystack === '' || $needle === '') {
9546
      return 0;
9547
    }
9548
9549 36
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9550
      self::checkForSupport();
9551
    }
9552
9553
    if (
9554 36
        ($offset || $length !== null)
9555
        &&
9556 36
        self::$SUPPORT['mbstring_func_overload'] === true
9557
    ) {
9558
9559
      if ($length === null) {
9560
        $lengthTmp = self::strlen($haystack);
9561
        if ($lengthTmp === false) {
9562
          return false;
9563
        }
9564
        $length = (int)$lengthTmp;
9565
      }
9566
9567
      if (
9568
          (
9569
              $length !== 0
9570
              &&
9571
              $offset !== 0
9572
          )
9573
          &&
9574
          ($length + $offset) <= 0
9575
          &&
9576
          Bootup::is_php('7.1') === false // output from "substr_count()" have changed in PHP 7.1
9577
      ) {
9578
        return false;
9579
      }
9580
9581
      $haystackTmp = self::substr_in_byte($haystack, $offset, $length);
9582
      if ($haystackTmp === false) {
0 ignored issues
show
introduced by
The condition $haystackTmp === false is always false.
Loading history...
9583
        $haystackTmp = '';
9584
      }
9585
      $haystack = (string)$haystackTmp;
9586
    }
9587
9588 36
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
9589
      // "mb_" is available if overload is used, so use it ...
9590
      return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT
9591
    }
9592
9593 36
    return \substr_count($haystack, $needle, $offset, $length);
9594
  }
9595
9596
  /**
9597
   * Returns the number of occurrences of $substring in the given string.
9598
   * By default, the comparison is case-sensitive, but can be made insensitive
9599
   * by setting $caseSensitive to false.
9600
   *
9601
   * @param string $str           <p>The input string.</p>
9602
   * @param string $substring     <p>The substring to search for.</p>
9603
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
9604
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
9605
   *
9606
   * @return int
9607
   */
9608 15
  public static function substr_count_simple(string $str, string $substring, $caseSensitive = true, string $encoding = 'UTF-8'): int
9609
  {
9610 15
    if ('' === $str || '' === $substring) {
9611 2
      return 0;
9612
    }
9613
9614
    // only a fallback to prevent BC in the api ...
9615 13
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
9616 4
      $encoding = (string)$caseSensitive;
9617
    }
9618
9619 13
    if (!$caseSensitive) {
9620 6
      $str = self::strtocasefold($str, true, false, $encoding, null, false);
9621 6
      $substring = self::strtocasefold($substring, true, false, $encoding, null, false);
9622
    }
9623
9624 13
    return (int)self::substr_count($str, $substring, 0, null, $encoding);
9625
  }
9626
9627
  /**
9628
   * Removes an prefix ($needle) from start of the string ($haystack), case insensitive.
9629
   *
9630
   * @param string $haystack <p>The string to search in.</p>
9631
   * @param string $needle   <p>The substring to search for.</p>
9632
   *
9633
   * @return string Return the sub-string.
9634
   */
9635 2
  public static function substr_ileft(string $haystack, string $needle): string
9636
  {
9637 2
    if ('' === $haystack) {
9638 2
      return '';
9639
    }
9640
9641 2
    if ('' === $needle) {
9642 2
      return $haystack;
9643
    }
9644
9645 2
    if (self::str_istarts_with($haystack, $needle) === true) {
9646 2
      $haystackTmp = self::substr($haystack, self::strlen($needle));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($needle) can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9646
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($needle));
Loading history...
9647 2
      if ($haystackTmp === false) {
9648
        $haystackTmp = '';
9649
      }
9650 2
      $haystack = (string)$haystackTmp;
9651
    }
9652
9653 2
    return $haystack;
9654
  }
9655
9656
  /**
9657
   * Get part of a string process in bytes.
9658
   *
9659
   * @param string $str    <p>The string being checked.</p>
9660
   * @param int    $offset <p>The first position used in str.</p>
9661
   * @param int    $length [optional] <p>The maximum length of the returned string.</p>
9662
   *
9663
   * @return string|false
9664
   *                      The portion of <i>str</i> specified by the <i>offset</i> and
9665
   *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
9666
   *                      characters long, <b>FALSE</b> will be returned.
9667
   */
9668 50
  public static function substr_in_byte(string $str, int $offset = 0, int $length = null)
9669
  {
9670 50
    if ($str === '') {
9671
      return '';
9672
    }
9673
9674
    // Empty string
9675 50
    if ($length === 0) {
9676
      return '';
9677
    }
9678
9679
    // Whole string
9680 50
    if (!$offset && $length === null) {
9681
      return $str;
9682
    }
9683
9684 50
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9685
      self::checkForSupport();
9686
    }
9687
9688 50
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
9689
      // "mb_" is available if overload is used, so use it ...
9690
      return \mb_substr($str, $offset, $length ?? 2147483647, 'CP850'); // 8-BIT
9691
    }
9692
9693 50
    return \substr($str, $offset, $length ?? 2147483647);
9694
  }
9695
9696
  /**
9697
   * Removes an suffix ($needle) from end of the string ($haystack), case insensitive.
9698
   *
9699
   * @param string $haystack <p>The string to search in.</p>
9700
   * @param string $needle   <p>The substring to search for.</p>
9701
   *
9702
   * @return string Return the sub-string.
9703
   */
9704 2
  public static function substr_iright(string $haystack, string $needle): string
9705
  {
9706 2
    if ('' === $haystack) {
9707 2
      return '';
9708
    }
9709
9710 2
    if ('' === $needle) {
9711 2
      return $haystack;
9712
    }
9713
9714 2
    if (self::str_iends_with($haystack, $needle) === true) {
9715 2
      $haystackTmp = self::substr($haystack, 0, self::strlen($haystack) - self::strlen($needle));
9716 2
      if ($haystackTmp === false) {
9717
        $haystackTmp = '';
9718
      }
9719 2
      $haystack = (string)$haystackTmp;
9720
    }
9721
9722 2
    return $haystack;
9723
  }
9724
9725
  /**
9726
   * Removes an prefix ($needle) from start of the string ($haystack).
9727
   *
9728
   * @param string $haystack <p>The string to search in.</p>
9729
   * @param string $needle   <p>The substring to search for.</p>
9730
   *
9731
   * @return string Return the sub-string.
9732
   */
9733 2
  public static function substr_left(string $haystack, string $needle): string
9734
  {
9735 2
    if ('' === $haystack) {
9736 2
      return '';
9737
    }
9738
9739 2
    if ('' === $needle) {
9740 2
      return $haystack;
9741
    }
9742
9743 2
    if (self::str_starts_with($haystack, $needle) === true) {
9744 2
      $haystackTmp = self::substr($haystack, self::strlen($needle));
0 ignored issues
show
Bug introduced by
It seems like self::strlen($needle) can also be of type false; however, parameter $offset of voku\helper\UTF8::substr() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9744
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($needle));
Loading history...
9745 2
      if ($haystackTmp === false) {
9746
        $haystackTmp = '';
9747
      }
9748 2
      $haystack = (string)$haystackTmp;
9749
    }
9750
9751 2
    return $haystack;
9752
  }
9753
9754
  /**
9755
   * Replace text within a portion of a string.
9756
   *
9757
   * source: https://gist.github.com/stemar/8287074
9758
   *
9759
   * @param string|string[] $str              <p>The input string or an array of stings.</p>
9760
   * @param string|string[] $replacement      <p>The replacement string or an array of stings.</p>
9761
   * @param int|int[]       $offset           <p>
9762
   *                                          If start is positive, the replacing will begin at the start'th offset
9763
   *                                          into string.
9764
   *                                          <br><br>
9765
   *                                          If start is negative, the replacing will begin at the start'th character
9766
   *                                          from the end of string.
9767
   *                                          </p>
9768
   * @param int|int[]|null  $length           [optional] <p>If given and is positive, it represents the length of the
9769
   *                                          portion of string which is to be replaced. If it is negative, it
9770
   *                                          represents the number of characters from the end of string at which to
9771
   *                                          stop replacing. If it is not given, then it will default to strlen(
9772
   *                                          string ); i.e. end the replacing at the end of string. Of course, if
9773
   *                                          length is zero then this function will have the effect of inserting
9774
   *                                          replacement into string at the given start offset.</p>
9775
   * @param string          $encoding         [optional] <p>Set the charset for e.g. "mb_" function</p>
9776
   *
9777
   * @return string|string[] The result string is returned. If string is an array then array is returned.
9778
   */
9779 10
  public static function substr_replace($str, $replacement, $offset, $length = null, string $encoding = 'UTF-8')
9780
  {
9781 10
    if (\is_array($str) === true) {
9782 1
      $num = \count($str);
9783
9784
      // the replacement
9785 1
      if (\is_array($replacement) === true) {
9786 1
        $replacement = \array_slice($replacement, 0, $num);
9787
      } else {
9788 1
        $replacement = \array_pad([$replacement], $num, $replacement);
9789
      }
9790
9791
      // the offset
9792 1
      if (\is_array($offset) === true) {
9793 1
        $offset = \array_slice($offset, 0, $num);
9794 1
        foreach ($offset as &$valueTmp) {
9795 1
          $valueTmp = (int)$valueTmp === $valueTmp ? $valueTmp : 0;
9796
        }
9797 1
        unset($valueTmp);
9798
      } else {
9799 1
        $offset = \array_pad([$offset], $num, $offset);
9800
      }
9801
9802
      // the length
9803 1
      if (null === $length) {
9804 1
        $length = \array_fill(0, $num, 0);
9805 1
      } elseif (\is_array($length) === true) {
9806 1
        $length = \array_slice($length, 0, $num);
9807 1
        foreach ($length as &$valueTmpV2) {
9808 1
          if (null !== $valueTmpV2) {
9809 1
            $valueTmpV2 = (int)$valueTmpV2 === $valueTmpV2 ? $valueTmpV2 : $num;
9810
          } else {
9811 1
            $valueTmpV2 = 0;
9812
          }
9813
        }
9814 1
        unset($valueTmpV2);
9815
      } else {
9816 1
        $length = \array_pad([$length], $num, $length);
9817
      }
9818
9819
      // recursive call
9820 1
      return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length);
9821
    }
9822
9823 10
    if (\is_array($replacement) === true) {
9824 1
      if (\count($replacement) > 0) {
9825 1
        $replacement = $replacement[0];
9826
      } else {
9827 1
        $replacement = '';
9828
      }
9829
    }
9830
9831
    // init
9832 10
    $str = (string)$str;
9833 10
    $replacement = (string)$replacement;
9834
9835 10
    if ('' === $str) {
9836 1
      return $replacement;
9837
    }
9838
9839 9
    if (self::is_ascii($str)) {
9840 6
      return ($length === null) ?
9841
          \substr_replace($str, $replacement, $offset) :
0 ignored issues
show
Bug introduced by
It seems like $offset can also be of type integer[]; however, parameter $start of substr_replace() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9841
          \substr_replace($str, $replacement, /** @scrutinizer ignore-type */ $offset) :
Loading history...
9842 6
          \substr_replace($str, $replacement, $offset, $length);
0 ignored issues
show
Bug introduced by
It seems like $length can also be of type integer[]; however, parameter $length of substr_replace() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9842
          \substr_replace($str, $replacement, $offset, /** @scrutinizer ignore-type */ $length);
Loading history...
9843
    }
9844
9845 8
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9846
      self::checkForSupport();
9847
    }
9848
9849 8
    if (self::$SUPPORT['mbstring'] === true) {
9850 8
      $string_length = self::strlen($str, $encoding);
9851
9852 8
      if ($offset < 0) {
9853 1
        $offset = \max(0, $string_length + $offset);
9854 8
      } elseif ($offset > $string_length) {
9855
        $offset = $string_length;
9856
      }
9857
9858 8
      if ($length < 0) {
9859 1
        $length = \max(0, $string_length - $offset + $length);
9860 8
      } elseif ($length === null || $length > $string_length) {
9861 3
        $length = $string_length;
9862
      }
9863
9864 8
      if (($offset + $length) > $string_length) {
9865 3
        $length = $string_length - $offset;
9866
      }
9867
9868 8
      return self::substr($str, 0, $offset, $encoding) . $replacement . self::substr($str, $offset + $length, $string_length - $offset - $length, $encoding);
0 ignored issues
show
Bug introduced by
Are you sure self::substr($str, $offs...t - $length, $encoding) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9868
      return self::substr($str, 0, $offset, $encoding) . $replacement . /** @scrutinizer ignore-type */ self::substr($str, $offset + $length, $string_length - $offset - $length, $encoding);
Loading history...
Bug introduced by
Are you sure self::substr($str, 0, $offset, $encoding) of type false|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9868
      return /** @scrutinizer ignore-type */ self::substr($str, 0, $offset, $encoding) . $replacement . self::substr($str, $offset + $length, $string_length - $offset - $length, $encoding);
Loading history...
9869
    }
9870
9871
    \preg_match_all('/./us', $str, $smatches);
9872
    \preg_match_all('/./us', $replacement, $rmatches);
9873
9874
    if ($length === null) {
9875
      $lengthTmp = self::strlen($str, $encoding);
9876
      if ($lengthTmp === false) {
9877
        // e.g.: non mbstring support + invalid chars
9878
        return '';
9879
      }
9880
      $length = (int)$lengthTmp;
9881
    }
9882
9883
    \array_splice($smatches[0], $offset, $length, $rmatches[0]);
0 ignored issues
show
Bug introduced by
It seems like $length can also be of type integer[]; however, parameter $length of array_splice() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9883
    \array_splice($smatches[0], $offset, /** @scrutinizer ignore-type */ $length, $rmatches[0]);
Loading history...
Bug introduced by
It seems like $offset can also be of type integer[]; however, parameter $offset of array_splice() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

9883
    \array_splice($smatches[0], /** @scrutinizer ignore-type */ $offset, $length, $rmatches[0]);
Loading history...
9884
9885
    return \implode('', $smatches[0]);
9886
  }
9887
9888
  /**
9889
   * Removes an suffix ($needle) from end of the string ($haystack).
9890
   *
9891
   * @param string $haystack <p>The string to search in.</p>
9892
   * @param string $needle   <p>The substring to search for.</p>
9893
   *
9894
   * @return string Return the sub-string.
9895
   */
9896 2
  public static function substr_right(string $haystack, string $needle): string
9897
  {
9898 2
    if ('' === $haystack) {
9899 2
      return '';
9900
    }
9901
9902 2
    if ('' === $needle) {
9903 2
      return $haystack;
9904
    }
9905
9906 2
    if (self::str_ends_with($haystack, $needle) === true) {
9907 2
      $haystackTmp = self::substr($haystack, 0, self::strlen($haystack) - self::strlen($needle));
9908 2
      if ($haystackTmp === false) {
9909
        $haystackTmp = '';
9910
      }
9911 2
      $haystack = (string)$haystackTmp;
9912
    }
9913
9914 2
    return $haystack;
9915
  }
9916
9917
  /**
9918
   * Returns a case swapped version of the string.
9919
   *
9920
   * @param string $str       <p>The input string.</p>
9921
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9922
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9923
   *
9924
   * @return string Each character's case swapped.
9925
   */
9926 6
  public static function swapCase(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
9927
  {
9928 6
    if ('' === $str) {
9929 1
      return '';
9930
    }
9931
9932 6
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9933 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9934
    }
9935
9936 6
    if ($cleanUtf8 === true) {
9937
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9938
      // if invalid characters are found in $haystack before $needle
9939 2
      $str = self::clean($str);
9940
    }
9941
9942 6
    return (string)(self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str);
9943
  }
9944
9945
  /**
9946
   * Checks whether mbstring is available on the server.
9947
   *
9948
   * @return bool
9949
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
9950
   */
9951
  public static function symfony_polyfill_used(): bool
9952
  {
9953
    // init
9954
    $return = false;
9955
9956
    $returnTmp = \extension_loaded('mbstring') ? true : false;
9957
    if ($returnTmp === false && \function_exists('mb_strlen')) {
9958
      $return = true;
9959
    }
9960
9961
    $returnTmp = \extension_loaded('iconv') ? true : false;
9962
    if ($returnTmp === false && \function_exists('iconv')) {
9963
      $return = true;
9964
    }
9965
9966
    return $return;
9967
  }
9968
9969
  /**
9970
   * @param string $str
9971
   * @param int    $tabLength
9972
   *
9973
   * @return string
9974
   */
9975 6
  public static function tabs_to_spaces(string $str, int $tabLength = 4): string
9976
  {
9977 6
    return \str_replace("\t", \str_repeat(' ', $tabLength), $str);
9978
  }
9979
9980
  /**
9981
   * Converts the first character of each word in the string to uppercase
9982
   * and all other chars to lowercase.
9983
   *
9984
   * @param string      $str                   <p>The input string.</p>
9985
   * @param string      $encoding              [optional] <p>Set the charset for e.g. "mb_" function</p>
9986
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
9987
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
9988
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
9989
   *
9990
   * @return string String with all characters of $str being title-cased.
9991
   */
9992 5
  public static function titlecase(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
9993
  {
9994 5
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9995 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9996
    }
9997
9998 5
    return self::str_titleize($str, null, $encoding, $cleanUtf8, $lang, $tryToKeepStringLength, false);
9999
  }
10000
10001
  /**
10002
   * alias for "UTF8::to_ascii()"
10003
   *
10004
   * @see        UTF8::to_ascii()
10005
   *
10006
   * @param string $str
10007
   * @param string $subst_chr
10008
   * @param bool   $strict
10009
   *
10010
   * @return string
10011
   *
10012
   * @deprecated <p>use "UTF8::to_ascii()"</p>
10013
   */
10014 7
  public static function toAscii(string $str, string $subst_chr = '?', bool $strict = false): string
10015
  {
10016 7
    return self::to_ascii($str, $subst_chr, $strict);
10017
  }
10018
10019
  /**
10020
   * alias for "UTF8::to_iso8859()"
10021
   *
10022
   * @see        UTF8::to_iso8859()
10023
   *
10024
   * @param string|string[] $str
10025
   *
10026
   * @return string|string[]
10027
   *
10028
   * @deprecated <p>use "UTF8::to_iso8859()"</p>
10029
   */
10030 2
  public static function toIso8859($str)
10031
  {
10032 2
    return self::to_iso8859($str);
10033
  }
10034
10035
  /**
10036
   * alias for "UTF8::to_latin1()"
10037
   *
10038
   * @see        UTF8::to_latin1()
10039
   *
10040
   * @param string|string[] $str
10041
   *
10042
   * @return string|string[]
10043
   *
10044
   * @deprecated <p>use "UTF8::to_latin1()"</p>
10045
   */
10046 2
  public static function toLatin1($str)
10047
  {
10048 2
    return self::to_latin1($str);
10049
  }
10050
10051
  /**
10052
   * alias for "UTF8::to_utf8()"
10053
   *
10054
   * @see        UTF8::to_utf8()
10055
   *
10056
   * @param string|string[] $str
10057
   *
10058
   * @return string|string[]
10059
   *
10060
   * @deprecated <p>use "UTF8::to_utf8()"</p>
10061
   */
10062 2
  public static function toUTF8($str)
10063
  {
10064 2
    return self::to_utf8($str);
10065
  }
10066
10067
  /**
10068
   * Convert a string into ASCII.
10069
   *
10070
   * @param string $str     <p>The input string.</p>
10071
   * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
10072
   * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
10073
   *                        performance</p>
10074
   *
10075
   * @return string
10076
   */
10077 38
  public static function to_ascii(string $str, string $unknown = '?', bool $strict = false): string
10078
  {
10079 38
    static $UTF8_TO_ASCII;
10080
10081 38
    if ('' === $str) {
10082 3
      return '';
10083
    }
10084
10085
    // check if we only have ASCII, first (better performance)
10086 35
    if (self::is_ascii($str) === true) {
10087 7
      return $str;
10088
    }
10089
10090 30
    $str = self::clean(
10091 30
        $str,
10092 30
        true,
10093 30
        true,
10094 30
        true,
10095 30
        false,
10096 30
        true,
10097 30
        true
10098
    );
10099
10100
    // check again, if we only have ASCII, now ...
10101 30
    if (self::is_ascii($str) === true) {
10102 12
      return $str;
10103
    }
10104
10105 19
    if ($strict === true) {
10106
10107 1
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
10108
        self::checkForSupport();
10109
      }
10110
10111 1
      if (self::$SUPPORT['intl'] === true) {
10112
        // INFO: https://unicode.org/cldr/utility/character.jsp?a=%E2%84%8C
10113
        /** @noinspection PhpComposerExtensionStubsInspection */
10114 1
        $str = \transliterator_transliterate('NFKC; [:Nonspacing Mark:] Remove; NFKC; Any-Latin; Latin-ASCII;', $str);
10115
10116
        // check again, if we only have ASCII, now ...
10117 1
        if (self::is_ascii($str) === true) {
10118 1
          return $str;
10119
        }
10120
10121
      }
10122
    }
10123
10124 19
    if (self::$ORD === null) {
10125
      self::$ORD = self::getData('ord');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('ord') can also be of type false. However, the property $ORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10126
    }
10127
10128 19
    \preg_match_all('/.{1}|[^\x00]{1,1}$/us', $str, $ar);
10129 19
    $chars = $ar[0];
10130 19
    $ord = null;
10131 19
    foreach ($chars as &$c) {
10132
10133 19
      $ordC0 = self::$ORD[$c[0]];
10134
10135 19
      if ($ordC0 >= 0 && $ordC0 <= 127) {
10136 15
        continue;
10137
      }
10138
10139 19
      $ordC1 = self::$ORD[$c[1]];
10140
10141
      // ASCII - next please
10142 19
      if ($ordC0 >= 192 && $ordC0 <= 223) {
10143 17
        $ord = ($ordC0 - 192) * 64 + ($ordC1 - 128);
10144
      }
10145
10146 19
      if ($ordC0 >= 224) {
10147 8
        $ordC2 = self::$ORD[$c[2]];
10148
10149 8
        if ($ordC0 <= 239) {
10150 7
          $ord = ($ordC0 - 224) * 4096 + ($ordC1 - 128) * 64 + ($ordC2 - 128);
10151
        }
10152
10153 8
        if ($ordC0 >= 240) {
10154 2
          $ordC3 = self::$ORD[$c[3]];
10155
10156 2
          if ($ordC0 <= 247) {
10157 2
            $ord = ($ordC0 - 240) * 262144 + ($ordC1 - 128) * 4096 + ($ordC2 - 128) * 64 + ($ordC3 - 128);
10158
          }
10159
10160 2
          if ($ordC0 >= 248) {
10161
            $ordC4 = self::$ORD[$c[4]];
10162
10163
            if ($ordC0 <= 251) {
10164
              $ord = ($ordC0 - 248) * 16777216 + ($ordC1 - 128) * 262144 + ($ordC2 - 128) * 4096 + ($ordC3 - 128) * 64 + ($ordC4 - 128);
10165
            }
10166
10167
            if ($ordC0 >= 252) {
10168
              $ordC5 = self::$ORD[$c[5]];
10169
10170
              if ($ordC0 <= 253) {
10171
                $ord = ($ordC0 - 252) * 1073741824 + ($ordC1 - 128) * 16777216 + ($ordC2 - 128) * 262144 + ($ordC3 - 128) * 4096 + ($ordC4 - 128) * 64 + ($ordC5 - 128);
10172
              }
10173
            }
10174
          }
10175
        }
10176
      }
10177
10178 19
      if ($ordC0 === 254 || $ordC0 === 255) {
10179
        $c = $unknown;
10180
        continue;
10181
      }
10182
10183 19
      if ($ord === null) {
10184
        $c = $unknown;
10185
        continue;
10186
      }
10187
10188 19
      $bank = $ord >> 8;
10189 19
      if (!isset($UTF8_TO_ASCII[$bank])) {
10190 9
        $UTF8_TO_ASCII[$bank] = self::getData(\sprintf('x%02x', $bank));
10191 9
        if ($UTF8_TO_ASCII[$bank] === false) {
10192 2
          $UTF8_TO_ASCII[$bank] = [];
10193
        }
10194
      }
10195
10196 19
      $newchar = $ord & 255;
10197
10198 19
      if (isset($UTF8_TO_ASCII[$bank][$newchar])) {
10199
10200
        // keep for debugging
10201
        /*
10202
        echo "file: " . sprintf('x%02x', $bank) . "\n";
10203
        echo "char: " . $c . "\n";
10204
        echo "ord: " . $ord . "\n";
10205
        echo "newchar: " . $newchar . "\n";
10206
        echo "ascii: " . $UTF8_TO_ASCII[$bank][$newchar] . "\n";
10207
        echo "bank:" . $bank . "\n\n";
10208
        */
10209
10210 18
        $c = $UTF8_TO_ASCII[$bank][$newchar];
10211
      } else {
10212
10213
        // keep for debugging missing chars
10214
        /*
10215
        echo "file: " . sprintf('x%02x', $bank) . "\n";
10216
        echo "char: " . $c . "\n";
10217
        echo "ord: " . $ord . "\n";
10218
        echo "newchar: " . $newchar . "\n";
10219
        echo "bank:" . $bank . "\n\n";
10220
        */
10221
10222 19
        $c = $unknown;
10223
      }
10224
    }
10225
10226 19
    return \implode('', $chars);
10227
  }
10228
10229
  /**
10230
   * @param mixed $str
10231
   *
10232
   * @return bool
10233
   */
10234 19
  public static function to_boolean($str): bool
10235
  {
10236
    // init
10237 19
    $str = (string)$str;
10238
10239 19
    if ('' === $str) {
10240 2
      return false;
10241
    }
10242
10243 17
    $key = \strtolower($str);
10244
10245
    // Info: http://php.net/manual/en/filter.filters.validate.php
10246
    $map = [
10247 17
        'true'  => true,
10248
        '1'     => true,
10249
        'on'    => true,
10250
        'yes'   => true,
10251
        'false' => false,
10252
        '0'     => false,
10253
        'off'   => false,
10254
        'no'    => false,
10255
    ];
10256
10257 17
    if (isset($map[$key])) {
10258 13
      return $map[$key];
10259
    }
10260
10261
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
10262 4
    if (\is_numeric($str)) {
10263 2
      return (((float)$str + 0) > 0);
10264
    }
10265
10266 2
    return (bool)self::trim($str);
10267
  }
10268
10269
  /**
10270
   * Convert given string to safe filename (and keep string case).
10271
   *
10272
   * @param string $string
10273
   * @param bool   $use_transliterate No transliteration, conversion etc. is done by default - unsafe characters are
10274
   *                                  simply replaced with hyphen.
10275
   * @param string $fallback_char
10276
   *
10277
   * @return string
10278
   */
10279 1
  public static function to_filename(string $string, bool $use_transliterate = false, string $fallback_char = '-'): string
10280
  {
10281 1
    if ($use_transliterate === true) {
10282 1
      $string = self::str_transliterate($string, $fallback_char);
10283
    }
10284
10285 1
    $fallback_char_escaped = \preg_quote($fallback_char, '/');
10286
10287 1
    $string = (string)\preg_replace(
10288
        [
10289 1
            '/[^' . $fallback_char_escaped . '\.\-a-zA-Z0-9\s]/', // 1) remove un-needed chars
10290 1
            '/[\s]+/',                                            // 2) convert spaces to $fallback_char
10291 1
            '/[' . $fallback_char_escaped . ']+/',                // 3) remove double $fallback_char's
10292
        ],
10293
        [
10294 1
            '',
10295 1
            $fallback_char,
10296 1
            $fallback_char,
10297
        ],
10298 1
        $string
10299
    );
10300
10301
    // trim "$fallback_char" from beginning and end of the string
10302 1
    return \trim($string, $fallback_char);
10303
  }
10304
10305
  /**
10306
   * Convert a string into "ISO-8859"-encoding (Latin-1).
10307
   *
10308
   * @param string|string[] $str
10309
   *
10310
   * @return string|string[]
10311
   */
10312 7
  public static function to_iso8859($str)
10313
  {
10314 7
    if (\is_array($str) === true) {
10315 2
      foreach ($str as $k => $v) {
10316 2
        $str[$k] = self::to_iso8859($v);
10317
      }
10318
10319 2
      return $str;
10320
    }
10321
10322 7
    $str = (string)$str;
10323 7
    if ('' === $str) {
10324 2
      return '';
10325
    }
10326
10327 7
    return self::utf8_decode($str);
10328
  }
10329
10330
  /**
10331
   * alias for "UTF8::to_iso8859()"
10332
   *
10333
   * @see UTF8::to_iso8859()
10334
   *
10335
   * @param string|string[] $str
10336
   *
10337
   * @return string|string[]
10338
   */
10339 2
  public static function to_latin1($str)
10340
  {
10341 2
    return self::to_iso8859($str);
10342
  }
10343
10344
  /**
10345
   * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
10346
   *
10347
   * <ul>
10348
   * <li>It decode UTF-8 codepoints and unicode escape sequences.</li>
10349
   * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
10350
   * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
10351
   * case.</li>
10352
   * </ul>
10353
   *
10354
   * @param string|string[] $str                    <p>Any string or array.</p>
10355
   * @param bool            $decodeHtmlEntityToUtf8 <p>Set to true, if you need to decode html-entities.</p>
10356
   *
10357
   * @return string|string[] The UTF-8 encoded string.
10358
   */
10359 37
  public static function to_utf8($str, bool $decodeHtmlEntityToUtf8 = false)
10360
  {
10361 37
    if (\is_array($str) === true) {
10362 4
      foreach ($str as $k => $v) {
10363 4
        $str[$k] = self::to_utf8($v, $decodeHtmlEntityToUtf8);
10364
      }
10365
10366 4
      return $str;
10367
    }
10368
10369 37
    $str = (string)$str;
10370 37
    if ('' === $str) {
10371 6
      return $str;
10372
    }
10373
10374 37
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
10375
      self::checkForSupport();
10376
    }
10377
10378 37
    $max = self::strlen_in_byte($str);
10379 37
    $buf = '';
10380
10381
    /** @noinspection ForeachInvariantsInspection */
10382 37
    for ($i = 0; $i < $max; $i++) {
10383 37
      $c1 = $str[$i];
10384
10385 37
      if ($c1 >= "\xC0") { // should be converted to UTF8, if it's not UTF8 already
10386
10387 34
        if ($c1 <= "\xDF") { // looks like 2 bytes UTF8
10388
10389 31
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10390
10391 31
          if ($c2 >= "\x80" && $c2 <= "\xBF") { // yeah, almost sure it's UTF8 already
10392 17
            $buf .= $c1 . $c2;
10393 17
            $i++;
10394
          } else { // not valid UTF8 - convert it
10395 31
            $buf .= self::to_utf8_convert_helper($c1);
10396
          }
10397
10398 34
        } elseif ($c1 >= "\xE0" && $c1 <= "\xEF") { // looks like 3 bytes UTF8
10399
10400 32
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10401 32
          $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
10402
10403 32
          if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF") { // yeah, almost sure it's UTF8 already
10404 14
            $buf .= $c1 . $c2 . $c3;
10405 14
            $i += 2;
10406
          } else { // not valid UTF8 - convert it
10407 32
            $buf .= self::to_utf8_convert_helper($c1);
10408
          }
10409
10410 26
        } elseif ($c1 >= "\xF0" && $c1 <= "\xF7") { // looks like 4 bytes UTF8
10411
10412 26
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10413 26
          $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
10414 26
          $c4 = $i + 3 >= $max ? "\x00" : $str[$i + 3];
10415
10416 26
          if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF" && $c4 >= "\x80" && $c4 <= "\xBF") { // yeah, almost sure it's UTF8 already
10417 8
            $buf .= $c1 . $c2 . $c3 . $c4;
10418 8
            $i += 3;
10419
          } else { // not valid UTF8 - convert it
10420 26
            $buf .= self::to_utf8_convert_helper($c1);
10421
          }
10422
10423
        } else { // doesn't look like UTF8, but should be converted
10424 34
          $buf .= self::to_utf8_convert_helper($c1);
10425
        }
10426
10427 34
      } elseif (($c1 & "\xC0") === "\x80") { // needs conversion
10428
10429 4
        $buf .= self::to_utf8_convert_helper($c1);
10430
10431
      } else { // it doesn't need conversion
10432 34
        $buf .= $c1;
10433
      }
10434
    }
10435
10436
    // decode unicode escape sequences
10437 37
    $buf = \preg_replace_callback(
10438 37
        '/\\\\u([0-9a-f]{4})/i',
10439
        function ($match) {
10440
          // always fallback via symfony polyfill
10441 8
          return \mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
10442 37
        },
10443 37
        $buf
10444
    );
10445
10446
    // decode UTF-8 codepoints
10447 37
    if ($decodeHtmlEntityToUtf8 === true) {
10448 2
      $buf = self::html_entity_decode($buf);
10449
    }
10450
10451 37
    return $buf;
10452
  }
10453
10454
  /**
10455
   * @param int|string $input
10456
   *
10457
   * @return string
10458
   */
10459 30
  private static function to_utf8_convert_helper($input): string
10460
  {
10461
    // init
10462 30
    $buf = '';
10463
10464 30
    if (self::$ORD === null) {
10465 1
      self::$ORD = self::getData('ord');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('ord') can also be of type false. However, the property $ORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10466
    }
10467
10468 30
    if (self::$CHR === null) {
10469 1
      self::$CHR = self::getData('chr');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('chr') can also be of type false. However, the property $CHR is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10470
    }
10471
10472 30
    if (self::$WIN1252_TO_UTF8 === null) {
10473 1
      self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('win1252_to_utf8') can also be of type false. However, the property $WIN1252_TO_UTF8 is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10474
    }
10475
10476 30
    $ordC1 = self::$ORD[$input];
10477 30
    if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases
10478 30
      $buf .= self::$WIN1252_TO_UTF8[$ordC1];
10479
    } else {
10480 2
      $cc1 = self::$CHR[$ordC1 / 64] | "\xC0";
10481 2
      $cc2 = ((string)$input & "\x3F") | "\x80";
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise & or did you mean &&?
Loading history...
Bug introduced by
Are you sure you want to use the bitwise | or did you mean ||?
Loading history...
10482 2
      $buf .= $cc1 . $cc2;
10483
    }
10484
10485 30
    return $buf;
10486
  }
10487
10488
  /**
10489
   * Strip whitespace or other characters from beginning or end of a UTF-8 string.
10490
   *
10491
   * INFO: This is slower then "trim()"
10492
   *
10493
   * We can only use the original-function, if we use <= 7-Bit in the string / chars
10494
   * but the check for ACSII (7-Bit) cost more time, then we can safe here.
10495
   *
10496
   * @param string $str   <p>The string to be trimmed</p>
10497
   * @param mixed  $chars [optional] <p>Optional characters to be stripped</p>
10498
   *
10499
   * @return string The trimmed string.
10500
   */
10501 214
  public static function trim(string $str = '', $chars = INF): string
10502
  {
10503 214
    if ('' === $str) {
10504 11
      return '';
10505
    }
10506
10507
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
10508 206
    if ($chars === INF || !$chars) {
10509 179
      $pattern = "^[\pZ\pC]+|[\pZ\pC]+\$";
10510
    } else {
10511 47
      $chars = \preg_quote($chars, '/');
10512 47
      $pattern = "^[$chars]+|[$chars]+\$";
10513
    }
10514
10515 206
    return self::regex_replace($str, $pattern, '', '', '/');
10516
  }
10517
10518
  /**
10519
   * Makes string's first char uppercase.
10520
   *
10521
   * @param string      $str                   <p>The input string.</p>
10522
   * @param string      $encoding              [optional] <p>Set the charset for e.g. "mb_" function</p>
10523
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
10524
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
10525
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
10526
   *
10527
   * @return string The resulting string.
10528
   */
10529 81
  public static function ucfirst(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
10530
  {
10531 81
    if ($cleanUtf8 === true) {
10532
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10533
      // if invalid characters are found in $haystack before $needle
10534 1
      $str = self::clean($str);
10535
    }
10536
10537 81
    $strPartTwo = self::substr($str, 1, null, $encoding);
10538 81
    if ($strPartTwo === false) {
10539
      $strPartTwo = '';
10540
    }
10541
10542 81
    $strPartOne = self::strtoupper(
10543 81
        (string)self::substr($str, 0, 1, $encoding),
10544 81
        $encoding,
10545 81
        $cleanUtf8,
10546 81
        $lang,
10547 81
        $tryToKeepStringLength
10548
    );
10549
10550 81
    return $strPartOne . $strPartTwo;
10551
  }
10552
10553
  /**
10554
   * alias for "UTF8::ucfirst()"
10555
   *
10556
   * @see UTF8::ucfirst()
10557
   *
10558
   * @param string $str
10559
   * @param string $encoding
10560
   * @param bool   $cleanUtf8
10561
   *
10562
   * @return string
10563
   */
10564 1
  public static function ucword(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
10565
  {
10566 1
    return self::ucfirst($str, $encoding, $cleanUtf8);
10567
  }
10568
10569
  /**
10570
   * Uppercase for all words in the string.
10571
   *
10572
   * @param string   $str        <p>The input string.</p>
10573
   * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
10574
   * @param string   $charlist   [optional] <p>Additional chars that contains to words and do not start a new word.</p>
10575
   * @param string   $encoding   [optional] <p>Set the charset.</p>
10576
   * @param bool     $cleanUtf8  [optional] <p>Remove non UTF-8 chars from the string.</p>
10577
   *
10578
   * @return string
10579
   */
10580 9
  public static function ucwords(string $str, array $exceptions = [], string $charlist = '', string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
10581
  {
10582 9
    if (!$str) {
10583 2
      return '';
10584
    }
10585
10586
    // INFO: mb_convert_case($str, MB_CASE_TITLE);
10587
    // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters
10588
10589 8
    if ($cleanUtf8 === true) {
10590
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10591
      // if invalid characters are found in $haystack before $needle
10592 1
      $str = self::clean($str);
10593
    }
10594
10595 8
    $usePhpDefaultFunctions = !(bool)($charlist . \implode('', $exceptions));
10596
10597
    if (
10598 8
        $usePhpDefaultFunctions === true
10599
        &&
10600 8
        self::is_ascii($str) === true
10601
    ) {
10602
      return \ucwords($str);
10603
    }
10604
10605 8
    $words = self::str_to_words($str, $charlist);
10606 8
    $newWords = [];
10607
10608 8
    if (\count($exceptions) > 0) {
10609 1
      $useExceptions = true;
10610
    } else {
10611 8
      $useExceptions = false;
10612
    }
10613
10614 8
    foreach ($words as $word) {
10615
10616 8
      if (!$word) {
10617 8
        continue;
10618
      }
10619
10620
      if (
10621 8
          $useExceptions === false
10622
          ||
10623
          (
10624 1
              $useExceptions === true
10625
              &&
10626 8
              !\in_array($word, $exceptions, true)
10627
          )
10628
      ) {
10629 8
        $word = self::ucfirst($word, $encoding);
10630
      }
10631
10632 8
      $newWords[] = $word;
10633
    }
10634
10635 8
    return \implode('', $newWords);
10636
  }
10637
10638
  /**
10639
   * Multi decode html entity & fix urlencoded-win1252-chars.
10640
   *
10641
   * e.g:
10642
   * 'test+test'                     => 'test test'
10643
   * 'D&#252;sseldorf'               => 'Düsseldorf'
10644
   * 'D%FCsseldorf'                  => 'Düsseldorf'
10645
   * 'D&#xFC;sseldorf'               => 'Düsseldorf'
10646
   * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
10647
   * 'Düsseldorf'                   => 'Düsseldorf'
10648
   * 'D%C3%BCsseldorf'               => 'Düsseldorf'
10649
   * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
10650
   * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
10651
   *
10652
   * @param string $str          <p>The input string.</p>
10653
   * @param bool   $multi_decode <p>Decode as often as possible.</p>
10654
   *
10655
   * @return string
10656
   */
10657 2
  public static function urldecode(string $str, bool $multi_decode = true): string
10658
  {
10659 2
    if ('' === $str) {
10660 2
      return '';
10661
    }
10662
10663 2
    $pattern = '/%u([0-9a-f]{3,4})/i';
10664 2
    if (\preg_match($pattern, $str)) {
10665 2
      $str = (string)\preg_replace($pattern, '&#x\\1;', \urldecode($str));
10666
    }
10667
10668 2
    $flags = ENT_QUOTES | ENT_HTML5;
10669
10670
    do {
10671 2
      $str_compare = $str;
10672
10673 2
      $str = self::fix_simple_utf8(
10674 2
          \urldecode(
10675 2
              self::html_entity_decode(
10676 2
                  self::to_utf8($str),
10677 2
                  $flags
10678
              )
10679
          )
10680
      );
10681
10682 2
    } while ($multi_decode === true && $str_compare !== $str);
10683
10684 2
    return $str;
10685
  }
10686
10687
  /**
10688
   * Return a array with "urlencoded"-win1252 -> UTF-8
10689
   *
10690
   * @deprecated <p>use the "UTF8::urldecode()" function to decode a string</p>
10691
   *
10692
   * @return string[]
10693
   */
10694 2
  public static function urldecode_fix_win1252_chars(): array
10695
  {
10696
    return [
10697 2
        '%20' => ' ',
10698
        '%21' => '!',
10699
        '%22' => '"',
10700
        '%23' => '#',
10701
        '%24' => '$',
10702
        '%25' => '%',
10703
        '%26' => '&',
10704
        '%27' => "'",
10705
        '%28' => '(',
10706
        '%29' => ')',
10707
        '%2A' => '*',
10708
        '%2B' => '+',
10709
        '%2C' => ',',
10710
        '%2D' => '-',
10711
        '%2E' => '.',
10712
        '%2F' => '/',
10713
        '%30' => '0',
10714
        '%31' => '1',
10715
        '%32' => '2',
10716
        '%33' => '3',
10717
        '%34' => '4',
10718
        '%35' => '5',
10719
        '%36' => '6',
10720
        '%37' => '7',
10721
        '%38' => '8',
10722
        '%39' => '9',
10723
        '%3A' => ':',
10724
        '%3B' => ';',
10725
        '%3C' => '<',
10726
        '%3D' => '=',
10727
        '%3E' => '>',
10728
        '%3F' => '?',
10729
        '%40' => '@',
10730
        '%41' => 'A',
10731
        '%42' => 'B',
10732
        '%43' => 'C',
10733
        '%44' => 'D',
10734
        '%45' => 'E',
10735
        '%46' => 'F',
10736
        '%47' => 'G',
10737
        '%48' => 'H',
10738
        '%49' => 'I',
10739
        '%4A' => 'J',
10740
        '%4B' => 'K',
10741
        '%4C' => 'L',
10742
        '%4D' => 'M',
10743
        '%4E' => 'N',
10744
        '%4F' => 'O',
10745
        '%50' => 'P',
10746
        '%51' => 'Q',
10747
        '%52' => 'R',
10748
        '%53' => 'S',
10749
        '%54' => 'T',
10750
        '%55' => 'U',
10751
        '%56' => 'V',
10752
        '%57' => 'W',
10753
        '%58' => 'X',
10754
        '%59' => 'Y',
10755
        '%5A' => 'Z',
10756
        '%5B' => '[',
10757
        '%5C' => '\\',
10758
        '%5D' => ']',
10759
        '%5E' => '^',
10760
        '%5F' => '_',
10761
        '%60' => '`',
10762
        '%61' => 'a',
10763
        '%62' => 'b',
10764
        '%63' => 'c',
10765
        '%64' => 'd',
10766
        '%65' => 'e',
10767
        '%66' => 'f',
10768
        '%67' => 'g',
10769
        '%68' => 'h',
10770
        '%69' => 'i',
10771
        '%6A' => 'j',
10772
        '%6B' => 'k',
10773
        '%6C' => 'l',
10774
        '%6D' => 'm',
10775
        '%6E' => 'n',
10776
        '%6F' => 'o',
10777
        '%70' => 'p',
10778
        '%71' => 'q',
10779
        '%72' => 'r',
10780
        '%73' => 's',
10781
        '%74' => 't',
10782
        '%75' => 'u',
10783
        '%76' => 'v',
10784
        '%77' => 'w',
10785
        '%78' => 'x',
10786
        '%79' => 'y',
10787
        '%7A' => 'z',
10788
        '%7B' => '{',
10789
        '%7C' => '|',
10790
        '%7D' => '}',
10791
        '%7E' => '~',
10792
        '%7F' => '',
10793
        '%80' => '`',
10794
        '%81' => '',
10795
        '%82' => '‚',
10796
        '%83' => 'ƒ',
10797
        '%84' => '„',
10798
        '%85' => '…',
10799
        '%86' => '†',
10800
        '%87' => '‡',
10801
        '%88' => 'ˆ',
10802
        '%89' => '‰',
10803
        '%8A' => 'Š',
10804
        '%8B' => '‹',
10805
        '%8C' => 'Œ',
10806
        '%8D' => '',
10807
        '%8E' => 'Ž',
10808
        '%8F' => '',
10809
        '%90' => '',
10810
        '%91' => '‘',
10811
        '%92' => '’',
10812
        '%93' => '“',
10813
        '%94' => '”',
10814
        '%95' => '•',
10815
        '%96' => '–',
10816
        '%97' => '—',
10817
        '%98' => '˜',
10818
        '%99' => '™',
10819
        '%9A' => 'š',
10820
        '%9B' => '›',
10821
        '%9C' => 'œ',
10822
        '%9D' => '',
10823
        '%9E' => 'ž',
10824
        '%9F' => 'Ÿ',
10825
        '%A0' => '',
10826
        '%A1' => '¡',
10827
        '%A2' => '¢',
10828
        '%A3' => '£',
10829
        '%A4' => '¤',
10830
        '%A5' => '¥',
10831
        '%A6' => '¦',
10832
        '%A7' => '§',
10833
        '%A8' => '¨',
10834
        '%A9' => '©',
10835
        '%AA' => 'ª',
10836
        '%AB' => '«',
10837
        '%AC' => '¬',
10838
        '%AD' => '',
10839
        '%AE' => '®',
10840
        '%AF' => '¯',
10841
        '%B0' => '°',
10842
        '%B1' => '±',
10843
        '%B2' => '²',
10844
        '%B3' => '³',
10845
        '%B4' => '´',
10846
        '%B5' => 'µ',
10847
        '%B6' => '¶',
10848
        '%B7' => '·',
10849
        '%B8' => '¸',
10850
        '%B9' => '¹',
10851
        '%BA' => 'º',
10852
        '%BB' => '»',
10853
        '%BC' => '¼',
10854
        '%BD' => '½',
10855
        '%BE' => '¾',
10856
        '%BF' => '¿',
10857
        '%C0' => 'À',
10858
        '%C1' => 'Á',
10859
        '%C2' => 'Â',
10860
        '%C3' => 'Ã',
10861
        '%C4' => 'Ä',
10862
        '%C5' => 'Å',
10863
        '%C6' => 'Æ',
10864
        '%C7' => 'Ç',
10865
        '%C8' => 'È',
10866
        '%C9' => 'É',
10867
        '%CA' => 'Ê',
10868
        '%CB' => 'Ë',
10869
        '%CC' => 'Ì',
10870
        '%CD' => 'Í',
10871
        '%CE' => 'Î',
10872
        '%CF' => 'Ï',
10873
        '%D0' => 'Ð',
10874
        '%D1' => 'Ñ',
10875
        '%D2' => 'Ò',
10876
        '%D3' => 'Ó',
10877
        '%D4' => 'Ô',
10878
        '%D5' => 'Õ',
10879
        '%D6' => 'Ö',
10880
        '%D7' => '×',
10881
        '%D8' => 'Ø',
10882
        '%D9' => 'Ù',
10883
        '%DA' => 'Ú',
10884
        '%DB' => 'Û',
10885
        '%DC' => 'Ü',
10886
        '%DD' => 'Ý',
10887
        '%DE' => 'Þ',
10888
        '%DF' => 'ß',
10889
        '%E0' => 'à',
10890
        '%E1' => 'á',
10891
        '%E2' => 'â',
10892
        '%E3' => 'ã',
10893
        '%E4' => 'ä',
10894
        '%E5' => 'å',
10895
        '%E6' => 'æ',
10896
        '%E7' => 'ç',
10897
        '%E8' => 'è',
10898
        '%E9' => 'é',
10899
        '%EA' => 'ê',
10900
        '%EB' => 'ë',
10901
        '%EC' => 'ì',
10902
        '%ED' => 'í',
10903
        '%EE' => 'î',
10904
        '%EF' => 'ï',
10905
        '%F0' => 'ð',
10906
        '%F1' => 'ñ',
10907
        '%F2' => 'ò',
10908
        '%F3' => 'ó',
10909
        '%F4' => 'ô',
10910
        '%F5' => 'õ',
10911
        '%F6' => 'ö',
10912
        '%F7' => '÷',
10913
        '%F8' => 'ø',
10914
        '%F9' => 'ù',
10915
        '%FA' => 'ú',
10916
        '%FB' => 'û',
10917
        '%FC' => 'ü',
10918
        '%FD' => 'ý',
10919
        '%FE' => 'þ',
10920
        '%FF' => 'ÿ',
10921
    ];
10922
  }
10923
10924
  /**
10925
   * Decodes an UTF-8 string to ISO-8859-1.
10926
   *
10927
   * @param string $str <p>The input string.</p>
10928
   * @param bool   $keepUtf8Chars
10929
   *
10930
   * @return string
10931
   */
10932 13
  public static function utf8_decode(string $str, bool $keepUtf8Chars = false): string
10933
  {
10934 13
    if ('' === $str) {
10935 5
      return '';
10936
    }
10937
10938 13
    static $UTF8_TO_WIN1252_KEYS_CACHE = null;
10939 13
    static $UTF8_TO_WIN1252_VALUES_CACHE = null;
10940
10941 13
    if ($UTF8_TO_WIN1252_KEYS_CACHE === null) {
10942
10943 1
      if (self::$WIN1252_TO_UTF8 === null) {
10944
        self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('win1252_to_utf8') can also be of type false. However, the property $WIN1252_TO_UTF8 is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10945
      }
10946
10947 1
      $UTF8_TO_WIN1252_KEYS_CACHE = \array_keys(self::$WIN1252_TO_UTF8);
0 ignored issues
show
Bug introduced by
It seems like self::WIN1252_TO_UTF8 can also be of type false; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

10947
      $UTF8_TO_WIN1252_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10948 1
      $UTF8_TO_WIN1252_VALUES_CACHE = \array_values(self::$WIN1252_TO_UTF8);
0 ignored issues
show
Bug introduced by
It seems like self::WIN1252_TO_UTF8 can also be of type false; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

10948
      $UTF8_TO_WIN1252_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10949
    }
10950
10951
    /** @noinspection PhpInternalEntityUsedInspection */
10952 13
    $str = \str_replace($UTF8_TO_WIN1252_KEYS_CACHE, $UTF8_TO_WIN1252_VALUES_CACHE, $str);
10953
10954 13
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
10955
      self::checkForSupport();
10956
    }
10957
10958
    // save for later comparision
10959 13
    $str_backup = $str;
10960 13
    $len = self::strlen_in_byte($str);
10961
10962 13
    if (self::$ORD === null) {
10963
      self::$ORD = self::getData('ord');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('ord') can also be of type false. However, the property $ORD is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10964
    }
10965
10966 13
    if (self::$CHR === null) {
10967
      self::$CHR = self::getData('chr');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('chr') can also be of type false. However, the property $CHR is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
10968
    }
10969
10970 13
    $noCharFound = '?';
10971
    /** @noinspection ForeachInvariantsInspection */
10972 13
    for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
10973 13
      switch ($str[$i] & "\xF0") {
10974 13
        case "\xC0":
10975 12
        case "\xD0":
10976 13
          $c = (self::$ORD[$str[$i] & "\x1F"] << 6) | self::$ORD[$str[++$i] & "\x3F"];
10977 13
          $str[$j] = $c < 256 ? self::$CHR[$c] : $noCharFound;
10978 13
          break;
10979
10980
        /** @noinspection PhpMissingBreakStatementInspection */
10981 12
        case "\xF0":
10982
          ++$i;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
10983 12
        case "\xE0":
10984 10
          $str[$j] = $noCharFound;
10985 10
          $i += 2;
10986 10
          break;
10987
10988
        default:
10989 12
          $str[$j] = $str[$i];
10990
      }
10991
    }
10992
10993 13
    $return = self::substr_in_byte($str, 0, $j);
10994 13
    if ($return === false) {
0 ignored issues
show
introduced by
The condition $return === false is always false.
Loading history...
10995
      $return = '';
10996
    }
10997
10998
    if (
10999 13
        $keepUtf8Chars === true
11000
        &&
11001 13
        self::strlen($return) >= self::strlen($str_backup)
11002
    ) {
11003 2
      return $str_backup;
11004
    }
11005
11006 13
    return $return;
11007
  }
11008
11009
  /**
11010
   * Encodes an ISO-8859-1 string to UTF-8.
11011
   *
11012
   * @param string $str <p>The input string.</p>
11013
   *
11014
   * @return string
11015
   */
11016 14
  public static function utf8_encode(string $str): string
11017
  {
11018 14
    if ('' === $str) {
11019 13
      return '';
11020
    }
11021
11022 14
    $str = \utf8_encode($str);
11023
11024
    // the polyfill maybe return false
11025
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
11026 14
    if ($str === false) {
11027
      return '';
11028
    }
11029
11030 14
    if (false === \strpos($str, "\xC2")) {
11031 6
      return $str;
11032
    }
11033
11034 12
    static $WIN1252_TO_UTF8_KEYS_CACHE = null;
11035 12
    static $WIN1252_TO_UTF8_VALUES_CACHE = null;
11036
11037 12
    if ($WIN1252_TO_UTF8_KEYS_CACHE === null) {
11038
11039 1
      if (self::$WIN1252_TO_UTF8 === null) {
11040
        self::$WIN1252_TO_UTF8 = self::getData('win1252_to_utf8');
0 ignored issues
show
Documentation Bug introduced by
It seems like self::getData('win1252_to_utf8') can also be of type false. However, the property $WIN1252_TO_UTF8 is declared as type array|null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
11041
      }
11042
11043 1
      $WIN1252_TO_UTF8_KEYS_CACHE = \array_keys(self::$WIN1252_TO_UTF8);
0 ignored issues
show
Bug introduced by
It seems like self::WIN1252_TO_UTF8 can also be of type false; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

11043
      $WIN1252_TO_UTF8_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
11044 1
      $WIN1252_TO_UTF8_VALUES_CACHE = \array_values(self::$WIN1252_TO_UTF8);
0 ignored issues
show
Bug introduced by
It seems like self::WIN1252_TO_UTF8 can also be of type false; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

11044
      $WIN1252_TO_UTF8_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
11045
    }
11046
11047 12
    return \str_replace($WIN1252_TO_UTF8_KEYS_CACHE, $WIN1252_TO_UTF8_VALUES_CACHE, $str);
11048
  }
11049
11050
  /**
11051
   * fix -> utf8-win1252 chars
11052
   *
11053
   * @param string $str <p>The input string.</p>
11054
   *
11055
   * @return string
11056
   *
11057
   * @deprecated <p>use "UTF8::fix_simple_utf8()"</p>
11058
   */
11059 2
  public static function utf8_fix_win1252_chars(string $str): string
11060
  {
11061 2
    return self::fix_simple_utf8($str);
11062
  }
11063
11064
  /**
11065
   * Returns an array with all utf8 whitespace characters.
11066
   *
11067
   * @see   : http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html
11068
   *
11069
   * @author: Derek E. [email protected]
11070
   *
11071
   * @return string[]
11072
   *                 An array with all known whitespace characters as values and the type of whitespace as keys
11073
   *                 as defined in above URL.
11074
   */
11075 2
  public static function whitespace_table(): array
11076
  {
11077 2
    return self::$WHITESPACE_TABLE;
11078
  }
11079
11080
  /**
11081
   * Limit the number of words in a string.
11082
   *
11083
   * @param string $str      <p>The input string.</p>
11084
   * @param int    $limit    <p>The limit of words as integer.</p>
11085
   * @param string $strAddOn <p>Replacement for the striped string.</p>
11086
   *
11087
   * @return string
11088
   */
11089 2
  public static function words_limit(string $str, int $limit = 100, string $strAddOn = '…'): string
11090
  {
11091 2
    if ('' === $str) {
11092 2
      return '';
11093
    }
11094
11095 2
    if ($limit < 1) {
11096 2
      return '';
11097
    }
11098
11099 2
    \preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/u', $str, $matches);
11100
11101
    if (
11102 2
        !isset($matches[0])
11103
        ||
11104 2
        self::strlen($str) === self::strlen($matches[0])
11105
    ) {
11106 2
      return $str;
11107
    }
11108
11109 2
    return self::rtrim($matches[0]) . $strAddOn;
11110
  }
11111
11112
  /**
11113
   * Wraps a string to a given number of characters
11114
   *
11115
   * @link  http://php.net/manual/en/function.wordwrap.php
11116
   *
11117
   * @param string $str   <p>The input string.</p>
11118
   * @param int    $width [optional] <p>The column width.</p>
11119
   * @param string $break [optional] <p>The line is broken using the optional break parameter.</p>
11120
   * @param bool   $cut   [optional] <p>
11121
   *                      If the cut is set to true, the string is
11122
   *                      always wrapped at or before the specified width. So if you have
11123
   *                      a word that is larger than the given width, it is broken apart.
11124
   *                      </p>
11125
   *
11126
   * @return string The given string wrapped at the specified column.
11127
   */
11128 10
  public static function wordwrap(string $str, int $width = 75, string $break = "\n", bool $cut = false): string
11129
  {
11130 10
    if ('' === $str || '' === $break) {
11131 3
      return '';
11132
    }
11133
11134 8
    $w = '';
11135 8
    $strSplit = \explode($break, $str);
11136 8
    if ($strSplit === false) {
11137
      $count = 0;
11138
    } else {
11139 8
      $count = \count($strSplit);
11140
    }
11141
11142 8
    $chars = [];
11143
    /** @noinspection ForeachInvariantsInspection */
11144 8
    for ($i = 0; $i < $count; ++$i) {
11145
11146 8
      if ($i) {
11147 1
        $chars[] = $break;
11148 1
        $w .= '#';
11149
      }
11150
11151 8
      $c = $strSplit[$i];
11152 8
      unset($strSplit[$i]);
11153
11154 8
      if ($c !== null) {
11155 8
        foreach (self::split($c) as $c) {
11156 8
          $chars[] = $c;
11157 8
          $w .= ' ' === $c ? ' ' : '?';
11158
        }
11159
      }
11160
    }
11161
11162 8
    $strReturn = '';
11163 8
    $j = 0;
11164 8
    $b = $i = -1;
11165 8
    $w = \wordwrap($w, $width, '#', $cut);
11166
11167 8
    while (false !== $b = self::strpos($w, '#', $b + 1)) {
11168 6
      for (++$i; $i < $b; ++$i) {
11169 6
        $strReturn .= $chars[$j];
11170 6
        unset($chars[$j++]);
11171
      }
11172
11173 6
      if ($break === $chars[$j] || ' ' === $chars[$j]) {
11174 3
        unset($chars[$j++]);
11175
      }
11176
11177 6
      $strReturn .= $break;
11178
    }
11179
11180 8
    return $strReturn . \implode('', $chars);
11181
  }
11182
11183
  /**
11184
   * Line-Wrap the string after $limit, but also after the next word.
11185
   *
11186
   * @param string $str
11187
   * @param int    $limit
11188
   *
11189
   * @return string
11190
   */
11191 1
  public static function wordwrap_per_line(string $str, int $limit): string
11192
  {
11193 1
    $strings = (array)\preg_split('/\\r\\n|\\r|\\n/', $str);
11194
11195 1
    $string = '';
11196 1
    foreach ($strings as $value) {
11197 1
      if ($value === false) {
11198
        continue;
11199
      }
11200
11201 1
      $string .= wordwrap($value, $limit);
11202 1
      $string .= "\n";
11203
    }
11204
11205 1
    return $string;
11206
  }
11207
11208
  /**
11209
   * Returns an array of Unicode White Space characters.
11210
   *
11211
   * @return string[] An array with numeric code point as key and White Space Character as value.
11212
   */
11213 2
  public static function ws(): array
11214
  {
11215 2
    return self::$WHITESPACE;
11216
  }
11217
11218
11219
}
11220