Passed
Push — master ( 8d4043...d83c95 )
by Lars
03:07
created

UTF8::is_bom()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 3
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 16
  public static function chr($code_point, string $encoding = 'UTF-8')
513
  {
514
    // init
515 16
    static $CHAR_CACHE = [];
516
517 16
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
518
      self::checkForSupport();
519
    }
520
521 16
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
522 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
523
    }
524
525
    if (
526 16
        $encoding !== 'UTF-8'
527
        &&
528 16
        $encoding !== 'ISO-8859-1'
529
        &&
530 16
        $encoding !== 'WINDOWS-1252'
531
        &&
532 16
        self::$SUPPORT['mbstring'] === false
533
    ) {
534
      \trigger_error('UTF8::chr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
535
    }
536
537 16
    $cacheKey = $code_point . $encoding;
538 16
    if (isset($CHAR_CACHE[$cacheKey]) === true) {
539 15
      return $CHAR_CACHE[$cacheKey];
540
    }
541
542 10
    if ($code_point <= 127) { // use "simple"-char only until "\x80"
543
544 9
      if (self::$CHR === null) {
545
        $chrTmp = self::getData('chr');
546
        if ($chrTmp) {
547
          self::$CHR = (array)$chrTmp;
548
        }
549
      }
550
551 9
      $chr = self::$CHR[$code_point];
552
553 9
      if ($encoding !== 'UTF-8') {
554 1
        $chr = self::encode($encoding, $chr);
555
      }
556
557 9
      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 4
      return \array_map(
643 4
          function ($data) {
644 4
            return UTF8::strlen_in_byte($data);
645 4
          },
646 4
          $strSplit
647
      );
648
    }
649
650
    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 111
  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 111
    $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 111
    $str = (string)\preg_replace($regx, '$1', $str);
786
787 111
    if ($replace_diamond_question_mark === true) {
788 61
      $str = self::replace_diamond_question_mark($str, '');
789
    }
790
791 111
    if ($remove_invisible_characters === true) {
792 111
      $str = self::remove_invisible_characters($str);
793
    }
794
795 111
    if ($normalize_whitespace === true) {
796 65
      $str = self::normalize_whitespace($str, $keep_non_breaking_space);
797
    }
798
799 111
    if ($normalize_msword === true) {
800 33
      $str = self::normalize_msword($str);
801
    }
802
803 111
    if ($remove_bom === true) {
804 63
      $str = self::remove_bom($str);
805
    }
806
807 111
    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 30
  public static function encode(string $toEncoding, string $str, bool $autodetectFromEncoding = true, string $fromEncoding = ''): string
1009
  {
1010 30
    if ('' === $str || '' === $toEncoding) {
1011 12
      return $str;
1012
    }
1013
1014 30
    if ($toEncoding !== 'UTF-8' && $toEncoding !== 'CP850') {
1015 8
      $toEncoding = self::normalize_encoding($toEncoding, 'UTF-8');
1016
    }
1017
1018 30
    if ($fromEncoding && $fromEncoding !== 'UTF-8' && $fromEncoding !== 'CP850') {
1019 2
      $fromEncoding = self::normalize_encoding($fromEncoding, null);
1020
    }
1021
1022 30
    if ($toEncoding && $fromEncoding && $fromEncoding === $toEncoding) {
1023
      return $str;
1024
    }
1025
1026 30
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1027
      self::checkForSupport();
1028
    }
1029
1030 30
    if ($fromEncoding === 'BASE64') {
1031 2
      $str = base64_decode($str);
1032 2
      $fromEncoding = null;
1033
    }
1034
1035 30
    if ($toEncoding === 'BASE64') {
1036 2
      return base64_encode($str);
1037
    }
1038
1039 30
    if ($toEncoding === 'HTML-ENTITIES') {
1040
1041 2
      if ($fromEncoding === 'HTML-ENTITIES') {
1042
        $fromEncoding = 'UTF-8';
1043
      }
1044
1045 2
      if ($fromEncoding !== 'UTF-8') {
1046 2
        $str = self::encode('UTF-8', $str, false, $fromEncoding);
1047
      }
1048
1049 2
      return self::html_encode($str, true, 'UTF-8');
1050
    }
1051
1052 30
    if ($fromEncoding === 'HTML-ENTITIES') {
1053 2
      $str = self::html_entity_decode($str, ENT_COMPAT, 'UTF-8');
1054 2
      $fromEncoding = 'UTF-8';
1055
    }
1056
1057 30
    $fromEncodingDetected = false;
1058
    if (
1059 30
        $autodetectFromEncoding === true
1060
        ||
1061 30
        !$fromEncoding
1062
    ) {
1063 30
      $fromEncodingDetected = self::str_detect_encoding($str);
1064
    }
1065
1066
    // DEBUG
1067
    //var_dump($toEncoding, $fromEncoding, $fromEncodingDetected, $str, "\n\n");
1068
1069 30
    if ($fromEncodingDetected !== false) {
1070 25
      $fromEncoding = $fromEncodingDetected;
1071 9
    } elseif ($fromEncodingDetected === false && $autodetectFromEncoding === true) {
1072
      // fallback for the "autodetect"-mode
1073 7
      return self::to_utf8($str);
1074
    }
1075
1076
    if (
1077 25
        !$fromEncoding
1078
        ||
1079 25
        $fromEncoding === $toEncoding
1080
    ) {
1081 15
      return $str;
1082
    }
1083
1084
    if (
1085 19
        $toEncoding === 'UTF-8'
1086
        &&
1087
        (
1088 17
            $fromEncoding === 'WINDOWS-1252'
1089
            ||
1090 19
            $fromEncoding === 'ISO-8859-1'
1091
        )
1092
    ) {
1093 14
      return self::to_utf8($str);
1094
    }
1095
1096
    if (
1097 11
        $toEncoding === 'ISO-8859-1'
1098
        &&
1099
        (
1100 6
            $fromEncoding === 'WINDOWS-1252'
1101
            ||
1102 11
            $fromEncoding === 'UTF-8'
1103
        )
1104
    ) {
1105 6
      return self::to_iso8859($str);
1106
    }
1107
1108
    if (
1109 9
        $toEncoding !== 'UTF-8'
1110
        &&
1111 9
        $toEncoding !== 'ISO-8859-1'
1112
        &&
1113 9
        $toEncoding !== 'WINDOWS-1252'
1114
        &&
1115 9
        self::$SUPPORT['mbstring'] === false
1116
    ) {
1117
      \trigger_error('UTF8::encode() without mbstring cannot handle "' . $toEncoding . '" encoding', E_USER_WARNING);
1118
    }
1119
1120 9
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1121
      self::checkForSupport();
1122
    }
1123
1124 9
    if (self::$SUPPORT['mbstring'] === true) {
1125
      // info: do not use the symfony polyfill here
1126 9
      $strEncoded = \mb_convert_encoding(
1127 9
          $str,
1128 9
          $toEncoding,
1129 9
          ($autodetectFromEncoding === true ? $toEncoding : $fromEncoding)
1130
      );
1131
1132 9
      if ($strEncoded) {
1133 9
        return $strEncoded;
1134
      }
1135
    }
1136
1137
    $return = \iconv($fromEncoding, $toEncoding . '//IGNORE', $str);
1138
    if ($return !== false) {
1139
      return $return;
1140
    }
1141
1142
    return $str;
1143
  }
1144
1145
  /**
1146
   * @param string $str
1147
   * @param string $fromCharset      [optional] <p>Set the input charset.</p>
1148
   * @param string $toCharset        [optional] <p>Set the output charset.</p>
1149
   * @param string $transferEncoding [optional] <p>Set the transfer encoding.</p>
1150
   * @param string $linefeed         [optional] <p>Set the used linefeed.</p>
1151
   * @param int    $indent           [optional] <p>Set the max length indent.</p>
1152
   *
1153
   * @return string|false
1154
   *                      An encoded MIME field on success,
1155
   *                      or false if an error occurs during the encoding.
1156
   */
1157
  public static function encode_mimeheader(
1158
      $str,
1159
      $fromCharset = 'UTF-8',
1160
      $toCharset = 'UTF-8',
1161
      $transferEncoding = 'Q',
1162
      $linefeed = "\r\n",
1163
      $indent = 76
1164
  )
1165
  {
1166
    if ($fromCharset !== 'UTF-8' && $fromCharset !== 'CP850') {
1167
      $fromCharset = self::normalize_encoding($fromCharset, 'UTF-8');
1168
    }
1169
1170
    if ($toCharset !== 'UTF-8' && $toCharset !== 'CP850') {
1171
      $toCharset = self::normalize_encoding($toCharset, 'UTF-8');
1172
    }
1173
1174
    $output = \iconv_mime_encode(
1175
        '',
1176
        $str,
1177
        [
1178
            'scheme'           => $transferEncoding,
1179
            'line-length'      => $indent,
1180
            'input-charset'    => $fromCharset,
1181
            'output-charset'   => $toCharset,
1182
            'line-break-chars' => $linefeed,
1183
        ]
1184
    );
1185
1186
    return $output;
1187
  }
1188
1189
  /**
1190
   * Create an extract from a sentence, so if the search-string was found, it try to centered in the output.
1191
   *
1192
   * @param string   $str                    <p>The input string.</p>
1193
   * @param string   $search                 <p>The searched string.</p>
1194
   * @param int|null $length                 [optional] <p>Default: null === text->length / 2</p>
1195
   * @param string   $replacerForSkippedText [optional] <p>Default: …</p>
1196
   * @param string   $encoding               [optional] <p>Set the charset for e.g. "mb_" function</p>
1197
   *
1198
   * @return string
1199
   */
1200 1
  public static function extract_text(string $str, string $search = '', int $length = null, string $replacerForSkippedText = '…', string $encoding = 'UTF-8'): string
1201
  {
1202 1
    if ('' === $str) {
1203 1
      return '';
1204
    }
1205
1206 1
    $trimChars = "\t\r\n -_()!~?=+/*\\,.:;\"'[]{}`&";
1207
1208 1
    if ($length === null) {
1209 1
      $length = (int)\round(self::strlen($str, $encoding) / 2, 0);
1210
    }
1211
1212 1
    if (empty($search)) {
1213
1214 1
      $stringLength = self::strlen($str, $encoding);
1215
1216 1
      if ($length > 0) {
1217 1
        $end = ($length - 1) > $stringLength ? $stringLength : ($length - 1);
1218
      } else {
1219 1
        $end = 0;
1220
      }
1221
1222 1
      $pos = (int)\min(
1223 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

1223
          self::strpos($str, ' ', /** @scrutinizer ignore-type */ $end, $encoding),
Loading history...
1224 1
          self::strpos($str, '.', $end, $encoding)
1225
      );
1226
1227 1
      if ($pos) {
1228 1
        $strSub = self::substr($str, 0, $pos, $encoding);
1229 1
        if ($strSub === false) {
1230
          return '';
1231
        }
1232
1233 1
        return \rtrim($strSub, $trimChars) . $replacerForSkippedText;
1234
      }
1235
1236
      return $str;
1237
    }
1238
1239 1
    $wordPos = self::stripos($str, $search, 0, $encoding);
1240 1
    $halfSide = (int)($wordPos - $length / 2 + self::strlen($search, $encoding) / 2);
1241
1242 1
    $pos_start = 0;
1243 1
    if ($halfSide > 0) {
1244 1
      $halfText = self::substr($str, 0, $halfSide, $encoding);
1245 1
      if ($halfText !== false) {
1246 1
        $pos_start = (int)\max(
1247 1
            self::strrpos($halfText, ' ', 0, $encoding),
1248 1
            self::strrpos($halfText, '.', 0, $encoding)
1249
        );
1250
      }
1251
    }
1252
1253 1
    if ($wordPos && $halfSide > 0) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $wordPos of type integer|false 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...
1254 1
      $l = $pos_start + $length - 1;
1255 1
      $realLength = self::strlen($str, $encoding);
1256
1257 1
      if ($l > $realLength) {
1258
        $l = $realLength;
1259
      }
1260
1261 1
      $pos_end = (int)\min(
1262 1
              self::strpos($str, ' ', $l, $encoding),
1263 1
              self::strpos($str, '.', $l, $encoding)
1264 1
          ) - $pos_start;
1265
1266 1
      if (!$pos_end || $pos_end <= 0) {
1267 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 null|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

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

1805
      $BROKEN_UTF8_TO_UTF8_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$BROKEN_UTF8_FIX);
Loading history...
1806 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

1806
      $BROKEN_UTF8_TO_UTF8_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$BROKEN_UTF8_FIX);
Loading history...
1807
    }
1808
1809 42
    return \str_replace($BROKEN_UTF8_TO_UTF8_KEYS_CACHE, $BROKEN_UTF8_TO_UTF8_VALUES_CACHE, $str);
1810
  }
1811
1812
  /**
1813
   * Fix a double (or multiple) encoded UTF8 string.
1814
   *
1815
   * @param string[]|string $str You can use a string or an array of strings.
1816
   *
1817
   * @return string[]|string
1818
   *                          Will return the fixed input-"array" or
1819
   *                          the fixed input-"string".
1820
   */
1821 2
  public static function fix_utf8($str)
1822
  {
1823 2
    if (\is_array($str) === true) {
1824 2
      foreach ($str as $k => $v) {
1825 2
        $str[$k] = self::fix_utf8($v);
1826
      }
1827
1828 2
      return $str;
1829
    }
1830
1831 2
    $str = (string)$str;
1832 2
    $last = '';
1833 2
    while ($last !== $str) {
1834 2
      $last = $str;
1835 2
      $str = self::to_utf8(
1836 2
          self::utf8_decode($str, true)
1837
      );
1838
    }
1839
1840 2
    return $str;
1841
  }
1842
1843
  /**
1844
   * Get character of a specific character.
1845
   *
1846
   * @param string $char
1847
   *
1848
   * @return string 'RTL' or 'LTR'
1849
   */
1850 2
  public static function getCharDirection(string $char): string
1851
  {
1852 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1853
      self::checkForSupport();
1854
    }
1855
1856 2
    if (self::$SUPPORT['intlChar'] === true) {
1857
      /** @noinspection PhpComposerExtensionStubsInspection */
1858 2
      $tmpReturn = \IntlChar::charDirection($char);
1859
1860
      // from "IntlChar"-Class
1861
      $charDirection = [
1862 2
          'RTL' => [1, 13, 14, 15, 21],
1863
          'LTR' => [0, 11, 12, 20],
1864
      ];
1865
1866 2
      if (\in_array($tmpReturn, $charDirection['LTR'], true)) {
1867
        return 'LTR';
1868
      }
1869
1870 2
      if (\in_array($tmpReturn, $charDirection['RTL'], true)) {
1871 2
        return 'RTL';
1872
      }
1873
    }
1874
1875 2
    $c = static::chr_to_decimal($char);
1876
1877 2
    if (!(0x5be <= $c && 0x10b7f >= $c)) {
1878 2
      return 'LTR';
1879
    }
1880
1881 2
    if (0x85e >= $c) {
1882
1883 2
      if (0x5be === $c ||
1884 2
          0x5c0 === $c ||
1885 2
          0x5c3 === $c ||
1886 2
          0x5c6 === $c ||
1887 2
          (0x5d0 <= $c && 0x5ea >= $c) ||
1888 2
          (0x5f0 <= $c && 0x5f4 >= $c) ||
1889 2
          0x608 === $c ||
1890 2
          0x60b === $c ||
1891 2
          0x60d === $c ||
1892 2
          0x61b === $c ||
1893 2
          (0x61e <= $c && 0x64a >= $c) ||
1894
          (0x66d <= $c && 0x66f >= $c) ||
1895
          (0x671 <= $c && 0x6d5 >= $c) ||
1896
          (0x6e5 <= $c && 0x6e6 >= $c) ||
1897
          (0x6ee <= $c && 0x6ef >= $c) ||
1898
          (0x6fa <= $c && 0x70d >= $c) ||
1899
          0x710 === $c ||
1900
          (0x712 <= $c && 0x72f >= $c) ||
1901
          (0x74d <= $c && 0x7a5 >= $c) ||
1902
          0x7b1 === $c ||
1903
          (0x7c0 <= $c && 0x7ea >= $c) ||
1904
          (0x7f4 <= $c && 0x7f5 >= $c) ||
1905
          0x7fa === $c ||
1906
          (0x800 <= $c && 0x815 >= $c) ||
1907
          0x81a === $c ||
1908
          0x824 === $c ||
1909
          0x828 === $c ||
1910
          (0x830 <= $c && 0x83e >= $c) ||
1911
          (0x840 <= $c && 0x858 >= $c) ||
1912 2
          0x85e === $c
1913
      ) {
1914 2
        return 'RTL';
1915
      }
1916
1917 2
    } elseif (0x200f === $c) {
1918
1919
      return 'RTL';
1920
1921 2
    } elseif (0xfb1d <= $c) {
1922
1923 2
      if (0xfb1d === $c ||
1924 2
          (0xfb1f <= $c && 0xfb28 >= $c) ||
1925 2
          (0xfb2a <= $c && 0xfb36 >= $c) ||
1926 2
          (0xfb38 <= $c && 0xfb3c >= $c) ||
1927 2
          0xfb3e === $c ||
1928 2
          (0xfb40 <= $c && 0xfb41 >= $c) ||
1929 2
          (0xfb43 <= $c && 0xfb44 >= $c) ||
1930 2
          (0xfb46 <= $c && 0xfbc1 >= $c) ||
1931 2
          (0xfbd3 <= $c && 0xfd3d >= $c) ||
1932 2
          (0xfd50 <= $c && 0xfd8f >= $c) ||
1933 2
          (0xfd92 <= $c && 0xfdc7 >= $c) ||
1934 2
          (0xfdf0 <= $c && 0xfdfc >= $c) ||
1935 2
          (0xfe70 <= $c && 0xfe74 >= $c) ||
1936 2
          (0xfe76 <= $c && 0xfefc >= $c) ||
1937 2
          (0x10800 <= $c && 0x10805 >= $c) ||
1938 2
          0x10808 === $c ||
1939 2
          (0x1080a <= $c && 0x10835 >= $c) ||
1940 2
          (0x10837 <= $c && 0x10838 >= $c) ||
1941 2
          0x1083c === $c ||
1942 2
          (0x1083f <= $c && 0x10855 >= $c) ||
1943 2
          (0x10857 <= $c && 0x1085f >= $c) ||
1944 2
          (0x10900 <= $c && 0x1091b >= $c) ||
1945 2
          (0x10920 <= $c && 0x10939 >= $c) ||
1946 2
          0x1093f === $c ||
1947 2
          0x10a00 === $c ||
1948 2
          (0x10a10 <= $c && 0x10a13 >= $c) ||
1949 2
          (0x10a15 <= $c && 0x10a17 >= $c) ||
1950 2
          (0x10a19 <= $c && 0x10a33 >= $c) ||
1951 2
          (0x10a40 <= $c && 0x10a47 >= $c) ||
1952 2
          (0x10a50 <= $c && 0x10a58 >= $c) ||
1953 2
          (0x10a60 <= $c && 0x10a7f >= $c) ||
1954 2
          (0x10b00 <= $c && 0x10b35 >= $c) ||
1955 2
          (0x10b40 <= $c && 0x10b55 >= $c) ||
1956 2
          (0x10b58 <= $c && 0x10b72 >= $c) ||
1957 2
          (0x10b78 <= $c && 0x10b7f >= $c)
1958
      ) {
1959 2
        return 'RTL';
1960
      }
1961
    }
1962
1963 2
    return 'LTR';
1964
  }
1965
1966
  /**
1967
   * get data from "/data/*.ser"
1968
   *
1969
   * @param string $file
1970
   *
1971
   * @return mixed|false Will return false on error.
1972
   */
1973 13
  private static function getData(string $file)
1974
  {
1975 13
    $file = __DIR__ . '/data/' . $file . '.php';
1976 13
    if (\file_exists($file)) {
1977
      /** @noinspection PhpIncludeInspection */
1978 12
      return require $file;
1979
    }
1980
1981 2
    return false;
1982
  }
1983
1984
  /**
1985
   * Check for php-support.
1986
   *
1987
   * @param string|null $key
1988
   *
1989
   * @return mixed
1990
   *               Return the full support-"array", if $key === null<br>
1991
   *               return bool-value, if $key is used and available<br>
1992
   *               otherwise return <strong>null</strong>.
1993
   */
1994 25
  public static function getSupportInfo(string $key = null)
1995
  {
1996 25
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
1997
      self::checkForSupport();
1998
    }
1999
2000 25
    if ($key === null) {
2001 4
      return self::$SUPPORT;
2002
    }
2003
2004 23
    if (!isset(self::$SUPPORT[$key])) {
2005 2
      return null;
2006
    }
2007
2008 21
    return self::$SUPPORT[$key];
2009
  }
2010
2011
  /**
2012
   * @param string $str
2013
   *
2014
   * @return string[]
2015
   */
2016 40
  private static function get_file_type($str)
2017
  {
2018 40
    if ('' === $str) {
2019
      return ['ext' => '', 'type' => ''];
2020
    }
2021
2022 40
    $str_info = self::substr_in_byte($str, 0, 2);
2023 40
    if (self::strlen_in_byte($str_info) !== 2) {
2024 11
      return ['ext' => '', 'type' => ''];
2025
    }
2026
2027 35
    $str_info = \unpack("C2chars", $str_info);
2028 35
    $type_code = (int)($str_info['chars1'] . $str_info['chars2']);
2029
2030
    // DEBUG
2031
    //var_dump($type_code);
2032
2033
    switch ($type_code) {
2034 35
      case 3780:
2035 4
        $ext = 'pdf';
2036 4
        $type = 'binary';
2037 4
        break;
2038 35
      case 7790:
2039
        $ext = 'exe';
2040
        $type = 'binary';
2041
        break;
2042 35
      case 7784:
2043
        $ext = 'midi';
2044
        $type = 'binary';
2045
        break;
2046 35
      case 8075:
2047 6
        $ext = 'zip';
2048 6
        $type = 'binary';
2049 6
        break;
2050 35
      case 8297:
2051
        $ext = 'rar';
2052
        $type = 'binary';
2053
        break;
2054 35
      case 255216:
2055
        $ext = 'jpg';
2056
        $type = 'binary';
2057
        break;
2058 35
      case 7173:
2059
        $ext = 'gif';
2060
        $type = 'binary';
2061
        break;
2062 35
      case 6677:
2063
        $ext = 'bmp';
2064
        $type = 'binary';
2065
        break;
2066 35
      case 13780:
2067 6
        $ext = 'png';
2068 6
        $type = 'binary';
2069 6
        break;
2070
      default:
2071 33
        $ext = '???';
2072 33
        $type = '???';
2073 33
        break;
2074
    }
2075
2076 35
    return ['ext' => $ext, 'type' => $type];
2077
  }
2078
2079
  /**
2080
   * @param int    $length        <p>Length of the random string.</p>
2081
   * @param string $possibleChars [optional] <p>Characters string for the random selection.</p>
2082
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
2083
   *
2084
   * @return string
2085
   */
2086 1
  public static function get_random_string(int $length, string $possibleChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', string $encoding = 'UTF-8'): string
2087
  {
2088
    // init
2089 1
    $i = 0;
2090 1
    $str = '';
2091 1
    $maxlength = self::strlen($possibleChars, $encoding);
2092
2093 1
    if ($maxlength === 0) {
2094 1
      return '';
2095
    }
2096
2097
    // add random chars
2098 1
    while ($i < $length) {
2099
      try {
2100 1
        $randInt = \random_int(0, $maxlength - 1);
2101
      } catch (\Exception $e) {
2102
        /** @noinspection RandomApiMigrationInspection */
2103
        $randInt = \mt_rand(0, $maxlength - 1);
2104
      }
2105 1
      $char = self::substr($possibleChars, $randInt, 1, $encoding);
2106 1
      $str .= $char;
2107 1
      $i++;
2108
    }
2109
2110 1
    return $str;
2111
  }
2112
2113
  /**
2114
   * @param string|int $entropyExtra [optional] <p>Extra entropy via a string or int value.</p>
2115
   * @param bool       $md5          [optional] <p>Return the unique identifier as md5-hash? Default: true</p>
2116
   *
2117
   * @return string
2118
   */
2119 1
  public static function get_unique_string($entropyExtra = '', bool $md5 = true): string
2120
  {
2121 1
    $uniqueHelper = \mt_rand() .
2122 1
                    \session_id() .
2123 1
                    ($_SERVER['REMOTE_ADDR'] ?? '') .
2124 1
                    ($_SERVER['SERVER_ADDR'] ?? '') .
2125 1
                    $entropyExtra;
2126
2127 1
    $uniqueString = \uniqid($uniqueHelper, true);
2128
2129 1
    if ($md5) {
2130 1
      $uniqueString = \md5($uniqueString . $uniqueHelper);
2131
    }
2132
2133 1
    return $uniqueString;
2134
  }
2135
2136
  /**
2137
   * alias for "UTF8::string_has_bom()"
2138
   *
2139
   * @see        UTF8::string_has_bom()
2140
   *
2141
   * @param string $str
2142
   *
2143
   * @return bool
2144
   *
2145
   * @deprecated <p>use "UTF8::string_has_bom()"</p>
2146
   */
2147 2
  public static function hasBom(string $str): bool
2148
  {
2149 2
    return self::string_has_bom($str);
2150
  }
2151
2152
  /**
2153
   * Returns true if the string contains a lower case char, false otherwise.
2154
   *
2155
   * @param string $str <p>The input string.</p>
2156
   *
2157
   * @return bool Whether or not the string contains a lower case character.
2158
   */
2159 47
  public static function has_lowercase(string $str): bool
2160
  {
2161 47
    return self::str_matches_pattern($str, '.*[[:lower:]]');
2162
  }
2163
2164
  /**
2165
   * Returns true if the string contains an upper case char, false otherwise.
2166
   *
2167
   * @param string $str <p>The input string.</p>
2168
   *
2169
   * @return bool Whether or not the string contains an upper case character.
2170
   */
2171 12
  public static function has_uppercase(string $str): bool
2172
  {
2173 12
    return self::str_matches_pattern($str, '.*[[:upper:]]');
2174
  }
2175
2176
  /**
2177
   * Converts a hexadecimal-value into an UTF-8 character.
2178
   *
2179
   * @param string $hexdec <p>The hexadecimal value.</p>
2180
   *
2181
   * @return string|false One single UTF-8 character.
2182
   */
2183 4
  public static function hex_to_chr(string $hexdec)
2184
  {
2185 4
    return self::decimal_to_chr(\hexdec($hexdec));
2186
  }
2187
2188
  /**
2189
   * Converts hexadecimal U+xxxx code point representation to integer.
2190
   *
2191
   * INFO: opposite to UTF8::int_to_hex()
2192
   *
2193
   * @param string $hexDec <p>The hexadecimal code point representation.</p>
2194
   *
2195
   * @return int|false The code point, or false on failure.
2196
   */
2197 2
  public static function hex_to_int($hexDec)
2198
  {
2199
    // init
2200 2
    $hexDec = (string)$hexDec;
2201
2202 2
    if ('' === $hexDec) {
2203 2
      return false;
2204
    }
2205
2206 2
    if (\preg_match('/^(?:\\\u|U\+|)([a-z0-9]{4,6})$/i', $hexDec, $match)) {
2207 2
      return \intval($match[1], 16);
2208
    }
2209
2210 2
    return false;
2211
  }
2212
2213
  /**
2214
   * alias for "UTF8::html_entity_decode()"
2215
   *
2216
   * @see UTF8::html_entity_decode()
2217
   *
2218
   * @param string $str
2219
   * @param int    $flags
2220
   * @param string $encoding
2221
   *
2222
   * @return string
2223
   */
2224 2
  public static function html_decode(string $str, int $flags = null, string $encoding = 'UTF-8'): string
2225
  {
2226 2
    return self::html_entity_decode($str, $flags, $encoding);
2227
  }
2228
2229
  /**
2230
   * Converts a UTF-8 string to a series of HTML numbered entities.
2231
   *
2232
   * INFO: opposite to UTF8::html_decode()
2233
   *
2234
   * @param string $str            <p>The Unicode string to be encoded as numbered entities.</p>
2235
   * @param bool   $keepAsciiChars [optional] <p>Keep ASCII chars.</p>
2236
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
2237
   *
2238
   * @return string HTML numbered entities.
2239
   */
2240 13
  public static function html_encode(string $str, bool $keepAsciiChars = false, string $encoding = 'UTF-8'): string
2241
  {
2242 13
    if ('' === $str) {
2243 4
      return '';
2244
    }
2245
2246 13
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2247 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2248
    }
2249
2250 13
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
2251
      self::checkForSupport();
2252
    }
2253
2254
    # INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2255 13
    if (self::$SUPPORT['mbstring'] === true) {
2256 13
      $startCode = 0x00;
2257 13
      if ($keepAsciiChars === true) {
2258 13
        $startCode = 0x80;
2259
      }
2260
2261 13
      return \mb_encode_numericentity(
2262 13
          $str,
2263 13
          [$startCode, 0xfffff, 0, 0xfffff, 0],
2264 13
          $encoding
2265
      );
2266
    }
2267
2268
    //
2269
    // fallback via vanilla php
2270
    //
2271
2272
    return \implode(
2273
        '',
2274
        \array_map(
2275
            function ($chr) use ($keepAsciiChars, $encoding) {
2276
              return UTF8::single_chr_html_encode($chr, $keepAsciiChars, $encoding);
2277
            },
2278
            self::split($str)
2279
        )
2280
    );
2281
  }
2282
2283
  /**
2284
   * UTF-8 version of html_entity_decode()
2285
   *
2286
   * The reason we are not using html_entity_decode() by itself is because
2287
   * while it is not technically correct to leave out the semicolon
2288
   * at the end of an entity most browsers will still interpret the entity
2289
   * correctly. html_entity_decode() does not convert entities without
2290
   * semicolons, so we are left with our own little solution here. Bummer.
2291
   *
2292
   * Convert all HTML entities to their applicable characters
2293
   *
2294
   * INFO: opposite to UTF8::html_encode()
2295
   *
2296
   * @link http://php.net/manual/en/function.html-entity-decode.php
2297
   *
2298
   * @param string $str      <p>
2299
   *                         The input string.
2300
   *                         </p>
2301
   * @param int    $flags    [optional] <p>
2302
   *                         A bitmask of one or more of the following flags, which specify how to handle quotes and
2303
   *                         which document type to use. The default is ENT_COMPAT | ENT_HTML401.
2304
   *                         <table>
2305
   *                         Available <i>flags</i> constants
2306
   *                         <tr valign="top">
2307
   *                         <td>Constant Name</td>
2308
   *                         <td>Description</td>
2309
   *                         </tr>
2310
   *                         <tr valign="top">
2311
   *                         <td><b>ENT_COMPAT</b></td>
2312
   *                         <td>Will convert double-quotes and leave single-quotes alone.</td>
2313
   *                         </tr>
2314
   *                         <tr valign="top">
2315
   *                         <td><b>ENT_QUOTES</b></td>
2316
   *                         <td>Will convert both double and single quotes.</td>
2317
   *                         </tr>
2318
   *                         <tr valign="top">
2319
   *                         <td><b>ENT_NOQUOTES</b></td>
2320
   *                         <td>Will leave both double and single quotes unconverted.</td>
2321
   *                         </tr>
2322
   *                         <tr valign="top">
2323
   *                         <td><b>ENT_HTML401</b></td>
2324
   *                         <td>
2325
   *                         Handle code as HTML 4.01.
2326
   *                         </td>
2327
   *                         </tr>
2328
   *                         <tr valign="top">
2329
   *                         <td><b>ENT_XML1</b></td>
2330
   *                         <td>
2331
   *                         Handle code as XML 1.
2332
   *                         </td>
2333
   *                         </tr>
2334
   *                         <tr valign="top">
2335
   *                         <td><b>ENT_XHTML</b></td>
2336
   *                         <td>
2337
   *                         Handle code as XHTML.
2338
   *                         </td>
2339
   *                         </tr>
2340
   *                         <tr valign="top">
2341
   *                         <td><b>ENT_HTML5</b></td>
2342
   *                         <td>
2343
   *                         Handle code as HTML 5.
2344
   *                         </td>
2345
   *                         </tr>
2346
   *                         </table>
2347
   *                         </p>
2348
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
2349
   *
2350
   * @return string The decoded string.
2351
   */
2352 40
  public static function html_entity_decode(string $str, int $flags = null, string $encoding = 'UTF-8'): string
2353
  {
2354 40
    if ('' === $str) {
2355 12
      return '';
2356
    }
2357
2358 40
    if (!isset($str[3])) { // examples: &; || &x;
2359 19
      return $str;
2360
    }
2361
2362
    if (
2363 39
        \strpos($str, '&') === false
2364
        ||
2365
        (
2366 39
            \strpos($str, '&#') === false
2367
            &&
2368 39
            \strpos($str, ';') === false
2369
        )
2370
    ) {
2371 18
      return $str;
2372
    }
2373
2374 39
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2375 9
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2376
    }
2377
2378 39
    if ($flags === null) {
2379 10
      $flags = ENT_QUOTES | ENT_HTML5;
2380
    }
2381
2382
    if (
2383 39
        $encoding !== 'UTF-8'
2384
        &&
2385 39
        $encoding !== 'ISO-8859-1'
2386
        &&
2387 39
        $encoding !== 'WINDOWS-1252'
2388
        &&
2389 39
        self::$SUPPORT['mbstring'] === false
2390
    ) {
2391
      \trigger_error('UTF8::html_entity_decode() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
2392
    }
2393
2394 39
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
2395
      self::checkForSupport();
2396
    }
2397
2398
    do {
2399 39
      $str_compare = $str;
2400
2401
      # INFO: http://stackoverflow.com/questions/35854535/better-explanation-of-convmap-in-mb-encode-numericentity
2402 39
      if (self::$SUPPORT['mbstring'] === true) {
2403
2404 39
        $str = \mb_decode_numericentity(
2405 39
            $str,
2406 39
            [0x80, 0xfffff, 0, 0xfffff, 0],
2407 39
            $encoding
2408
        );
2409
2410
      } else {
2411
2412
        $str = (string)\preg_replace_callback(
2413
            "/&#\d{2,6};/",
2414
            function ($matches) use ($encoding) {
2415
              // always fallback via symfony polyfill
2416
              $returnTmp = \mb_convert_encoding($matches[0], $encoding, 'HTML-ENTITIES');
2417
2418
              if ($returnTmp !== '"' && $returnTmp !== "'") {
2419
                return $returnTmp;
2420
              }
2421
2422
              return $matches[0];
2423
            },
2424
            $str
2425
        );
2426
2427
      }
2428
2429
      // decode numeric & UTF16 two byte entities
2430 39
      $str = \html_entity_decode(
2431 39
          \preg_replace('/(&#(?:x0*[0-9a-f]{2,6}(?![0-9a-f;])|(?:0*\d{2,6}(?![0-9;]))))/iS', '$1;', $str),
2432 39
          $flags,
2433 39
          $encoding
2434
      );
2435
2436 39
    } while ($str_compare !== $str);
2437
2438 39
    return $str;
2439
  }
2440
2441
  /**
2442
   * Create a escape html version of the string via "UTF8::htmlspecialchars()".
2443
   *
2444
   * @param string $str
2445
   * @param string $encoding [optional] <p>Default: UTF-8</p>
2446
   *
2447
   * @return string
2448
   */
2449 6
  public static function html_escape(string $str, string $encoding = 'UTF-8'): string
2450
  {
2451 6
    return self::htmlspecialchars(
2452 6
        $str,
2453 6
        ENT_QUOTES | ENT_SUBSTITUTE,
2454 6
        $encoding
2455
    );
2456
  }
2457
2458
  /**
2459
   * Remove empty html-tag.
2460
   *
2461
   * e.g.: <tag></tag>
2462
   *
2463
   * @param string $str
2464
   *
2465
   * @return string
2466
   */
2467 1
  public static function html_stripe_empty_tags(string $str): string
2468
  {
2469 1
    return (string)\preg_replace(
2470 1
        "/<[^\/>]*>(([\s]?)*|)<\/[^>]*>/iu",
2471 1
        '',
2472 1
        $str
2473
    );
2474
  }
2475
2476
  /**
2477
   * Convert all applicable characters to HTML entities: UTF-8 version of htmlentities()
2478
   *
2479
   * @link http://php.net/manual/en/function.htmlentities.php
2480
   *
2481
   * @param string $str           <p>
2482
   *                              The input string.
2483
   *                              </p>
2484
   * @param int    $flags         [optional] <p>
2485
   *                              A bitmask of one or more of the following flags, which specify how to handle quotes,
2486
   *                              invalid code unit sequences and the used document type. The default is
2487
   *                              ENT_COMPAT | ENT_HTML401.
2488
   *                              <table>
2489
   *                              Available <i>flags</i> constants
2490
   *                              <tr valign="top">
2491
   *                              <td>Constant Name</td>
2492
   *                              <td>Description</td>
2493
   *                              </tr>
2494
   *                              <tr valign="top">
2495
   *                              <td><b>ENT_COMPAT</b></td>
2496
   *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2497
   *                              </tr>
2498
   *                              <tr valign="top">
2499
   *                              <td><b>ENT_QUOTES</b></td>
2500
   *                              <td>Will convert both double and single quotes.</td>
2501
   *                              </tr>
2502
   *                              <tr valign="top">
2503
   *                              <td><b>ENT_NOQUOTES</b></td>
2504
   *                              <td>Will leave both double and single quotes unconverted.</td>
2505
   *                              </tr>
2506
   *                              <tr valign="top">
2507
   *                              <td><b>ENT_IGNORE</b></td>
2508
   *                              <td>
2509
   *                              Silently discard invalid code unit sequences instead of returning
2510
   *                              an empty string. Using this flag is discouraged as it
2511
   *                              may have security implications.
2512
   *                              </td>
2513
   *                              </tr>
2514
   *                              <tr valign="top">
2515
   *                              <td><b>ENT_SUBSTITUTE</b></td>
2516
   *                              <td>
2517
   *                              Replace invalid code unit sequences with a Unicode Replacement Character
2518
   *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty string.
2519
   *                              </td>
2520
   *                              </tr>
2521
   *                              <tr valign="top">
2522
   *                              <td><b>ENT_DISALLOWED</b></td>
2523
   *                              <td>
2524
   *                              Replace invalid code points for the given document type with a
2525
   *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2526
   *                              (otherwise) instead of leaving them as is. This may be useful, for
2527
   *                              instance, to ensure the well-formedness of XML documents with
2528
   *                              embedded external content.
2529
   *                              </td>
2530
   *                              </tr>
2531
   *                              <tr valign="top">
2532
   *                              <td><b>ENT_HTML401</b></td>
2533
   *                              <td>
2534
   *                              Handle code as HTML 4.01.
2535
   *                              </td>
2536
   *                              </tr>
2537
   *                              <tr valign="top">
2538
   *                              <td><b>ENT_XML1</b></td>
2539
   *                              <td>
2540
   *                              Handle code as XML 1.
2541
   *                              </td>
2542
   *                              </tr>
2543
   *                              <tr valign="top">
2544
   *                              <td><b>ENT_XHTML</b></td>
2545
   *                              <td>
2546
   *                              Handle code as XHTML.
2547
   *                              </td>
2548
   *                              </tr>
2549
   *                              <tr valign="top">
2550
   *                              <td><b>ENT_HTML5</b></td>
2551
   *                              <td>
2552
   *                              Handle code as HTML 5.
2553
   *                              </td>
2554
   *                              </tr>
2555
   *                              </table>
2556
   *                              </p>
2557
   * @param string $encoding      [optional] <p>
2558
   *                              Like <b>htmlspecialchars</b>,
2559
   *                              <b>htmlentities</b> takes an optional third argument
2560
   *                              <i>encoding</i> which defines encoding used in
2561
   *                              conversion.
2562
   *                              Although this argument is technically optional, you are highly
2563
   *                              encouraged to specify the correct value for your code.
2564
   *                              </p>
2565
   * @param bool   $double_encode [optional] <p>
2566
   *                              When <i>double_encode</i> is turned off PHP will not
2567
   *                              encode existing html entities. The default is to convert everything.
2568
   *                              </p>
2569
   *
2570
   *
2571
   * @return string The encoded string.
2572
   * </p>
2573
   * <p>
2574
   * If the input <i>string</i> contains an invalid code unit
2575
   * sequence within the given <i>encoding</i> an empty string
2576
   * will be returned, unless either the <b>ENT_IGNORE</b> or
2577
   * <b>ENT_SUBSTITUTE</b> flags are set.
2578
   */
2579 9
  public static function htmlentities(string $str, int $flags = ENT_COMPAT, string $encoding = 'UTF-8', bool $double_encode = true): string
2580
  {
2581 9
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2582 7
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2583
    }
2584
2585 9
    $str = \htmlentities($str, $flags, $encoding, $double_encode);
2586
2587
    /**
2588
     * PHP doesn't replace a backslash to its html entity since this is something
2589
     * that's mostly used to escape characters when inserting in a database. Since
2590
     * we're using a decent database layer, we don't need this shit and we're replacing
2591
     * the double backslashes by its' html entity equivalent.
2592
     *
2593
     * https://github.com/forkcms/library/blob/master/spoon/filter/filter.php#L303
2594
     */
2595 9
    $str = \str_replace('\\', '&#92;', $str);
2596
2597 9
    return self::html_encode($str, true, $encoding);
2598
  }
2599
2600
  /**
2601
   * Convert only special characters to HTML entities: UTF-8 version of htmlspecialchars()
2602
   *
2603
   * INFO: Take a look at "UTF8::htmlentities()"
2604
   *
2605
   * @link http://php.net/manual/en/function.htmlspecialchars.php
2606
   *
2607
   * @param string $str           <p>
2608
   *                              The string being converted.
2609
   *                              </p>
2610
   * @param int    $flags         [optional] <p>
2611
   *                              A bitmask of one or more of the following flags, which specify how to handle quotes,
2612
   *                              invalid code unit sequences and the used document type. The default is
2613
   *                              ENT_COMPAT | ENT_HTML401.
2614
   *                              <table>
2615
   *                              Available <i>flags</i> constants
2616
   *                              <tr valign="top">
2617
   *                              <td>Constant Name</td>
2618
   *                              <td>Description</td>
2619
   *                              </tr>
2620
   *                              <tr valign="top">
2621
   *                              <td><b>ENT_COMPAT</b></td>
2622
   *                              <td>Will convert double-quotes and leave single-quotes alone.</td>
2623
   *                              </tr>
2624
   *                              <tr valign="top">
2625
   *                              <td><b>ENT_QUOTES</b></td>
2626
   *                              <td>Will convert both double and single quotes.</td>
2627
   *                              </tr>
2628
   *                              <tr valign="top">
2629
   *                              <td><b>ENT_NOQUOTES</b></td>
2630
   *                              <td>Will leave both double and single quotes unconverted.</td>
2631
   *                              </tr>
2632
   *                              <tr valign="top">
2633
   *                              <td><b>ENT_IGNORE</b></td>
2634
   *                              <td>
2635
   *                              Silently discard invalid code unit sequences instead of returning
2636
   *                              an empty string. Using this flag is discouraged as it
2637
   *                              may have security implications.
2638
   *                              </td>
2639
   *                              </tr>
2640
   *                              <tr valign="top">
2641
   *                              <td><b>ENT_SUBSTITUTE</b></td>
2642
   *                              <td>
2643
   *                              Replace invalid code unit sequences with a Unicode Replacement Character
2644
   *                              U+FFFD (UTF-8) or &#38;#38;#FFFD; (otherwise) instead of returning an empty string.
2645
   *                              </td>
2646
   *                              </tr>
2647
   *                              <tr valign="top">
2648
   *                              <td><b>ENT_DISALLOWED</b></td>
2649
   *                              <td>
2650
   *                              Replace invalid code points for the given document type with a
2651
   *                              Unicode Replacement Character U+FFFD (UTF-8) or &#38;#38;#FFFD;
2652
   *                              (otherwise) instead of leaving them as is. This may be useful, for
2653
   *                              instance, to ensure the well-formedness of XML documents with
2654
   *                              embedded external content.
2655
   *                              </td>
2656
   *                              </tr>
2657
   *                              <tr valign="top">
2658
   *                              <td><b>ENT_HTML401</b></td>
2659
   *                              <td>
2660
   *                              Handle code as HTML 4.01.
2661
   *                              </td>
2662
   *                              </tr>
2663
   *                              <tr valign="top">
2664
   *                              <td><b>ENT_XML1</b></td>
2665
   *                              <td>
2666
   *                              Handle code as XML 1.
2667
   *                              </td>
2668
   *                              </tr>
2669
   *                              <tr valign="top">
2670
   *                              <td><b>ENT_XHTML</b></td>
2671
   *                              <td>
2672
   *                              Handle code as XHTML.
2673
   *                              </td>
2674
   *                              </tr>
2675
   *                              <tr valign="top">
2676
   *                              <td><b>ENT_HTML5</b></td>
2677
   *                              <td>
2678
   *                              Handle code as HTML 5.
2679
   *                              </td>
2680
   *                              </tr>
2681
   *                              </table>
2682
   *                              </p>
2683
   * @param string $encoding      [optional] <p>
2684
   *                              Defines encoding used in conversion.
2685
   *                              </p>
2686
   *                              <p>
2687
   *                              For the purposes of this function, the encodings
2688
   *                              ISO-8859-1, ISO-8859-15,
2689
   *                              UTF-8, cp866,
2690
   *                              cp1251, cp1252, and
2691
   *                              KOI8-R are effectively equivalent, provided the
2692
   *                              <i>string</i> itself is valid for the encoding, as
2693
   *                              the characters affected by <b>htmlspecialchars</b> occupy
2694
   *                              the same positions in all of these encodings.
2695
   *                              </p>
2696
   * @param bool   $double_encode [optional] <p>
2697
   *                              When <i>double_encode</i> is turned off PHP will not
2698
   *                              encode existing html entities, the default is to convert everything.
2699
   *                              </p>
2700
   *
2701
   * @return string The converted string.
2702
   * </p>
2703
   * <p>
2704
   * If the input <i>string</i> contains an invalid code unit
2705
   * sequence within the given <i>encoding</i> an empty string
2706
   * will be returned, unless either the <b>ENT_IGNORE</b> or
2707
   * <b>ENT_SUBSTITUTE</b> flags are set.
2708
   */
2709 8
  public static function htmlspecialchars(string $str, int $flags = ENT_COMPAT, string $encoding = 'UTF-8', bool $double_encode = true): string
2710
  {
2711 8
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
2712 8
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
2713
    }
2714
2715 8
    return \htmlspecialchars($str, $flags, $encoding, $double_encode);
2716
  }
2717
2718
  /**
2719
   * Checks whether iconv is available on the server.
2720
   *
2721
   * @return bool
2722
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2723
   */
2724
  public static function iconv_loaded(): bool
2725
  {
2726
    return \extension_loaded('iconv') ? true : false;
2727
  }
2728
2729
  /**
2730
   * alias for "UTF8::decimal_to_chr()"
2731
   *
2732
   * @see UTF8::decimal_to_chr()
2733
   *
2734
   * @param mixed $int
2735
   *
2736
   * @return string
2737
   */
2738 4
  public static function int_to_chr($int): string
2739
  {
2740 4
    return self::decimal_to_chr($int);
2741
  }
2742
2743
  /**
2744
   * Converts Integer to hexadecimal U+xxxx code point representation.
2745
   *
2746
   * INFO: opposite to UTF8::hex_to_int()
2747
   *
2748
   * @param int    $int  <p>The integer to be converted to hexadecimal code point.</p>
2749
   * @param string $pfix [optional]
2750
   *
2751
   * @return string The code point, or empty string on failure.
2752
   */
2753 6
  public static function int_to_hex(int $int, string $pfix = 'U+'): string
2754
  {
2755 6
    $hex = \dechex($int);
2756
2757 6
    $hex = (\strlen($hex) < 4 ? \substr('0000' . $hex, -4) : $hex);
2758
2759 6
    return $pfix . $hex . '';
2760
  }
2761
2762
  /**
2763
   * Checks whether intl-char is available on the server.
2764
   *
2765
   * @return bool
2766
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2767
   */
2768
  public static function intlChar_loaded(): bool
2769
  {
2770
    return \class_exists('IntlChar');
2771
  }
2772
2773
  /**
2774
   * Checks whether intl is available on the server.
2775
   *
2776
   * @return bool
2777
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
2778
   */
2779 5
  public static function intl_loaded(): bool
2780
  {
2781 5
    return \extension_loaded('intl');
2782
  }
2783
2784
  /**
2785
   * alias for "UTF8::is_ascii()"
2786
   *
2787
   * @see        UTF8::is_ascii()
2788
   *
2789
   * @param string $str
2790
   *
2791
   * @return bool
2792
   *
2793
   * @deprecated <p>use "UTF8::is_ascii()"</p>
2794
   */
2795 2
  public static function isAscii(string $str): bool
2796
  {
2797 2
    return self::is_ascii($str);
2798
  }
2799
2800
  /**
2801
   * alias for "UTF8::is_base64()"
2802
   *
2803
   * @see        UTF8::is_base64()
2804
   *
2805
   * @param string $str
2806
   *
2807
   * @return bool
2808
   *
2809
   * @deprecated <p>use "UTF8::is_base64()"</p>
2810
   */
2811 2
  public static function isBase64($str): bool
2812
  {
2813 2
    return self::is_base64($str);
2814
  }
2815
2816
  /**
2817
   * alias for "UTF8::is_binary()"
2818
   *
2819
   * @see        UTF8::is_binary()
2820
   *
2821
   * @param mixed $str
2822
   * @param bool  $strict
2823
   *
2824
   * @return bool
2825
   *
2826
   * @deprecated <p>use "UTF8::is_binary()"</p>
2827
   */
2828 4
  public static function isBinary($str, $strict = false): bool
2829
  {
2830 4
    return self::is_binary($str, $strict);
2831
  }
2832
2833
  /**
2834
   * alias for "UTF8::is_bom()"
2835
   *
2836
   * @see        UTF8::is_bom()
2837
   *
2838
   * @param string $utf8_chr
2839
   *
2840
   * @return bool
2841
   *
2842
   * @deprecated <p>use "UTF8::is_bom()"</p>
2843
   */
2844 2
  public static function isBom(string $utf8_chr): bool
2845
  {
2846 2
    return self::is_bom($utf8_chr);
2847
  }
2848
2849
  /**
2850
   * alias for "UTF8::is_html()"
2851
   *
2852
   * @see        UTF8::is_html()
2853
   *
2854
   * @param string $str
2855
   *
2856
   * @return bool
2857
   *
2858
   * @deprecated <p>use "UTF8::is_html()"</p>
2859
   */
2860 2
  public static function isHtml(string $str): bool
2861
  {
2862 2
    return self::is_html($str);
2863
  }
2864
2865
  /**
2866
   * alias for "UTF8::is_json()"
2867
   *
2868
   * @see        UTF8::is_json()
2869
   *
2870
   * @param string $str
2871
   *
2872
   * @return bool
2873
   *
2874
   * @deprecated <p>use "UTF8::is_json()"</p>
2875
   */
2876
  public static function isJson(string $str): bool
2877
  {
2878
    return self::is_json($str);
2879
  }
2880
2881
  /**
2882
   * alias for "UTF8::is_utf16()"
2883
   *
2884
   * @see        UTF8::is_utf16()
2885
   *
2886
   * @param mixed $str
2887
   *
2888
   * @return int|false
2889
   *                    <strong>false</strong> if is't not UTF16,<br>
2890
   *                    <strong>1</strong> for UTF-16LE,<br>
2891
   *                    <strong>2</strong> for UTF-16BE.
2892
   *
2893
   * @deprecated <p>use "UTF8::is_utf16()"</p>
2894
   */
2895 2
  public static function isUtf16($str)
2896
  {
2897 2
    return self::is_utf16($str);
2898
  }
2899
2900
  /**
2901
   * alias for "UTF8::is_utf32()"
2902
   *
2903
   * @see        UTF8::is_utf32()
2904
   *
2905
   * @param mixed $str
2906
   *
2907
   * @return int|false
2908
   *                   <strong>false</strong> if is't not UTF16,
2909
   *                   <strong>1</strong> for UTF-32LE,
2910
   *                   <strong>2</strong> for UTF-32BE.
2911
   *
2912
   * @deprecated <p>use "UTF8::is_utf32()"</p>
2913
   */
2914 2
  public static function isUtf32($str)
2915
  {
2916 2
    return self::is_utf32($str);
2917
  }
2918
2919
  /**
2920
   * alias for "UTF8::is_utf8()"
2921
   *
2922
   * @see        UTF8::is_utf8()
2923
   *
2924
   * @param string $str
2925
   * @param bool   $strict
2926
   *
2927
   * @return bool
2928
   *
2929
   * @deprecated <p>use "UTF8::is_utf8()"</p>
2930
   */
2931 17
  public static function isUtf8($str, $strict = false): bool
2932
  {
2933 17
    return self::is_utf8($str, $strict);
2934
  }
2935
2936
  /**
2937
   * Returns true if the string contains only alphabetic chars, false otherwise.
2938
   *
2939
   * @param string $str
2940
   *
2941
   * @return bool
2942
   *               Whether or not $str contains only alphabetic chars.
2943
   */
2944 10
  public static function is_alpha(string $str): bool
2945
  {
2946 10
    return self::str_matches_pattern($str, '^[[:alpha:]]*$');
2947
  }
2948
2949
  /**
2950
   * Returns true if the string contains only alphabetic and numeric chars, false otherwise.
2951
   *
2952
   * @param string $str
2953
   *
2954
   * @return bool
2955
   *               Whether or not $str contains only alphanumeric chars.
2956
   */
2957 13
  public static function is_alphanumeric(string $str): bool
2958
  {
2959 13
    return self::str_matches_pattern($str, '^[[:alnum:]]*$');
2960
  }
2961
2962
  /**
2963
   * Checks if a string is 7 bit ASCII.
2964
   *
2965
   * @param string $str <p>The string to check.</p>
2966
   *
2967
   * @return bool
2968
   *              <strong>true</strong> if it is ASCII<br>
2969
   *              <strong>false</strong> otherwise
2970
   *
2971
   */
2972 197
  public static function is_ascii(string $str): bool
2973
  {
2974 197
    if ('' === $str) {
2975 10
      return true;
2976
    }
2977
2978 196
    return !\preg_match('/[^\x09\x10\x13\x0A\x0D\x20-\x7E]/', $str);
2979
  }
2980
2981
  /**
2982
   * Returns true if the string is base64 encoded, false otherwise.
2983
   *
2984
   * @param string $str <p>The input string.</p>
2985
   *
2986
   * @return bool Whether or not $str is base64 encoded.
2987
   */
2988 9
  public static function is_base64($str): bool
2989
  {
2990 9
    if ('' === $str) {
2991 3
      return false;
2992
    }
2993
2994 8
    if (\is_string($str) === false) {
0 ignored issues
show
introduced by
The condition is_string($str) === false is always false.
Loading history...
2995 2
      return false;
2996
    }
2997
2998 8
    $base64String = (string)\base64_decode($str, true);
2999
3000 8
    return $base64String && \base64_encode($base64String) === $str;
3001
  }
3002
3003
  /**
3004
   * Check if the input is binary... (is look like a hack).
3005
   *
3006
   * @param mixed $input
3007
   * @param bool  $strict
3008
   *
3009
   * @return bool
3010
   */
3011 40
  public static function is_binary($input, bool $strict = false): bool
3012
  {
3013 40
    $input = (string)$input;
3014 40
    if ('' === $input) {
3015 10
      return false;
3016
    }
3017
3018 40
    if (\preg_match('~^[01]+$~', $input)) {
3019 12
      return true;
3020
    }
3021
3022 40
    if ($strict === true) {
3023
3024 34
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3025
        self::checkForSupport();
3026
      }
3027
3028 34
      if (self::$SUPPORT['finfo'] === false) {
3029
        throw new \RuntimeException('ext-fileinfo: is not installed');
3030
      }
3031
3032
      /** @noinspection PhpComposerExtensionStubsInspection */
3033 34
      $finfo = new \finfo(FILEINFO_MIME_ENCODING);
3034 34
      $finfo_encoding = $finfo->buffer($input);
3035 34
      if ($finfo_encoding && $finfo_encoding === 'binary') {
3036 15
        return true;
3037
      }
3038
3039
    }
3040
3041 40
    $ext = self::get_file_type($input);
3042 40
    if ($ext['type'] === 'binary') {
3043 6
      return true;
3044
    }
3045
3046 38
    $testLength = self::strlen_in_byte($input);
3047 38
    if ($testLength) {
3048 38
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3049
        self::checkForSupport();
3050
      }
3051
3052 38
      $testNull = self::substr_count_in_byte($input, "\x0", 0, $testLength);
3053 38
      if (($testNull / $testLength) > 0.256) {
3054 12
        return true;
3055
      }
3056
    }
3057
3058 36
    return false;
3059
  }
3060
3061
  /**
3062
   * Check if the file is binary.
3063
   *
3064
   * @param string $file
3065
   *
3066
   * @return bool
3067
   */
3068 6
  public static function is_binary_file($file): bool
3069
  {
3070
    // init
3071 6
    $block = '';
3072
3073 6
    $fp = \fopen($file, 'rb');
3074 6
    if (\is_resource($fp)) {
3075 6
      $block = \fread($fp, 512);
3076 6
      \fclose($fp);
3077
    }
3078
3079 6
    if ($block === '') {
3080 2
      return false;
3081
    }
3082
3083 6
    return self::is_binary($block, true);
3084
  }
3085
3086
  /**
3087
   * Returns true if the string contains only whitespace chars, false otherwise.
3088
   *
3089
   * @param string $str
3090
   *
3091
   * @return bool
3092
   *               Whether or not $str contains only whitespace characters.
3093
   */
3094 15
  public static function is_blank(string $str): bool
3095
  {
3096 15
    return self::str_matches_pattern($str, '^[[:space:]]*$');
3097
  }
3098
3099
  /**
3100
   * Checks if the given string is equal to any "Byte Order Mark".
3101
   *
3102
   * WARNING: Use "UTF8::string_has_bom()" if you will check BOM in a string.
3103
   *
3104
   * @param string $str <p>The input string.</p>
3105
   *
3106
   * @return bool
3107
   *              <strong>true</strong> if the $utf8_chr is Byte Order Mark, <strong>false</strong> otherwise.
3108
   */
3109 2
  public static function is_bom($str): bool
3110
  {
3111 2
    foreach (self::$BOM as $bomString => $bomByteLength) {
3112 2
      if ($str === $bomString) {
3113 2
        return true;
3114
      }
3115
    }
3116
3117 2
    return false;
3118
  }
3119
3120
  /**
3121
   * Determine whether the string is considered to be empty.
3122
   *
3123
   * A variable is considered empty if it does not exist or if its value equals FALSE.
3124
   * empty() does not generate a warning if the variable does not exist.
3125
   *
3126
   * @param mixed $str
3127
   *
3128
   * @return bool Whether or not $str is empty().
3129
   */
3130
  public static function is_empty($str): bool
3131
  {
3132
    return empty($str);
3133
  }
3134
3135
  /**
3136
   * Returns true if the string contains only hexadecimal chars, false otherwise.
3137
   *
3138
   * @param string $str
3139
   *
3140
   * @return bool
3141
   *               Whether or not $str contains only hexadecimal chars.
3142
   */
3143 13
  public static function is_hexadecimal(string $str): bool
3144
  {
3145 13
    return self::str_matches_pattern($str, '^[[:xdigit:]]*$');
3146
  }
3147
3148
  /**
3149
   * Check if the string contains any html-tags <lall>.
3150
   *
3151
   * @param string $str <p>The input string.</p>
3152
   *
3153
   * @return bool
3154
   */
3155 3
  public static function is_html(string $str): bool
3156
  {
3157 3
    if ('' === $str) {
3158 3
      return false;
3159
    }
3160
3161
    // init
3162 3
    $matches = [];
3163
3164 3
    \preg_match("/<\/?\w+(?:(?:\s+\w+(?:\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)*+\s*|\s*)\/?>/", $str, $matches);
3165
3166 3
    return !(\count($matches) === 0);
3167
  }
3168
3169
  /**
3170
   * Try to check if "$str" is an json-string.
3171
   *
3172
   * @param string $str <p>The input string.</p>
3173
   *
3174
   * @return bool
3175
   */
3176 22
  public static function is_json(string $str): bool
3177
  {
3178 22
    if ('' === $str) {
3179 3
      return false;
3180
    }
3181
3182 21
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3183
      self::checkForSupport();
3184
    }
3185
3186 21
    if (self::$SUPPORT['json'] === false) {
3187
      throw new \RuntimeException('ext-json: is not installed');
3188
    }
3189
3190 21
    $json = self::json_decode($str);
3191
3192
    /** @noinspection PhpComposerExtensionStubsInspection */
3193
    return (
3194 21
               \is_object($json) === true
3195
               ||
3196 21
               \is_array($json) === true
3197
           )
3198
           &&
3199 21
           \json_last_error() === JSON_ERROR_NONE;
3200
  }
3201
3202
  /**
3203
   * @param string $str
3204
   *
3205
   * @return bool
3206
   */
3207 8
  public static function is_lowercase(string $str): bool
3208
  {
3209 8
    if (self::str_matches_pattern($str, '^[[:lower:]]*$')) {
3210 3
      return true;
3211
    }
3212
3213 5
    return false;
3214
  }
3215
3216
  /**
3217
   * Returns true if the string is serialized, false otherwise.
3218
   *
3219
   * @param string $str
3220
   *
3221
   * @return bool Whether or not $str is serialized.
3222
   */
3223 7
  public static function is_serialized(string $str): bool
3224
  {
3225 7
    if ('' === $str) {
3226 1
      return false;
3227
    }
3228
3229
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
3230
    /** @noinspection UnserializeExploitsInspection */
3231 6
    return $str === 'b:0;'
3232
           ||
3233 6
           @\unserialize($str) !== false;
3234
  }
3235
3236
  /**
3237
   * Returns true if the string contains only lower case chars, false
3238
   * otherwise.
3239
   *
3240
   * @param string $str <p>The input string.</p>
3241
   *
3242
   * @return bool
3243
   *               Whether or not $str contains only lower case characters.
3244
   */
3245 8
  public static function is_uppercase(string $str): bool
3246
  {
3247 8
    return self::str_matches_pattern($str, '^[[:upper:]]*$');
3248
  }
3249
3250
  /**
3251
   * Check if the string is UTF-16.
3252
   *
3253
   * @param mixed $str <p>The input string.</p>
3254
   *
3255
   * @return int|false
3256
   *                   <strong>false</strong> if is't not UTF-16,<br>
3257
   *                   <strong>1</strong> for UTF-16LE,<br>
3258
   *                   <strong>2</strong> for UTF-16BE.
3259
   */
3260 21
  public static function is_utf16($str)
3261
  {
3262
    // init
3263 21
    $str = (string)$str;
3264
3265 21
    if (self::is_binary($str) === false) {
3266 9
      return false;
3267
    }
3268
3269 16
    if (self::$SUPPORT['mbstring'] === false) {
3270
      \trigger_error('UTF8::is_utf16() without mbstring may did not work correctly', E_USER_WARNING);
3271
    }
3272
3273
    // init
3274 16
    $strChars = [];
3275
3276 16
    $str = self::remove_bom($str);
3277
3278 16
    $maybeUTF16LE = 0;
3279 16
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16LE');
3280 16
    if ($test) {
3281 14
      $test2 = \mb_convert_encoding($test, 'UTF-16LE', 'UTF-8');
3282 14
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16LE');
3283 14
      if ($test3 === $test) {
3284 14
        if (\count($strChars) === 0) {
3285 14
          $strChars = self::count_chars($str, true);
3286
        }
3287 14
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3288 14
          if (\in_array($test3char, $strChars, true) === true) {
3289 14
            $maybeUTF16LE++;
3290
          }
3291
        }
3292
      }
3293
    }
3294
3295 16
    $maybeUTF16BE = 0;
3296 16
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-16BE');
3297 16
    if ($test) {
3298 14
      $test2 = \mb_convert_encoding($test, 'UTF-16BE', 'UTF-8');
3299 14
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-16BE');
3300 14
      if ($test3 === $test) {
3301 14
        if (\count($strChars) === 0) {
3302 6
          $strChars = self::count_chars($str, true);
3303
        }
3304 14
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3305 14
          if (\in_array($test3char, $strChars, true) === true) {
3306 14
            $maybeUTF16BE++;
3307
          }
3308
        }
3309
      }
3310
    }
3311
3312 16
    if ($maybeUTF16BE !== $maybeUTF16LE) {
3313 6
      if ($maybeUTF16LE > $maybeUTF16BE) {
3314 4
        return 1;
3315
      }
3316
3317 6
      return 2;
3318
    }
3319
3320 12
    return false;
3321
  }
3322
3323
  /**
3324
   * Check if the string is UTF-32.
3325
   *
3326
   * @param mixed $str
3327
   *
3328
   * @return int|false
3329
   *                   <strong>false</strong> if is't not UTF-32,<br>
3330
   *                   <strong>1</strong> for UTF-32LE,<br>
3331
   *                   <strong>2</strong> for UTF-32BE.
3332
   */
3333 17
  public static function is_utf32($str)
3334
  {
3335
    // init
3336 17
    $str = (string)$str;
3337
3338 17
    if (self::is_binary($str) === false) {
3339 9
      return false;
3340
    }
3341
3342 12
    if (self::$SUPPORT['mbstring'] === false) {
3343
      \trigger_error('UTF8::is_utf32() without mbstring may did not work correctly', E_USER_WARNING);
3344
    }
3345
3346
    // init
3347 12
    $strChars = [];
3348
3349 12
    $str = self::remove_bom($str);
3350
3351 12
    $maybeUTF32LE = 0;
3352 12
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32LE');
3353 12
    if ($test) {
3354 10
      $test2 = \mb_convert_encoding($test, 'UTF-32LE', 'UTF-8');
3355 10
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32LE');
3356 10
      if ($test3 === $test) {
3357 10
        if (\count($strChars) === 0) {
3358 10
          $strChars = self::count_chars($str, true);
3359
        }
3360 10
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3361 10
          if (\in_array($test3char, $strChars, true) === true) {
3362 10
            $maybeUTF32LE++;
3363
          }
3364
        }
3365
      }
3366
    }
3367
3368 12
    $maybeUTF32BE = 0;
3369 12
    $test = \mb_convert_encoding($str, 'UTF-8', 'UTF-32BE');
3370 12
    if ($test) {
3371 10
      $test2 = \mb_convert_encoding($test, 'UTF-32BE', 'UTF-8');
3372 10
      $test3 = \mb_convert_encoding($test2, 'UTF-8', 'UTF-32BE');
3373 10
      if ($test3 === $test) {
3374 10
        if (\count($strChars) === 0) {
3375 6
          $strChars = self::count_chars($str, true);
3376
        }
3377 10
        foreach (self::count_chars($test3, true) as $test3char => $test3charEmpty) {
3378 10
          if (\in_array($test3char, $strChars, true) === true) {
3379 10
            $maybeUTF32BE++;
3380
          }
3381
        }
3382
      }
3383
    }
3384
3385 12
    if ($maybeUTF32BE !== $maybeUTF32LE) {
3386 2
      if ($maybeUTF32LE > $maybeUTF32BE) {
3387 2
        return 1;
3388
      }
3389
3390 2
      return 2;
3391
    }
3392
3393 12
    return false;
3394
  }
3395
3396
  /**
3397
   * Checks whether the passed string contains only byte sequences that appear valid UTF-8 characters.
3398
   *
3399
   * @see    http://hsivonen.iki.fi/php-utf8/
3400
   *
3401
   * @param string|string[] $str    <p>The string to be checked.</p>
3402
   * @param bool            $strict <p>Check also if the string is not UTF-16 or UTF-32.</p>
3403
   *
3404
   * @return bool
3405
   */
3406 107
  public static function is_utf8($str, bool $strict = false): bool
3407
  {
3408 107
    if (\is_array($str) === true) {
3409 2
      foreach ($str as $k => $v) {
3410 2
        if (false === self::is_utf8($v, $strict)) {
3411 2
          return false;
3412
        }
3413
      }
3414
3415
      return true;
3416
    }
3417
3418 107
    if ('' === $str) {
3419 12
      return true;
3420
    }
3421
3422 103
    if ($strict === true) {
3423 2
      if (self::is_utf16($str) !== false) {
3424 2
        return false;
3425
      }
3426
3427
      if (self::is_utf32($str) !== false) {
3428
        return false;
3429
      }
3430
    }
3431
3432 103
    if (self::pcre_utf8_support() !== true) {
3433
3434
      // If even just the first character can be matched, when the /u
3435
      // modifier is used, then it's valid UTF-8. If the UTF-8 is somehow
3436
      // invalid, nothing at all will match, even if the string contains
3437
      // some valid sequences
3438
      return (\preg_match('/^.{1}/us', $str, $ar) === 1);
3439
    }
3440
3441 103
    $mState = 0; // cached expected number of octets after the current octet
3442
    // until the beginning of the next UTF8 character sequence
3443 103
    $mUcs4 = 0; // cached Unicode character
3444 103
    $mBytes = 1; // cached expected number of octets in the current sequence
3445
3446 103
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3447
      self::checkForSupport();
3448
    }
3449
3450 103
    if (self::$ORD === null) {
3451
      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 null|array. 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...
3452
    }
3453
3454 103
    $len = self::strlen_in_byte((string)$str);
3455
    /** @noinspection ForeachInvariantsInspection */
3456 103
    for ($i = 0; $i < $len; $i++) {
3457 103
      $in = self::$ORD[$str[$i]];
3458 103
      if ($mState === 0) {
3459
        // When mState is zero we expect either a US-ASCII character or a
3460
        // multi-octet sequence.
3461 103
        if (0 === (0x80 & $in)) {
3462
          // US-ASCII, pass straight through.
3463 98
          $mBytes = 1;
3464 84
        } elseif (0xC0 === (0xE0 & $in)) {
3465
          // First octet of 2 octet sequence.
3466 75
          $mUcs4 = $in;
3467 75
          $mUcs4 = ($mUcs4 & 0x1F) << 6;
3468 75
          $mState = 1;
3469 75
          $mBytes = 2;
3470 58
        } elseif (0xE0 === (0xF0 & $in)) {
3471
          // First octet of 3 octet sequence.
3472 41
          $mUcs4 = $in;
3473 41
          $mUcs4 = ($mUcs4 & 0x0F) << 12;
3474 41
          $mState = 2;
3475 41
          $mBytes = 3;
3476 30
        } elseif (0xF0 === (0xF8 & $in)) {
3477
          // First octet of 4 octet sequence.
3478 19
          $mUcs4 = $in;
3479 19
          $mUcs4 = ($mUcs4 & 0x07) << 18;
3480 19
          $mState = 3;
3481 19
          $mBytes = 4;
3482 13
        } elseif (0xF8 === (0xFC & $in)) {
3483
          /* First octet of 5 octet sequence.
3484
          *
3485
          * This is illegal because the encoded codepoint must be either
3486
          * (a) not the shortest form or
3487
          * (b) outside the Unicode range of 0-0x10FFFF.
3488
          * Rather than trying to resynchronize, we will carry on until the end
3489
          * of the sequence and let the later error handling code catch it.
3490
          */
3491 5
          $mUcs4 = $in;
3492 5
          $mUcs4 = ($mUcs4 & 0x03) << 24;
3493 5
          $mState = 4;
3494 5
          $mBytes = 5;
3495 10
        } elseif (0xFC === (0xFE & $in)) {
3496
          // First octet of 6 octet sequence, see comments for 5 octet sequence.
3497 5
          $mUcs4 = $in;
3498 5
          $mUcs4 = ($mUcs4 & 1) << 30;
3499 5
          $mState = 5;
3500 5
          $mBytes = 6;
3501
        } else {
3502
          // Current octet is neither in the US-ASCII range nor a legal first
3503
          // octet of a multi-octet sequence.
3504 103
          return false;
3505
        }
3506
      } else {
3507
        // When mState is non-zero, we expect a continuation of the multi-octet
3508
        // sequence
3509 84
        if (0x80 === (0xC0 & $in)) {
3510
          // Legal continuation.
3511 76
          $shift = ($mState - 1) * 6;
3512 76
          $tmp = $in;
3513 76
          $tmp = ($tmp & 0x0000003F) << $shift;
3514 76
          $mUcs4 |= $tmp;
3515
          // Prefix: End of the multi-octet sequence. mUcs4 now contains the final
3516
          // Unicode code point to be output.
3517 76
          if (0 === --$mState) {
3518
            // Check for illegal sequences and code points.
3519
            //
3520
            // From Unicode 3.1, non-shortest form is illegal
3521
            if (
3522 76
                (2 === $mBytes && $mUcs4 < 0x0080)
3523
                ||
3524 76
                (3 === $mBytes && $mUcs4 < 0x0800)
3525
                ||
3526 76
                (4 === $mBytes && $mUcs4 < 0x10000)
3527
                ||
3528 76
                (4 < $mBytes)
3529
                ||
3530
                // From Unicode 3.2, surrogate characters are illegal.
3531 76
                (($mUcs4 & 0xFFFFF800) === 0xD800)
3532
                ||
3533
                // Code points outside the Unicode range are illegal.
3534 76
                ($mUcs4 > 0x10FFFF)
3535
            ) {
3536 8
              return false;
3537
            }
3538
            // initialize UTF8 cache
3539 76
            $mState = 0;
3540 76
            $mUcs4 = 0;
3541 76
            $mBytes = 1;
3542
          }
3543
        } else {
3544
          // ((0xC0 & (*in) != 0x80) && (mState != 0))
3545
          // Incomplete multi-octet sequence.
3546 36
          return false;
3547
        }
3548
      }
3549
    }
3550
3551 67
    return true;
3552
  }
3553
3554
  /**
3555
   * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3556
   * Decodes a JSON string
3557
   *
3558
   * @link http://php.net/manual/en/function.json-decode.php
3559
   *
3560
   * @param string $json    <p>
3561
   *                        The <i>json</i> string being decoded.
3562
   *                        </p>
3563
   *                        <p>
3564
   *                        This function only works with UTF-8 encoded strings.
3565
   *                        </p>
3566
   *                        <p>PHP implements a superset of
3567
   *                        JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3568
   *                        only supports these values when they are nested inside an array or an object.
3569
   *                        </p>
3570
   * @param bool   $assoc   [optional] <p>
3571
   *                        When <b>TRUE</b>, returned objects will be converted into
3572
   *                        associative arrays.
3573
   *                        </p>
3574
   * @param int    $depth   [optional] <p>
3575
   *                        User specified recursion depth.
3576
   *                        </p>
3577
   * @param int    $options [optional] <p>
3578
   *                        Bitmask of JSON decode options. Currently only
3579
   *                        <b>JSON_BIGINT_AS_STRING</b>
3580
   *                        is supported (default is to cast large integers as floats)
3581
   *                        </p>
3582
   *
3583
   * @return mixed
3584
   *                The value encoded in <i>json</i> in appropriate PHP type. Values true, false and
3585
   *                null (case-insensitive) are returned as <b>TRUE</b>, <b>FALSE</b> and <b>NULL</b> respectively.
3586
   *                <b>NULL</b> is returned if the <i>json</i> cannot be decoded or if the encoded data
3587
   *                is deeper than the recursion limit.
3588
   */
3589 23
  public static function json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0)
3590
  {
3591 23
    $json = self::filter($json);
3592
3593 23
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3594
      self::checkForSupport();
3595
    }
3596
3597 23
    if (self::$SUPPORT['json'] === false) {
3598
      throw new \RuntimeException('ext-json: is not installed');
3599
    }
3600
3601
    /** @noinspection PhpComposerExtensionStubsInspection */
3602 23
    $json = \json_decode($json, $assoc, $depth, $options);
3603
3604 23
    return $json;
3605
  }
3606
3607
  /**
3608
   * (PHP 5 &gt;= 5.2.0, PECL json &gt;= 1.2.0)<br/>
3609
   * Returns the JSON representation of a value.
3610
   *
3611
   * @link http://php.net/manual/en/function.json-encode.php
3612
   *
3613
   * @param mixed $value   <p>
3614
   *                       The <i>value</i> being encoded. Can be any type except
3615
   *                       a resource.
3616
   *                       </p>
3617
   *                       <p>
3618
   *                       All string data must be UTF-8 encoded.
3619
   *                       </p>
3620
   *                       <p>PHP implements a superset of
3621
   *                       JSON - it will also encode and decode scalar types and <b>NULL</b>. The JSON standard
3622
   *                       only supports these values when they are nested inside an array or an object.
3623
   *                       </p>
3624
   * @param int   $options [optional] <p>
3625
   *                       Bitmask consisting of <b>JSON_HEX_QUOT</b>,
3626
   *                       <b>JSON_HEX_TAG</b>,
3627
   *                       <b>JSON_HEX_AMP</b>,
3628
   *                       <b>JSON_HEX_APOS</b>,
3629
   *                       <b>JSON_NUMERIC_CHECK</b>,
3630
   *                       <b>JSON_PRETTY_PRINT</b>,
3631
   *                       <b>JSON_UNESCAPED_SLASHES</b>,
3632
   *                       <b>JSON_FORCE_OBJECT</b>,
3633
   *                       <b>JSON_UNESCAPED_UNICODE</b>. The behaviour of these
3634
   *                       constants is described on
3635
   *                       the JSON constants page.
3636
   *                       </p>
3637
   * @param int   $depth   [optional] <p>
3638
   *                       Set the maximum depth. Must be greater than zero.
3639
   *                       </p>
3640
   *
3641
   * @return string|false
3642
   *                      A JSON encoded <strong>string</strong> on success or<br>
3643
   *                      <strong>FALSE</strong> on failure.
3644
   */
3645 4
  public static function json_encode($value, int $options = 0, int $depth = 512)
3646
  {
3647 4
    $value = self::filter($value);
3648
3649 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
3650
      self::checkForSupport();
3651
    }
3652
3653 4
    if (self::$SUPPORT['json'] === false) {
3654
      throw new \RuntimeException('ext-json: is not installed');
3655
    }
3656
3657
    /** @noinspection PhpComposerExtensionStubsInspection */
3658 4
    $json = \json_encode($value, $options, $depth);
3659
3660 4
    return $json;
3661
  }
3662
3663
  /**
3664
   * Checks whether JSON is available on the server.
3665
   *
3666
   * @return bool
3667
   *              <strong>true</strong> if available, <strong>false</strong> otherwise
3668
   */
3669
  public static function json_loaded(): bool
3670
  {
3671
    return \function_exists('json_decode');
3672
  }
3673
3674
  /**
3675
   * Makes string's first char lowercase.
3676
   *
3677
   * @param string $str       <p>The input string</p>
3678
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
3679
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
3680
   *
3681
   * @return string The resulting string.
3682
   */
3683 46
  public static function lcfirst(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
3684
  {
3685 46
    $strPartTwo = self::substr($str, 1, null, $encoding, $cleanUtf8);
3686 46
    if ($strPartTwo === false) {
3687
      $strPartTwo = '';
3688
    }
3689
3690 46
    $strPartOne = self::strtolower(
3691 46
        (string)self::substr($str, 0, 1, $encoding, $cleanUtf8),
3692 46
        $encoding,
3693 46
        $cleanUtf8
3694
    );
3695
3696 46
    return $strPartOne . $strPartTwo;
3697
  }
3698
3699
  /**
3700
   * alias for "UTF8::lcfirst()"
3701
   *
3702
   * @see UTF8::lcfirst()
3703
   *
3704
   * @param string $str
3705
   * @param string $encoding
3706
   * @param bool   $cleanUtf8
3707
   *
3708
   * @return string
3709
   */
3710 2
  public static function lcword(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
3711
  {
3712 2
    return self::lcfirst($str, $encoding, $cleanUtf8);
3713
  }
3714
3715
  /**
3716
   * Lowercase for all words in the string.
3717
   *
3718
   * @param string   $str        <p>The input string.</p>
3719
   * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
3720
   * @param string   $charlist   [optional] <p>Additional chars that contains to words and do not start a new word.</p>
3721
   * @param string   $encoding   [optional] <p>Set the charset.</p>
3722
   * @param bool     $cleanUtf8  [optional] <p>Remove non UTF-8 chars from the string.</p>
3723
   *
3724
   * @return string
3725
   */
3726 2
  public static function lcwords(string $str, array $exceptions = [], string $charlist = '', string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
3727
  {
3728 2
    if (!$str) {
3729 2
      return '';
3730
    }
3731
3732 2
    $words = self::str_to_words($str, $charlist);
3733 2
    $newWords = [];
3734
3735 2
    if (\count($exceptions) > 0) {
3736 2
      $useExceptions = true;
3737
    } else {
3738 2
      $useExceptions = false;
3739
    }
3740
3741 2
    foreach ($words as $word) {
3742
3743 2
      if (!$word) {
3744 2
        continue;
3745
      }
3746
3747
      if (
3748 2
          $useExceptions === false
3749
          ||
3750
          (
3751 2
              $useExceptions === true
3752
              &&
3753 2
              !\in_array($word, $exceptions, true)
3754
          )
3755
      ) {
3756 2
        $word = self::lcfirst($word, $encoding, $cleanUtf8);
3757
      }
3758
3759 2
      $newWords[] = $word;
3760
    }
3761
3762 2
    return \implode('', $newWords);
3763
  }
3764
3765
  /**
3766
   * alias for "UTF8::lcfirst()"
3767
   *
3768
   * @see UTF8::lcfirst()
3769
   *
3770
   * @param string $str
3771
   * @param string $encoding
3772
   * @param bool   $cleanUtf8
3773
   *
3774
   * @return string
3775
   */
3776 5
  public static function lowerCaseFirst(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
3777
  {
3778 5
    return self::lcfirst($str, $encoding, $cleanUtf8);
3779
  }
3780
3781
  /**
3782
   * Strip whitespace or other characters from beginning of a UTF-8 string.
3783
   *
3784
   * @param string $str   <p>The string to be trimmed</p>
3785
   * @param mixed  $chars <p>Optional characters to be stripped</p>
3786
   *
3787
   * @return string The string with unwanted characters stripped from the left.
3788
   */
3789 22
  public static function ltrim(string $str = '', $chars = INF): string
3790
  {
3791 22
    if ('' === $str) {
3792 3
      return '';
3793
    }
3794
3795
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
3796 21
    if ($chars === INF || !$chars) {
3797 14
      $pattern = "^[\pZ\pC]+";
3798
    } else {
3799 10
      $chars = \preg_quote($chars, '/');
3800 10
      $pattern = "^[$chars]+";
3801
    }
3802
3803 21
    return self::regex_replace($str, $pattern, '', '', '/');
3804
  }
3805
3806
  /**
3807
   * Returns the UTF-8 character with the maximum code point in the given data.
3808
   *
3809
   * @param string|array<string> $arg <p>A UTF-8 encoded string or an array of such strings.</p>
3810
   *
3811
   * @return string|null The character with the highest code point than others, returns null on failure or empty input.
3812
   */
3813 2
  public static function max($arg)
3814
  {
3815 2
    if (\is_array($arg) === true) {
3816 2
      $arg = \implode('', $arg);
3817
    }
3818
3819 2
    $codepoints = self::codepoints($arg, false);
3820 2
    if (\count($codepoints) === 0) {
3821 2
      return null;
3822
    }
3823
3824 2
    $codepoint_max = \max($codepoints);
3825
3826 2
    return self::chr($codepoint_max);
3827
  }
3828
3829
  /**
3830
   * Calculates and returns the maximum number of bytes taken by any
3831
   * UTF-8 encoded character in the given string.
3832
   *
3833
   * @param string $str <p>The original Unicode string.</p>
3834
   *
3835
   * @return int Max byte lengths of the given chars.
3836
   */
3837 2
  public static function max_chr_width(string $str): int
3838
  {
3839 2
    $bytes = self::chr_size_list($str);
3840 2
    if (\count($bytes) > 0) {
3841 2
      return (int)\max($bytes);
3842
    }
3843
3844 2
    return 0;
3845
  }
3846
3847
  /**
3848
   * Checks whether mbstring is available on the server.
3849
   *
3850
   * @return bool
3851
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
3852
   */
3853 27
  public static function mbstring_loaded(): bool
3854
  {
3855 27
    $return = \extension_loaded('mbstring') ? true : false;
3856
3857 27
    if ($return === true) {
3858 27
      \mb_internal_encoding('UTF-8');
3859
    }
3860
3861 27
    return $return;
3862
  }
3863
3864
  /**
3865
   * Checks whether mbstring "overloaded" is active on the server.
3866
   *
3867
   * @return bool
3868
   */
3869
  private static function mbstring_overloaded(): bool
3870
  {
3871
    /**
3872
     * INI directive 'mbstring.func_overload' is deprecated since PHP 7.2
3873
     */
3874
3875
    /** @noinspection PhpComposerExtensionStubsInspection */
3876
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
3877
    return \defined('MB_OVERLOAD_STRING')
3878
           &&
3879
           (@\ini_get('mbstring.func_overload') & MB_OVERLOAD_STRING);
3880
  }
3881
3882
  /**
3883
   * Returns the UTF-8 character with the minimum code point in the given data.
3884
   *
3885
   * @param mixed $arg <strong>A UTF-8 encoded string or an array of such strings.</strong>
3886
   *
3887
   * @return string|null The character with the lowest code point than others, returns null on failure or empty input.
3888
   */
3889 2
  public static function min($arg)
3890
  {
3891 2
    if (\is_array($arg) === true) {
3892 2
      $arg = \implode('', $arg);
3893
    }
3894
3895 2
    $codepoints = self::codepoints($arg, false);
3896 2
    if (\count($codepoints) === 0) {
3897 2
      return null;
3898
    }
3899
3900 2
    $codepoint_min = \min($codepoints);
3901
3902 2
    return self::chr($codepoint_min);
3903
  }
3904
3905
  /**
3906
   * alias for "UTF8::normalize_encoding()"
3907
   *
3908
   * @see        UTF8::normalize_encoding()
3909
   *
3910
   * @param mixed $encoding
3911
   * @param mixed $fallback
3912
   *
3913
   * @return mixed
3914
   *
3915
   * @deprecated <p>use "UTF8::normalize_encoding()"</p>
3916
   */
3917 2
  public static function normalizeEncoding($encoding, $fallback = '')
3918
  {
3919 2
    return self::normalize_encoding($encoding, $fallback);
3920
  }
3921
3922
  /**
3923
   * Normalize the encoding-"name" input.
3924
   *
3925
   * @param mixed $encoding <p>e.g.: ISO, UTF8, WINDOWS-1251 etc.</p>
3926
   * @param mixed $fallback <p>e.g.: UTF-8</p>
3927
   *
3928
   * @return mixed e.g.: ISO-8859-1, UTF-8, WINDOWS-1251 etc.<br>Will return a empty string as fallback (by default)
3929
   */
3930 340
  public static function normalize_encoding($encoding, $fallback = '')
3931
  {
3932 340
    static $STATIC_NORMALIZE_ENCODING_CACHE = [];
3933
3934
    // init
3935 340
    $encoding = (string)$encoding;
3936
3937
    if (
3938 340
        !$encoding
3939
        ||
3940 49
        $encoding === '1' // only a fallback, for non "strict_types" usage ...
3941
        ||
3942 340
        $encoding === '0' // only a fallback, for non "strict_types" usage ...
3943
    ) {
3944 296
      return $fallback;
3945
    }
3946
3947
    if (
3948 48
        'UTF-8' === $encoding
3949
        ||
3950 48
        'UTF8' === $encoding
3951
    ) {
3952 21
      return 'UTF-8';
3953
    }
3954
3955
    if (
3956 41
        '8BIT' === $encoding
3957
        ||
3958 41
        'BINARY' === $encoding
3959
    ) {
3960
      return 'CP850';
3961
    }
3962
3963
    if (
3964 41
        'HTML' === $encoding
3965
        ||
3966 41
        'HTML-ENTITIES' === $encoding
3967
    ) {
3968 2
      return 'HTML-ENTITIES';
3969
    }
3970
3971 41
    if (isset($STATIC_NORMALIZE_ENCODING_CACHE[$encoding])) {
3972 39
      return $STATIC_NORMALIZE_ENCODING_CACHE[$encoding];
3973
    }
3974
3975 5
    if (self::$ENCODINGS === null) {
3976 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 null|array. 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...
3977
    }
3978
3979 5
    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

3979
    if (\in_array($encoding, /** @scrutinizer ignore-type */ self::$ENCODINGS, true)) {
Loading history...
3980 4
      $STATIC_NORMALIZE_ENCODING_CACHE[$encoding] = $encoding;
3981
3982 4
      return $encoding;
3983
    }
3984
3985 4
    $encodingOrig = $encoding;
3986 4
    $encoding = \strtoupper($encoding);
3987 4
    $encodingUpperHelper = \preg_replace('/[^a-zA-Z0-9\s]/', '', $encoding);
3988
3989
    $equivalences = [
3990 4
        'ISO8859'     => 'ISO-8859-1',
3991
        'ISO88591'    => 'ISO-8859-1',
3992
        'ISO'         => 'ISO-8859-1',
3993
        'LATIN'       => 'ISO-8859-1',
3994
        'LATIN1'      => 'ISO-8859-1', // Western European
3995
        'ISO88592'    => 'ISO-8859-2',
3996
        'LATIN2'      => 'ISO-8859-2', // Central European
3997
        'ISO88593'    => 'ISO-8859-3',
3998
        'LATIN3'      => 'ISO-8859-3', // Southern European
3999
        'ISO88594'    => 'ISO-8859-4',
4000
        'LATIN4'      => 'ISO-8859-4', // Northern European
4001
        'ISO88595'    => 'ISO-8859-5',
4002
        'ISO88596'    => 'ISO-8859-6', // Greek
4003
        'ISO88597'    => 'ISO-8859-7',
4004
        'ISO88598'    => 'ISO-8859-8', // Hebrew
4005
        'ISO88599'    => 'ISO-8859-9',
4006
        'LATIN5'      => 'ISO-8859-9', // Turkish
4007
        'ISO885911'   => 'ISO-8859-11',
4008
        'TIS620'      => 'ISO-8859-11', // Thai
4009
        'ISO885910'   => 'ISO-8859-10',
4010
        'LATIN6'      => 'ISO-8859-10', // Nordic
4011
        'ISO885913'   => 'ISO-8859-13',
4012
        'LATIN7'      => 'ISO-8859-13', // Baltic
4013
        'ISO885914'   => 'ISO-8859-14',
4014
        'LATIN8'      => 'ISO-8859-14', // Celtic
4015
        'ISO885915'   => 'ISO-8859-15',
4016
        'LATIN9'      => 'ISO-8859-15', // Western European (with some extra chars e.g. €)
4017
        'ISO885916'   => 'ISO-8859-16',
4018
        'LATIN10'     => 'ISO-8859-16', // Southeast European
4019
        'CP1250'      => 'WINDOWS-1250',
4020
        'WIN1250'     => 'WINDOWS-1250',
4021
        'WINDOWS1250' => 'WINDOWS-1250',
4022
        'CP1251'      => 'WINDOWS-1251',
4023
        'WIN1251'     => 'WINDOWS-1251',
4024
        'WINDOWS1251' => 'WINDOWS-1251',
4025
        'CP1252'      => 'WINDOWS-1252',
4026
        'WIN1252'     => 'WINDOWS-1252',
4027
        'WINDOWS1252' => 'WINDOWS-1252',
4028
        'CP1253'      => 'WINDOWS-1253',
4029
        'WIN1253'     => 'WINDOWS-1253',
4030
        'WINDOWS1253' => 'WINDOWS-1253',
4031
        'CP1254'      => 'WINDOWS-1254',
4032
        'WIN1254'     => 'WINDOWS-1254',
4033
        'WINDOWS1254' => 'WINDOWS-1254',
4034
        'CP1255'      => 'WINDOWS-1255',
4035
        'WIN1255'     => 'WINDOWS-1255',
4036
        'WINDOWS1255' => 'WINDOWS-1255',
4037
        'CP1256'      => 'WINDOWS-1256',
4038
        'WIN1256'     => 'WINDOWS-1256',
4039
        'WINDOWS1256' => 'WINDOWS-1256',
4040
        'CP1257'      => 'WINDOWS-1257',
4041
        'WIN1257'     => 'WINDOWS-1257',
4042
        'WINDOWS1257' => 'WINDOWS-1257',
4043
        'CP1258'      => 'WINDOWS-1258',
4044
        'WIN1258'     => 'WINDOWS-1258',
4045
        'WINDOWS1258' => 'WINDOWS-1258',
4046
        'UTF16'       => 'UTF-16',
4047
        'UTF32'       => 'UTF-32',
4048
        'UTF8'        => 'UTF-8',
4049
        'UTF'         => 'UTF-8',
4050
        'UTF7'        => 'UTF-7',
4051
        '8BIT'        => 'CP850',
4052
        'BINARY'      => 'CP850',
4053
    ];
4054
4055 4
    if (!empty($equivalences[$encodingUpperHelper])) {
4056 4
      $encoding = $equivalences[$encodingUpperHelper];
4057
    }
4058
4059 4
    $STATIC_NORMALIZE_ENCODING_CACHE[$encodingOrig] = $encoding;
4060
4061 4
    return $encoding;
4062
  }
4063
4064
  /**
4065
   * Standardize line ending to unix-like.
4066
   *
4067
   * @param string $str
4068
   *
4069
   * @return string
4070
   */
4071 5
  public static function normalize_line_ending(string $str): string
4072
  {
4073 5
    return (string)str_replace(["\r\n", "\r"], "\n", $str);
4074
  }
4075
4076
  /**
4077
   * Normalize some MS Word special characters.
4078
   *
4079
   * @param string $str <p>The string to be normalized.</p>
4080
   *
4081
   * @return string
4082
   */
4083 39
  public static function normalize_msword(string $str): string
4084
  {
4085 39
    if ('' === $str) {
4086 2
      return '';
4087
    }
4088
4089 39
    static $UTF8_MSWORD_KEYS_CACHE = null;
4090 39
    static $UTF8_MSWORD_VALUES_CACHE = null;
4091
4092 39
    if ($UTF8_MSWORD_KEYS_CACHE === null) {
4093
4094 1
      if (self::$UTF8_MSWORD === null) {
4095 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 null|array. 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...
4096
      }
4097
4098 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

4098
      $UTF8_MSWORD_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$UTF8_MSWORD);
Loading history...
4099 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

4099
      $UTF8_MSWORD_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$UTF8_MSWORD);
Loading history...
4100
    }
4101
4102 39
    return \str_replace($UTF8_MSWORD_KEYS_CACHE, $UTF8_MSWORD_VALUES_CACHE, $str);
4103
  }
4104
4105
  /**
4106
   * Normalize the whitespace.
4107
   *
4108
   * @param string $str                     <p>The string to be normalized.</p>
4109
   * @param bool   $keepNonBreakingSpace    [optional] <p>Set to true, to keep non-breaking-spaces.</p>
4110
   * @param bool   $keepBidiUnicodeControls [optional] <p>Set to true, to keep non-printable (for the web)
4111
   *                                        bidirectional text chars.</p>
4112
   *
4113
   * @return string
4114
   */
4115 87
  public static function normalize_whitespace(string $str, bool $keepNonBreakingSpace = false, bool $keepBidiUnicodeControls = false): string
4116
  {
4117 87
    if ('' === $str) {
4118 9
      return '';
4119
    }
4120
4121 87
    static $WHITESPACE_CACHE = [];
4122 87
    $cacheKey = (int)$keepNonBreakingSpace;
4123
4124 87
    if (!isset($WHITESPACE_CACHE[$cacheKey])) {
4125
4126 2
      $WHITESPACE_CACHE[$cacheKey] = self::$WHITESPACE_TABLE;
4127
4128 2
      if ($keepNonBreakingSpace === true) {
4129 1
        unset($WHITESPACE_CACHE[$cacheKey]['NO-BREAK SPACE']);
4130
      }
4131
4132 2
      $WHITESPACE_CACHE[$cacheKey] = \array_values($WHITESPACE_CACHE[$cacheKey]);
4133
    }
4134
4135 87
    if ($keepBidiUnicodeControls === false) {
4136 87
      static $BIDI_UNICODE_CONTROLS_CACHE = null;
4137
4138 87
      if ($BIDI_UNICODE_CONTROLS_CACHE === null) {
4139 1
        $BIDI_UNICODE_CONTROLS_CACHE = \array_values(self::$BIDI_UNI_CODE_CONTROLS_TABLE);
4140
      }
4141
4142 87
      $str = \str_replace($BIDI_UNICODE_CONTROLS_CACHE, '', $str);
4143
    }
4144
4145 87
    return \str_replace($WHITESPACE_CACHE[$cacheKey], ' ', $str);
4146
  }
4147
4148
  /**
4149
   * Calculates Unicode code point of the given UTF-8 encoded character.
4150
   *
4151
   * INFO: opposite to UTF8::chr()
4152
   *
4153
   * @param string $chr      <p>The character of which to calculate code point.<p/>
4154
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
4155
   *
4156
   * @return int
4157
   *             Unicode code point of the given character,<br>
4158
   *             0 on invalid UTF-8 byte sequence.
4159
   */
4160 35
  public static function ord($chr, string $encoding = 'UTF-8'): int
4161
  {
4162
    // init
4163 35
    $chr = (string)$chr;
4164
4165 35
    static $CHAR_CACHE = [];
4166
4167
    // save the original string
4168 35
    $chr_orig = $chr;
4169
4170 35
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4171 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
4172
4173
      // check again, if it's still not UTF-8
4174 4
      if ($encoding !== 'UTF-8') {
4175 4
        $chr = self::encode($encoding, $chr);
4176
      }
4177
    }
4178
4179 35
    $cacheKey = $chr_orig . $encoding;
4180 35
    if (isset($CHAR_CACHE[$cacheKey]) === true) {
4181 35
      return $CHAR_CACHE[$cacheKey];
4182
    }
4183
4184 12
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4185
      self::checkForSupport();
4186
    }
4187
4188 12
    if (self::$SUPPORT['intlChar'] === true) {
4189
      /** @noinspection PhpComposerExtensionStubsInspection */
4190 12
      $code = \IntlChar::ord($chr);
4191 12
      if ($code) {
4192 11
        return $CHAR_CACHE[$cacheKey] = $code;
4193
      }
4194
    }
4195
4196
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
4197 4
    $chr = \unpack('C*', (string)self::substr($chr, 0, 4, 'CP850'));
0 ignored issues
show
Bug introduced by
$chr of type array is incompatible with the type string expected by parameter $str of voku\helper\UTF8::substr(). ( Ignorable by Annotation )

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

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

4587
          /** @scrutinizer ignore-type */ self::strlen($substring, $encoding),
Loading history...
4588 6
          null,
4589 6
          $encoding
4590
      );
4591
    }
4592
4593 6
    return $str;
4594
  }
4595
4596
  /**
4597
   * Returns a new string with the suffix $substring removed, if present.
4598
   *
4599
   * @param string $str
4600
   * @param string $substring <p>The suffix to remove.</p>
4601
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
4602
   *
4603
   * @return string String having a $str without the suffix $substring.
4604
   */
4605 12
  public static function remove_right(string $str, string $substring, string $encoding = 'UTF-8'): string
4606
  {
4607 12
    if (self::str_ends_with($str, $substring)) {
4608
4609 6
      return (string)self::substr(
4610 6
          $str,
4611 6
          0,
4612 6
          self::strlen($str, $encoding) - self::strlen($substring, $encoding)
4613
      );
4614
    }
4615
4616 6
    return $str;
4617
  }
4618
4619
  /**
4620
   * Replaces all occurrences of $search in $str by $replacement.
4621
   *
4622
   * @param string $str           <p>The input string.</p>
4623
   * @param string $search        <p>The needle to search for.</p>
4624
   * @param string $replacement   <p>The string to replace with.</p>
4625
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4626
   *
4627
   * @return string String after the replacements.
4628
   */
4629 29
  public static function replace(string $str, string $search, string $replacement, bool $caseSensitive = true): string
4630
  {
4631 29
    if ($caseSensitive) {
4632 22
      return self::str_replace($search, $replacement, $str);
4633
    }
4634
4635 7
    return self::str_ireplace($search, $replacement, $str);
4636
  }
4637
4638
  /**
4639
   * Replaces all occurrences of $search in $str by $replacement.
4640
   *
4641
   * @param string       $str           <p>The input string.</p>
4642
   * @param array        $search        <p>The elements to search for.</p>
4643
   * @param string|array $replacement   <p>The string to replace with.</p>
4644
   * @param bool         $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
4645
   *
4646
   * @return string String after the replacements.
4647
   */
4648 30
  public static function replace_all(string $str, array $search, $replacement, bool $caseSensitive = true): string
4649
  {
4650 30
    if ($caseSensitive) {
4651 23
      return self::str_replace($search, $replacement, $str);
4652
    }
4653
4654 7
    return self::str_ireplace($search, $replacement, $str);
4655
  }
4656
4657
  /**
4658
   * Replace the diamond question mark (�) and invalid-UTF8 chars with the replacement.
4659
   *
4660
   * @param string $str                <p>The input string</p>
4661
   * @param string $replacementChar    <p>The replacement character.</p>
4662
   * @param bool   $processInvalidUtf8 <p>Convert invalid UTF-8 chars </p>
4663
   *
4664
   * @return string
4665
   */
4666 63
  public static function replace_diamond_question_mark(string $str, string $replacementChar = '', bool $processInvalidUtf8 = true): string
4667
  {
4668 63
    if ('' === $str) {
4669 9
      return '';
4670
    }
4671
4672 63
    if ($processInvalidUtf8 === true) {
4673 63
      $replacementCharHelper = $replacementChar;
4674 63
      if ($replacementChar === '') {
4675 63
        $replacementCharHelper = 'none';
4676
      }
4677
4678 63
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4679
        self::checkForSupport();
4680
      }
4681
4682 63
      if (self::$SUPPORT['mbstring'] === false) {
4683
        // if there is no native support for "mbstring",
4684
        // then we need to clean the string before ...
4685
        $str = self::clean($str);
4686
      }
4687
4688
      // always fallback via symfony polyfill
4689 63
      $save = \mb_substitute_character();
4690 63
      \mb_substitute_character($replacementCharHelper);
4691 63
      $strTmp = \mb_convert_encoding($str, 'UTF-8', 'UTF-8');
4692 63
      \mb_substitute_character($save);
4693
4694 63
      if (\is_string($strTmp)) {
0 ignored issues
show
introduced by
The condition is_string($strTmp) is always true.
Loading history...
4695 63
        $str = $strTmp;
4696
      } else {
4697
        $str = '';
4698
      }
4699
    }
4700
4701 63
    return str_replace(
4702
        [
4703 63
            "\xEF\xBF\xBD",
4704
            '�',
4705
        ],
4706
        [
4707 63
            $replacementChar,
4708 63
            $replacementChar,
4709
        ],
4710 63
        $str
4711
    );
4712
  }
4713
4714
  /**
4715
   * Strip whitespace or other characters from end of a UTF-8 string.
4716
   *
4717
   * @param string $str   <p>The string to be trimmed.</p>
4718
   * @param mixed  $chars <p>Optional characters to be stripped.</p>
4719
   *
4720
   * @return string The string with unwanted characters stripped from the right.
4721
   */
4722 22
  public static function rtrim(string $str = '', $chars = INF): string
4723
  {
4724 22
    if ('' === $str) {
4725 3
      return '';
4726
    }
4727
4728
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
4729 21
    if ($chars === INF || !$chars) {
4730 16
      $pattern = "[\pZ\pC]+\$";
4731
    } else {
4732 8
      $chars = \preg_quote($chars, '/');
4733 8
      $pattern = "[$chars]+\$";
4734
    }
4735
4736 21
    return self::regex_replace($str, $pattern, '', '', '/');
4737
  }
4738
4739
  /**
4740
   * rxClass
4741
   *
4742
   * @param string $s
4743
   * @param string $class
4744
   *
4745
   * @return string
4746
   */
4747 37
  private static function rxClass(string $s, string $class = ''): string
4748
  {
4749 37
    static $RX_CLASSS_CACHE = [];
4750
4751 37
    $cacheKey = $s . $class;
4752
4753 37
    if (isset($RX_CLASSS_CACHE[$cacheKey])) {
4754 25
      return $RX_CLASSS_CACHE[$cacheKey];
4755
    }
4756
4757
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
4758 16
    $class = [$class];
4759
4760
    /** @noinspection SuspiciousLoopInspection */
4761 16
    foreach (self::str_split($s) as $s) {
4762 15
      if ('-' === $s) {
4763
        $class[0] = '-' . $class[0];
4764 15
      } elseif (!isset($s[2])) {
4765 15
        $class[0] .= \preg_quote($s, '/');
4766 1
      } elseif (1 === self::strlen($s)) {
4767 1
        $class[0] .= $s;
4768
      } else {
4769 15
        $class[] = $s;
4770
      }
4771
    }
4772
4773 16
    if ($class[0]) {
4774 16
      $class[0] = '[' . $class[0] . ']';
4775
    }
4776
4777 16
    if (1 === \count($class)) {
4778 16
      $return = $class[0];
4779
    } else {
4780
      $return = '(?:' . \implode('|', $class) . ')';
4781
    }
4782
4783 16
    $RX_CLASSS_CACHE[$cacheKey] = $return;
4784
4785 16
    return $return;
4786
  }
4787
4788
  /**
4789
   * WARNING: Print native UTF-8 support (libs), e.g. for debugging.
4790
   */
4791 2
  public static function showSupport()
4792
  {
4793 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4794
      self::checkForSupport();
4795
    }
4796
4797 2
    echo '<pre>';
4798 2
    foreach (self::$SUPPORT as $key => $value) {
4799 2
      echo $key . ' - ' . \print_r($value, true) . "\n<br>";
4800
    }
4801 2
    echo '</pre>';
4802 2
  }
4803
4804
  /**
4805
   * Converts a UTF-8 character to HTML Numbered Entity like "&#123;".
4806
   *
4807
   * @param string $char           <p>The Unicode character to be encoded as numbered entity.</p>
4808
   * @param bool   $keepAsciiChars <p>Set to <strong>true</strong> to keep ASCII chars.</>
4809
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
4810
   *
4811
   * @return string The HTML numbered entity.
4812
   */
4813 2
  public static function single_chr_html_encode(string $char, bool $keepAsciiChars = false, string $encoding = 'UTF-8'): string
4814
  {
4815 2
    if ('' === $char) {
4816 2
      return '';
4817
    }
4818
4819
    if (
4820 2
        $keepAsciiChars === true
4821
        &&
4822 2
        self::is_ascii($char) === true
4823
    ) {
4824 2
      return $char;
4825
    }
4826
4827 2
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
4828 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
4829
    }
4830
4831 2
    return '&#' . self::ord($char, $encoding) . ';';
4832
  }
4833
4834
  /**
4835
   * @param string $str
4836
   * @param int    $tabLength
4837
   *
4838
   * @return string
4839
   */
4840 5
  public static function spaces_to_tabs(string $str, int $tabLength = 4): string
4841
  {
4842 5
    return \str_replace(\str_repeat(' ', $tabLength), "\t", $str);
4843
  }
4844
4845
  /**
4846
   * Convert a string to an array of Unicode characters.
4847
   *
4848
   * @param string|int|string[]|int[] $str       <p>The string to split into array.</p>
4849
   * @param int                       $length    [optional] <p>Max character length of each array element.</p>
4850
   * @param bool                      $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
4851
   *
4852
   * @return string[] An array containing chunks of the string.
4853
   */
4854 82
  public static function split($str, int $length = 1, bool $cleanUtf8 = false): array
4855
  {
4856 82
    if ($length <= 0) {
4857 3
      return [];
4858
    }
4859
4860 81
    if (\is_array($str) === true) {
4861 2
      foreach ($str as $k => $v) {
4862 2
        $str[$k] = self::split($v, $length);
4863
      }
4864
4865 2
      return $str;
4866
    }
4867
4868
    // init
4869 81
    $str = (string)$str;
4870
4871 81
    if ('' === $str) {
4872 13
      return [];
4873
    }
4874
4875
    // init
4876 78
    $ret = [];
4877
4878 78
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4879
      self::checkForSupport();
4880
    }
4881
4882 78
    if ($cleanUtf8 === true) {
4883 18
      $str = self::clean($str);
4884
    }
4885
4886 78
    if (self::$SUPPORT['pcre_utf8'] === true) {
4887
4888 78
      \preg_match_all('/./us', $str, $retArray);
4889 78
      if (isset($retArray[0])) {
4890 78
        $ret = $retArray[0];
4891
      }
4892 78
      unset($retArray);
4893
4894
    } else {
4895
4896
      // fallback
4897
4898
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
4899
        self::checkForSupport();
4900
      }
4901
4902
      $len = self::strlen_in_byte($str);
4903
4904
      /** @noinspection ForeachInvariantsInspection */
4905
      for ($i = 0; $i < $len; $i++) {
4906
4907
        if (($str[$i] & "\x80") === "\x00") {
4908
4909
          $ret[] = $str[$i];
4910
4911
        } elseif (
4912
            isset($str[$i + 1])
4913
            &&
4914
            ($str[$i] & "\xE0") === "\xC0"
4915
        ) {
4916
4917
          if (($str[$i + 1] & "\xC0") === "\x80") {
4918
            $ret[] = $str[$i] . $str[$i + 1];
4919
4920
            $i++;
4921
          }
4922
4923
        } elseif (
4924
            isset($str[$i + 2])
4925
            &&
4926
            ($str[$i] & "\xF0") === "\xE0"
4927
        ) {
4928
4929
          if (
4930
              ($str[$i + 1] & "\xC0") === "\x80"
4931
              &&
4932
              ($str[$i + 2] & "\xC0") === "\x80"
4933
          ) {
4934
            $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2];
4935
4936
            $i += 2;
4937
          }
4938
4939
        } elseif (
4940
            isset($str[$i + 3])
4941
            &&
4942
            ($str[$i] & "\xF8") === "\xF0"
4943
        ) {
4944
4945
          if (
4946
              ($str[$i + 1] & "\xC0") === "\x80"
4947
              &&
4948
              ($str[$i + 2] & "\xC0") === "\x80"
4949
              &&
4950
              ($str[$i + 3] & "\xC0") === "\x80"
4951
          ) {
4952
            $ret[] = $str[$i] . $str[$i + 1] . $str[$i + 2] . $str[$i + 3];
4953
4954
            $i += 3;
4955
          }
4956
4957
        }
4958
      }
4959
    }
4960
4961 78
    if ($length > 1) {
4962 11
      $ret = \array_chunk($ret, $length);
4963
4964 11
      return \array_map(
4965 11
          function ($item) {
4966 11
            return \implode('', $item);
4967 11
          }, $ret
4968
      );
4969
    }
4970
4971 71
    if (isset($ret[0]) && $ret[0] === '') {
4972
      return [];
4973
    }
4974
4975 71
    return $ret;
4976
  }
4977
4978
  /**
4979
   * Returns a camelCase version of the string. Trims surrounding spaces,
4980
   * capitalizes letters following digits, spaces, dashes and underscores,
4981
   * and removes spaces, dashes, as well as underscores.
4982
   *
4983
   * @param string $str      <p>The input string.</p>
4984
   * @param string $encoding [optional] <p>Default: UTF-8</p>
4985
   *
4986
   * @return string
4987
   */
4988 32
  public static function str_camelize(string $str, string $encoding = 'UTF-8'): string
4989
  {
4990 32
    $str = self::lcfirst(self::trim($str), $encoding);
4991 32
    $str = (string)\preg_replace('/^[-_]+/', '', $str);
4992
4993 32
    $str = (string)\preg_replace_callback(
4994 32
        '/[-_\s]+(.)?/u',
4995 32
        function ($match) use ($encoding) {
4996 27
          if (isset($match[1])) {
4997 27
            return UTF8::strtoupper($match[1], $encoding);
4998
          }
4999
5000 1
          return '';
5001 32
        },
5002 32
        $str
5003
    );
5004
5005 32
    $str = (string)\preg_replace_callback(
5006 32
        '/[\d]+(.)?/u',
5007 32
        function ($match) use ($encoding) {
5008 6
          return UTF8::strtoupper($match[0], $encoding);
5009 32
        },
5010 32
        $str
5011
    );
5012
5013 32
    return $str;
5014
  }
5015
5016
  /**
5017
   * Returns the string with the first letter of each word capitalized,
5018
   * except for when the word is a name which shouldn't be capitalized.
5019
   *
5020
   * @param string $str
5021
   *
5022
   * @return string String with $str capitalized.
5023
   */
5024 1
  public static function str_capitalize_name(string $str): string
5025
  {
5026 1
    $str = self::collapse_whitespace($str);
5027
5028 1
    $str = self::str_capitalize_name_helper($str, ' ');
5029 1
    $str = self::str_capitalize_name_helper($str, '-');
5030
5031 1
    return $str;
5032
  }
5033
5034
  /**
5035
   * Personal names such as "Marcus Aurelius" are sometimes typed incorrectly using lowercase ("marcus aurelius").
5036
   *
5037
   * @param string $names
5038
   * @param string $delimiter
5039
   * @param string $encoding
5040
   *
5041
   * @return string
5042
   */
5043 1
  private static function str_capitalize_name_helper(string $names, string $delimiter, string $encoding = 'UTF-8'): string
5044
  {
5045
    // init
5046 1
    $namesArray = \explode($delimiter, $names);
5047
5048 1
    if ($namesArray === false) {
5049
      return '';
5050
    }
5051
5052
    $specialCases = [
5053 1
        'names'    => [
5054
            'ab',
5055
            'af',
5056
            'al',
5057
            'and',
5058
            'ap',
5059
            'bint',
5060
            'binte',
5061
            'da',
5062
            'de',
5063
            'del',
5064
            'den',
5065
            'der',
5066
            'di',
5067
            'dit',
5068
            'ibn',
5069
            'la',
5070
            'mac',
5071
            'nic',
5072
            'of',
5073
            'ter',
5074
            'the',
5075
            'und',
5076
            'van',
5077
            'von',
5078
            'y',
5079
            'zu',
5080
        ],
5081
        'prefixes' => [
5082
            'al-',
5083
            "d'",
5084
            'ff',
5085
            "l'",
5086
            'mac',
5087
            'mc',
5088
            'nic',
5089
        ],
5090
    ];
5091
5092 1
    foreach ($namesArray as &$name) {
5093 1
      if (\in_array($name, $specialCases['names'], true)) {
5094 1
        continue;
5095
      }
5096
5097 1
      $continue = false;
5098
5099 1
      if ($delimiter == '-') {
5100 1
        foreach ($specialCases['names'] as $beginning) {
5101 1
          if (self::strpos($name, $beginning, 0, $encoding) === 0) {
5102 1
            $continue = true;
5103
          }
5104
        }
5105
      }
5106
5107 1
      foreach ($specialCases['prefixes'] as $beginning) {
5108 1
        if (self::strpos($name, $beginning, 0, $encoding) === 0) {
5109 1
          $continue = true;
5110
        }
5111
      }
5112
5113 1
      if ($continue) {
5114 1
        continue;
5115
      }
5116
5117 1
      $name = self::str_upper_first($name);
5118
    }
5119
5120 1
    return \implode($delimiter, $namesArray);
5121
  }
5122
5123
  /**
5124
   * Returns true if the string contains $needle, false otherwise. By default
5125
   * the comparison is case-sensitive, but can be made insensitive by setting
5126
   * $caseSensitive to false.
5127
   *
5128
   * @param string $haystack      <p>The input string.</p>
5129
   * @param string $needle        <p>Substring to look for.</p>
5130
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5131
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5132
   *
5133
   * @return bool Whether or not $haystack contains $needle.
5134
   */
5135 106
  public static function str_contains(string $haystack, string $needle, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5136
  {
5137 106
    if ('' === $haystack || '' === $needle) {
5138 1
      return false;
5139
    }
5140
5141
    // only a fallback to prevent BC in the api ...
5142 105
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
5143 2
      $encoding = (string)$caseSensitive;
5144
    }
5145
5146 105
    if ($caseSensitive) {
5147 55
      return (self::strpos($haystack, $needle, 0, $encoding) !== false);
5148
    }
5149
5150 50
    return (self::stripos($haystack, $needle, 0, $encoding) !== false);
5151
  }
5152
5153
  /**
5154
   * Returns true if the string contains all $needles, false otherwise. By
5155
   * default the comparison is case-sensitive, but can be made insensitive by
5156
   * setting $caseSensitive to false.
5157
   *
5158
   * @param string $haystack      <p>The input string.</p>
5159
   * @param array  $needles       <p>SubStrings to look for.</p>
5160
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5161
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5162
   *
5163
   * @return bool Whether or not $haystack contains $needle.
5164
   */
5165 44
  public static function str_contains_all(string $haystack, array $needles, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5166
  {
5167 44
    if ('' === $haystack) {
5168
      return false;
5169
    }
5170
5171 44
    if (empty($needles)) {
5172 1
      return false;
5173
    }
5174
5175
    // only a fallback to prevent BC in the api ...
5176 43
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
5177 1
      $encoding = (string)$caseSensitive;
5178
    }
5179
5180 43
    foreach ($needles as $needle) {
5181 43
      if (!self::str_contains($haystack, $needle, $caseSensitive, $encoding)) {
5182 43
        return false;
5183
      }
5184
    }
5185
5186 24
    return true;
5187
  }
5188
5189
  /**
5190
   * Returns true if the string contains any $needles, false otherwise. By
5191
   * default the comparison is case-sensitive, but can be made insensitive by
5192
   * setting $caseSensitive to false.
5193
   *
5194
   * @param string $haystack      <p>The input string.</p>
5195
   * @param array  $needles       <p>SubStrings to look for.</p>
5196
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
5197
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
5198
   *
5199
   * @return bool
5200
   *               Whether or not $str contains $needle.
5201
   */
5202 43
  public static function str_contains_any(string $haystack, array $needles, $caseSensitive = true, string $encoding = 'UTF-8'): bool
5203
  {
5204 43
    if (empty($needles)) {
5205 1
      return false;
5206
    }
5207
5208 42
    foreach ($needles as $needle) {
5209 42
      if (self::str_contains($haystack, $needle, $caseSensitive, $encoding)) {
5210 42
        return true;
5211
      }
5212
    }
5213
5214 18
    return false;
5215
  }
5216
5217
  /**
5218
   * Returns a lowercase and trimmed string separated by dashes. Dashes are
5219
   * inserted before uppercase characters (with the exception of the first
5220
   * character of the string), and in place of spaces as well as underscores.
5221
   *
5222
   * @param string $str      <p>The input string.</p>
5223
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5224
   *
5225
   * @return string
5226
   */
5227 19
  public static function str_dasherize(string $str, string $encoding = 'UTF-8'): string
5228
  {
5229 19
    return self::str_delimit($str, '-', $encoding);
5230
  }
5231
5232
  /**
5233
   * Returns a lowercase and trimmed string separated by the given delimiter.
5234
   * Delimiters are inserted before uppercase characters (with the exception
5235
   * of the first character of the string), and in place of spaces, dashes,
5236
   * and underscores. Alpha delimiters are not converted to lowercase.
5237
   *
5238
   * @param string $str       <p>The input string.</p>
5239
   * @param string $delimiter <p>Sequence used to separate parts of the string.</p>
5240
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5241
   *
5242
   * @return string
5243
   */
5244 49
  public static function str_delimit(string $str, string $delimiter, string $encoding = 'UTF-8'): string
5245
  {
5246 49
    $str = self::trim($str);
5247
5248 49
    $str = (string)\preg_replace('/\B([A-Z])/u', '-\1', $str);
5249
5250 49
    $str = self::strtolower($str, $encoding);
5251
5252 49
    return (string)\preg_replace('/[-_\s]+/u', $delimiter, $str);
5253
  }
5254
5255
  /**
5256
   * Optimized "mb_detect_encoding()"-function -> with support for UTF-16 and UTF-32.
5257
   *
5258
   * @param string $str <p>The input string.</p>
5259
   *
5260
   * @return false|string
5261
   *                      The detected string-encoding e.g. UTF-8 or UTF-16BE,<br>
5262
   *                      otherwise it will return false e.g. for BINARY or not detected encoding.
5263
   */
5264 32
  public static function str_detect_encoding($str)
5265
  {
5266
    // init
5267 32
    $str = (string)$str;
5268
5269
    //
5270
    // 1.) check binary strings (010001001...) like UTF-16 / UTF-32 / PDF / Images / ...
5271
    //
5272
5273 32
    if (self::is_binary($str, true) === true) {
5274
5275 11
      if (self::is_utf16($str) === 1) {
5276 2
        return 'UTF-16LE';
5277
      }
5278
5279 11
      if (self::is_utf16($str) === 2) {
5280 2
        return 'UTF-16BE';
5281
      }
5282
5283 9
      if (self::is_utf32($str) === 1) {
5284
        return 'UTF-32LE';
5285
      }
5286
5287 9
      if (self::is_utf32($str) === 2) {
5288
        return 'UTF-32BE';
5289
      }
5290
5291
      // is binary but not "UTF-16" or "UTF-32"
5292 9
      return false;
5293
    }
5294
5295
    //
5296
    // 2.) simple check for ASCII chars
5297
    //
5298
5299 27
    if (self::is_ascii($str) === true) {
5300 9
      return 'ASCII';
5301
    }
5302
5303
    //
5304
    // 3.) simple check for UTF-8 chars
5305
    //
5306
5307 27
    if (self::is_utf8($str) === true) {
5308 19
      return 'UTF-8';
5309
    }
5310
5311
    //
5312
    // 4.) check via "mb_detect_encoding()"
5313
    //
5314
    // INFO: UTF-16, UTF-32, UCS2 and UCS4, encoding detection will fail always with "mb_detect_encoding()"
5315
5316
    $detectOrder = [
5317 16
        'ISO-8859-1',
5318
        'ISO-8859-2',
5319
        'ISO-8859-3',
5320
        'ISO-8859-4',
5321
        'ISO-8859-5',
5322
        'ISO-8859-6',
5323
        'ISO-8859-7',
5324
        'ISO-8859-8',
5325
        'ISO-8859-9',
5326
        'ISO-8859-10',
5327
        'ISO-8859-13',
5328
        'ISO-8859-14',
5329
        'ISO-8859-15',
5330
        'ISO-8859-16',
5331
        'WINDOWS-1251',
5332
        'WINDOWS-1252',
5333
        'WINDOWS-1254',
5334
        'CP932',
5335
        'CP936',
5336
        'CP950',
5337
        'CP866',
5338
        'CP850',
5339
        'CP51932',
5340
        'CP50220',
5341
        'CP50221',
5342
        'CP50222',
5343
        'ISO-2022-JP',
5344
        'ISO-2022-KR',
5345
        'JIS',
5346
        'JIS-ms',
5347
        'EUC-CN',
5348
        'EUC-JP',
5349
    ];
5350
5351 16
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
5352
      self::checkForSupport();
5353
    }
5354
5355 16
    if (self::$SUPPORT['mbstring'] === true) {
5356
      // info: do not use the symfony polyfill here
5357 16
      $encoding = \mb_detect_encoding($str, $detectOrder, true);
5358 16
      if ($encoding) {
5359 16
        return $encoding;
5360
      }
5361
    }
5362
5363
    //
5364
    // 5.) check via "iconv()"
5365
    //
5366
5367
    if (self::$ENCODINGS === null) {
5368
      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 null|array. 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...
5369
    }
5370
5371
    foreach (self::$ENCODINGS as $encodingTmp) {
5372
      # INFO: //IGNORE but still throw notice
5373
      /** @noinspection PhpUsageOfSilenceOperatorInspection */
5374
      if ((string)@\iconv($encodingTmp, $encodingTmp . '//IGNORE', $str) === $str) {
5375
        return $encodingTmp;
5376
      }
5377
    }
5378
5379
    return false;
5380
  }
5381
5382
  /**
5383
   * Check if the string ends with the given substring.
5384
   *
5385
   * @param string $haystack <p>The string to search in.</p>
5386
   * @param string $needle   <p>The substring to search for.</p>
5387
   *
5388
   * @return bool
5389
   */
5390 40
  public static function str_ends_with(string $haystack, string $needle): bool
5391
  {
5392 40
    if ('' === $haystack || '' === $needle) {
5393 4
      return false;
5394
    }
5395
5396 38
    return \substr($haystack, -\strlen($needle)) === $needle;
5397
  }
5398
5399
  /**
5400
   * Returns true if the string ends with any of $substrings, false otherwise.
5401
   *
5402
   * - case-sensitive
5403
   *
5404
   * @param string   $str        <p>The input string.</p>
5405
   * @param string[] $substrings <p>Substrings to look for.</p>
5406
   *
5407
   * @return bool Whether or not $str ends with $substring.
5408
   */
5409 7
  public static function str_ends_with_any(string $str, array $substrings): bool
5410
  {
5411 7
    if (empty($substrings)) {
5412
      return false;
5413
    }
5414
5415 7
    foreach ($substrings as $substring) {
5416 7
      if (self::str_ends_with($str, $substring)) {
5417 7
        return true;
5418
      }
5419
    }
5420
5421 6
    return false;
5422
  }
5423
5424
  /**
5425
   * Ensures that the string begins with $substring. If it doesn't, it's
5426
   * prepended.
5427
   *
5428
   * @param string $str       <p>The input string.</p>
5429
   * @param string $substring <p>The substring to add if not present.</p>
5430
   *
5431
   * @return string
5432
   */
5433 10
  public static function str_ensure_left(string $str, string $substring): string
5434
  {
5435 10
    if (!self::str_starts_with($str, $substring)) {
5436 4
      $str = $substring . $str;
5437
    }
5438
5439 10
    return $str;
5440
  }
5441
5442
  /**
5443
   * Ensures that the string ends with $substring. If it doesn't, it's appended.
5444
   *
5445
   * @param string $str       <p>The input string.</p>
5446
   * @param string $substring <p>The substring to add if not present.</p>
5447
   *
5448
   * @return string
5449
   */
5450 10
  public static function str_ensure_right(string $str, string $substring): string
5451
  {
5452 10
    if (!self::str_ends_with($str, $substring)) {
5453 4
      $str .= $substring;
5454
    }
5455
5456 10
    return $str;
5457
  }
5458
5459
  /**
5460
   * Capitalizes the first word of the string, replaces underscores with
5461
   * spaces, and strips '_id'.
5462
   *
5463
   * @param string $str
5464
   *
5465
   * @return string
5466
   */
5467 3
  public static function str_humanize($str): string
5468
  {
5469 3
    $str = self::str_replace(
5470
        [
5471 3
            '_id',
5472
            '_',
5473
        ],
5474
        [
5475 3
            '',
5476
            ' ',
5477
        ],
5478 3
        $str
5479
    );
5480
5481 3
    return self::ucfirst(self::trim($str));
5482
  }
5483
5484
  /**
5485
   * Check if the string ends with the given substring, case insensitive.
5486
   *
5487
   * @param string $haystack <p>The string to search in.</p>
5488
   * @param string $needle   <p>The substring to search for.</p>
5489
   *
5490
   * @return bool
5491
   */
5492 12
  public static function str_iends_with(string $haystack, string $needle): bool
5493
  {
5494 12
    if ('' === $haystack || '' === $needle) {
5495 2
      return false;
5496
    }
5497
5498 12
    if (self::strcasecmp(\substr($haystack, -\strlen($needle)), $needle) === 0) {
5499 12
      return true;
5500
    }
5501
5502 8
    return false;
5503
  }
5504
5505
  /**
5506
   * Returns true if the string ends with any of $substrings, false otherwise.
5507
   *
5508
   * - case-insensitive
5509
   *
5510
   * @param string   $str        <p>The input string.</p>
5511
   * @param string[] $substrings <p>Substrings to look for.</p>
5512
   *
5513
   * @return bool Whether or not $str ends with $substring.
5514
   */
5515 4
  public static function str_iends_with_any(string $str, array $substrings): bool
5516
  {
5517 4
    if (empty($substrings)) {
5518
      return false;
5519
    }
5520
5521 4
    foreach ($substrings as $substring) {
5522 4
      if (self::str_iends_with($str, $substring)) {
5523 4
        return true;
5524
      }
5525
    }
5526
5527
    return false;
5528
  }
5529
5530
  /**
5531
   * Returns the index of the first occurrence of $needle in the string,
5532
   * and false if not found. Accepts an optional offset from which to begin
5533
   * the search.
5534
   *
5535
   * @param string $str      <p>The input string.</p>
5536
   * @param string $needle   <p>Substring to look for.</p>
5537
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5538
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5539
   *
5540
   * @return int|false
5541
   *                    The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5542
   */
5543 2
  public static function str_iindex_first(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5544
  {
5545 2
    return self::stripos(
5546 2
        $str,
5547 2
        $needle,
5548 2
        $offset,
5549 2
        $encoding
5550
    );
5551
  }
5552
5553
  /**
5554
   * Returns the index of the last occurrence of $needle in the string,
5555
   * and false if not found. Accepts an optional offset from which to begin
5556
   * the search. Offsets may be negative to count from the last character
5557
   * in the string.
5558
   *
5559
   * @param string $str      <p>The input string.</p>
5560
   * @param string $needle   <p>Substring to look for.</p>
5561
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5562
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5563
   *
5564
   * @return int|false
5565
   *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5566
   */
5567 2
  public static function str_iindex_last(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5568
  {
5569 2
    return self::strripos(
5570 2
        $str,
5571 2
        $needle,
5572 2
        $offset,
5573 2
        $encoding
5574
    );
5575
  }
5576
5577
  /**
5578
   * Returns the index of the first occurrence of $needle in the string,
5579
   * and false if not found. Accepts an optional offset from which to begin
5580
   * the search.
5581
   *
5582
   * @param string $str      <p>The input string.</p>
5583
   * @param string $needle   <p>Substring to look for.</p>
5584
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5585
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5586
   *
5587
   * @return int|false
5588
   *                   The occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5589
   */
5590 12
  public static function str_index_first(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5591
  {
5592 12
    return self::strpos(
5593 12
        $str,
5594 12
        $needle,
5595 12
        $offset,
5596 12
        $encoding
5597
    );
5598
  }
5599
5600
  /**
5601
   * Returns the index of the last occurrence of $needle in the string,
5602
   * and false if not found. Accepts an optional offset from which to begin
5603
   * the search. Offsets may be negative to count from the last character
5604
   * in the string.
5605
   *
5606
   * @param string $str      <p>The input string.</p>
5607
   * @param string $needle   <p>Substring to look for.</p>
5608
   * @param int    $offset   [optional] <p>Offset from which to search. Default: 0</p>
5609
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5610
   *
5611
   * @return int|false
5612
   *                   The last occurrence's <strong>index</strong> if found, otherwise <strong>false</strong>.
5613
   */
5614 12
  public static function str_index_last(string $str, string $needle, int $offset = 0, string $encoding = 'UTF-8')
5615
  {
5616 12
    return self::strrpos(
5617 12
        $str,
5618 12
        $needle,
5619 12
        $offset,
5620 12
        $encoding
5621
    );
5622
  }
5623
5624
  /**
5625
   * Inserts $substring into the string at the $index provided.
5626
   *
5627
   * @param string $str       <p>The input string.</p>
5628
   * @param string $substring <p>String to be inserted.</p>
5629
   * @param int    $index     <p>The index at which to insert the substring.</p>
5630
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
5631
   *
5632
   * @return string
5633
   */
5634 8
  public static function str_insert(string $str, string $substring, int $index, string $encoding = 'UTF-8'): string
5635
  {
5636 8
    $len = self::strlen($str, $encoding);
5637
5638 8
    if ($index > $len) {
5639 1
      return $str;
5640
    }
5641
5642 7
    $start = self::substr($str, 0, $index, $encoding);
5643 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 null|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

5643
    $end = self::substr($str, $index, /** @scrutinizer ignore-type */ $len, $encoding);
Loading history...
5644
5645 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

5645
    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

5645
    return $start . $substring . /** @scrutinizer ignore-type */ $end;
Loading history...
5646
  }
5647
5648
  /**
5649
   * Case-insensitive and UTF-8 safe version of <function>str_replace</function>.
5650
   *
5651
   * @link  http://php.net/manual/en/function.str-ireplace.php
5652
   *
5653
   * @param mixed $search  <p>
5654
   *                       Every replacement with search array is
5655
   *                       performed on the result of previous replacement.
5656
   *                       </p>
5657
   * @param mixed $replace <p>
5658
   *                       </p>
5659
   * @param mixed $subject <p>
5660
   *                       If subject is an array, then the search and
5661
   *                       replace is performed with every entry of
5662
   *                       subject, and the return value is an array as
5663
   *                       well.
5664
   *                       </p>
5665
   * @param int   $count   [optional] <p>
5666
   *                       The number of matched and replaced needles will
5667
   *                       be returned in count which is passed by
5668
   *                       reference.
5669
   *                       </p>
5670
   *
5671
   * @return mixed A string or an array of replacements.
5672
   */
5673 41
  public static function str_ireplace($search, $replace, $subject, &$count = null)
5674
  {
5675 41
    $search = (array)$search;
5676
5677
    /** @noinspection AlterInForeachInspection */
5678 41
    foreach ($search as &$s) {
5679 41
      if ('' === $s .= '') {
5680 7
        $s = '/^(?<=.)$/';
5681
      } else {
5682 41
        $s = '/' . \preg_quote($s, '/') . '/ui';
5683
      }
5684
    }
5685
5686 41
    $subject = \preg_replace($search, $replace, $subject, -1, $replace);
5687 41
    $count = $replace; // used as reference parameter
5688
5689 41
    return $subject;
5690
  }
5691
5692
  /**
5693
   * Check if the string starts with the given substring, case insensitive.
5694
   *
5695
   * @param string $haystack <p>The string to search in.</p>
5696
   * @param string $needle   <p>The substring to search for.</p>
5697
   *
5698
   * @return bool
5699
   */
5700 12
  public static function str_istarts_with(string $haystack, string $needle): bool
5701
  {
5702 12
    if ('' === $haystack || '' === $needle) {
5703 2
      return false;
5704
    }
5705
5706 12
    if (self::stripos($haystack, $needle) === 0) {
5707 12
      return true;
5708
    }
5709
5710 4
    return false;
5711
  }
5712
5713
  /**
5714
   * Returns true if the string begins with any of $substrings, false otherwise.
5715
   *
5716
   * - case-insensitive
5717
   *
5718
   * @param string $str        <p>The input string.</p>
5719
   * @param array  $substrings <p>Substrings to look for.</p>
5720
   *
5721
   * @return bool Whether or not $str starts with $substring.
5722
   */
5723 4
  public static function str_istarts_with_any(string $str, array $substrings): bool
5724
  {
5725 4
    if ('' === $str) {
5726
      return false;
5727
    }
5728
5729 4
    if (empty($substrings)) {
5730
      return false;
5731
    }
5732
5733 4
    foreach ($substrings as $substring) {
5734 4
      if (self::str_istarts_with($str, $substring)) {
5735 4
        return true;
5736
      }
5737
    }
5738
5739
    return false;
5740
  }
5741
5742
  /**
5743
   * Gets the substring after the first occurrence of a separator.
5744
   *
5745
   * @param string $str       <p>The input string.</p>
5746
   * @param string $separator <p>The string separator.</p>
5747
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5748
   *
5749
   * @return string
5750
   */
5751 1
  public static function str_isubstr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5752
  {
5753
    if (
5754 1
        $separator === ''
5755
        ||
5756 1
        $str === ''
5757
    ) {
5758 1
      return '';
5759
    }
5760
5761 1
    $offset = self::str_iindex_first($str, $separator);
5762 1
    if ($offset === false) {
5763 1
      return '';
5764
    }
5765
5766 1
    return (string)self::substr(
5767 1
        $str,
5768 1
        $offset + self::strlen($separator, $encoding),
5769 1
        null,
5770 1
        $encoding
5771
    );
5772
  }
5773
5774
  /**
5775
   * Gets the substring after the last occurrence of a separator.
5776
   *
5777
   * @param string $str       <p>The input string.</p>
5778
   * @param string $separator <p>The string separator.</p>
5779
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5780
   *
5781
   * @return string
5782
   */
5783 1
  public static function str_isubstr_after_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5784
  {
5785
    if (
5786 1
        $separator === ''
5787
        ||
5788 1
        $str === ''
5789
    ) {
5790 1
      return '';
5791
    }
5792
5793 1
    $offset = self::str_iindex_last($str, $separator);
5794 1
    if ($offset === false) {
5795 1
      return '';
5796
    }
5797
5798 1
    return (string)self::substr(
5799 1
        $str,
5800 1
        $offset + self::strlen($separator, $encoding),
5801 1
        null,
5802 1
        $encoding
5803
    );
5804
  }
5805
5806
  /**
5807
   * Gets the substring before the first occurrence of a separator.
5808
   *
5809
   * @param string $str       <p>The input string.</p>
5810
   * @param string $separator <p>The string separator.</p>
5811
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5812
   *
5813
   * @return string
5814
   */
5815 1
  public static function str_isubstr_before_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5816
  {
5817
    if (
5818 1
        $separator === ''
5819
        ||
5820 1
        $str === ''
5821
    ) {
5822 1
      return '';
5823
    }
5824
5825 1
    $offset = self::str_iindex_first($str, $separator);
5826 1
    if ($offset === false) {
5827 1
      return '';
5828
    }
5829
5830 1
    return (string)self::substr($str, 0, $offset, $encoding);
5831
  }
5832
5833
  /**
5834
   * Gets the substring before the last occurrence of a separator.
5835
   *
5836
   * @param string $str       <p>The input string.</p>
5837
   * @param string $separator <p>The string separator.</p>
5838
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
5839
   *
5840
   * @return string
5841
   */
5842 1
  public static function str_isubstr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
5843
  {
5844
    if (
5845 1
        $separator === ''
5846
        ||
5847 1
        $str === ''
5848
    ) {
5849 1
      return '';
5850
    }
5851
5852 1
    $offset = self::str_iindex_last($str, $separator);
5853 1
    if ($offset === false) {
5854 1
      return '';
5855
    }
5856
5857 1
    return (string)self::substr($str, 0, $offset, $encoding);
5858
  }
5859
5860
  /**
5861
   * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
5862
   *
5863
   * @param string $str          <p>The input string.</p>
5864
   * @param string $needle       <p>The string to look for.</p>
5865
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
5866
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
5867
   *
5868
   * @return string
5869
   */
5870 2
  public static function str_isubstr_first(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
5871
  {
5872
    if (
5873 2
        '' === $needle
5874
        ||
5875 2
        '' === $str
5876
    ) {
5877 2
      return '';
5878
    }
5879
5880 2
    $part = self::stristr(
5881 2
        $str,
5882 2
        $needle,
5883 2
        $beforeNeedle,
5884 2
        $encoding
5885
    );
5886 2
    if (false === $part) {
5887 2
      return '';
5888
    }
5889
5890 2
    return $part;
5891
  }
5892
5893
  /**
5894
   * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
5895
   *
5896
   * @param string $str          <p>The input string.</p>
5897
   * @param string $needle       <p>The string to look for.</p>
5898
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
5899
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
5900
   *
5901
   * @return string
5902
   */
5903 1
  public static function str_isubstr_last(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
5904
  {
5905
    if (
5906 1
        '' === $needle
5907
        ||
5908 1
        '' === $str
5909
    ) {
5910 1
      return '';
5911
    }
5912
5913 1
    $part = self::strrichr($str, $needle, $beforeNeedle, $encoding);
5914 1
    if (false === $part) {
5915 1
      return '';
5916
    }
5917
5918 1
    return $part;
5919
  }
5920
5921
  /**
5922
   * Returns the last $n characters of the string.
5923
   *
5924
   * @param string $str      <p>The input string.</p>
5925
   * @param int    $n        <p>Number of characters to retrieve from the end.</p>
5926
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
5927
   *
5928
   * @return string
5929
   */
5930 12
  public static function str_last_char(string $str, int $n = 1, string $encoding = 'UTF-8'): string
5931
  {
5932 12
    if ($n <= 0) {
5933 4
      return '';
5934
    }
5935
5936 8
    $returnTmp = self::substr($str, -$n, null, $encoding);
5937
5938 8
    return ($returnTmp === false ? '' : $returnTmp);
5939
  }
5940
5941
  /**
5942
   * Limit the number of characters in a string.
5943
   *
5944
   * @param string $str      <p>The input string.</p>
5945
   * @param int    $length   [optional] <p>Default: 100</p>
5946
   * @param string $strAddOn [optional] <p>Default: …</p>
5947
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5948
   *
5949
   * @return string
5950
   */
5951 2
  public static function str_limit(string $str, int $length = 100, string $strAddOn = '…', string $encoding = 'UTF-8'): string
5952
  {
5953 2
    if ('' === $str) {
5954 2
      return '';
5955
    }
5956
5957 2
    if ($length <= 0) {
5958 2
      return '';
5959
    }
5960
5961 2
    if (self::strlen($str, $encoding) <= $length) {
5962 2
      return $str;
5963
    }
5964
5965 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

5965
    return /** @scrutinizer ignore-type */ self::substr($str, 0, $length - self::strlen($strAddOn), $encoding) . $strAddOn;
Loading history...
5966
  }
5967
5968
  /**
5969
   * Limit the number of characters in a string, but also after the next word.
5970
   *
5971
   * @param string $str      <p>The input string.</p>
5972
   * @param int    $length   [optional] <p>Default: 100</p>
5973
   * @param string $strAddOn [optional] <p>Default: …</p>
5974
   * @param string $encoding [optional] <p>Default: UTF-8</p>
5975
   *
5976
   * @return string
5977
   */
5978 6
  public static function str_limit_after_word(string $str, int $length = 100, string $strAddOn = '…', string $encoding = 'UTF-8'): string
5979
  {
5980 6
    if ('' === $str) {
5981 2
      return '';
5982
    }
5983
5984 6
    if ($length <= 0) {
5985 2
      return '';
5986
    }
5987
5988 6
    if (self::strlen($str, $encoding) <= $length) {
5989 2
      return $str;
5990
    }
5991
5992 6
    if (self::substr($str, $length - 1, 1, $encoding) === ' ') {
5993 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

5993
      return /** @scrutinizer ignore-type */ self::substr($str, 0, $length - 1, $encoding) . $strAddOn;
Loading history...
5994
    }
5995
5996 3
    $str = (string)self::substr($str, 0, $length, $encoding);
5997 3
    $array = \explode(' ', $str);
5998 3
    \array_pop($array);
5999 3
    $new_str = \implode(' ', $array);
6000
6001 3
    if ($new_str === '') {
6002 2
      $str = self::substr($str, 0, $length - 1, $encoding) . $strAddOn;
6003
    } else {
6004 3
      $str = $new_str . $strAddOn;
6005
    }
6006
6007 3
    return $str;
6008
  }
6009
6010
  /**
6011
   * Returns the longest common prefix between the string and $otherStr.
6012
   *
6013
   * @param string $str      <p>The input sting.</p>
6014
   * @param string $otherStr <p>Second string for comparison.</p>
6015
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6016
   *
6017
   * @return string
6018
   */
6019 10
  public static function str_longest_common_prefix(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6020
  {
6021 10
    $maxLength = \min(self::strlen($str, $encoding), self::strlen($otherStr, $encoding));
6022
6023 10
    $longestCommonPrefix = '';
6024 10
    for ($i = 0; $i < $maxLength; $i++) {
6025 8
      $char = self::substr($str, $i, 1, $encoding);
6026
6027 8
      if ($char == self::substr($otherStr, $i, 1, $encoding)) {
6028 6
        $longestCommonPrefix .= $char;
6029
      } else {
6030 6
        break;
6031
      }
6032
    }
6033
6034 10
    return $longestCommonPrefix;
6035
  }
6036
6037
  /**
6038
   * Returns the longest common substring between the string and $otherStr.
6039
   * In the case of ties, it returns that which occurs first.
6040
   *
6041
   * @param string $str
6042
   * @param string $otherStr <p>Second string for comparison.</p>
6043
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6044
   *
6045
   * @return string String with its $str being the longest common substring.
6046
   */
6047 11
  public static function str_longest_common_substring(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6048
  {
6049
    // Uses dynamic programming to solve
6050
    // http://en.wikipedia.org/wiki/Longest_common_substring_problem
6051 11
    $strLength = self::strlen($str, $encoding);
6052 11
    $otherLength = self::strlen($otherStr, $encoding);
6053
6054
    // Return if either string is empty
6055 11
    if ($strLength == 0 || $otherLength == 0) {
6056 2
      return '';
6057
    }
6058
6059 9
    $len = 0;
6060 9
    $end = 0;
6061 9
    $table = \array_fill(
6062 9
        0,
6063 9
        $strLength + 1,
6064 9
        \array_fill(0, $otherLength + 1, 0)
6065
    );
6066
6067 9
    for ($i = 1; $i <= $strLength; $i++) {
6068 9
      for ($j = 1; $j <= $otherLength; $j++) {
6069 9
        $strChar = self::substr($str, $i - 1, 1, $encoding);
6070 9
        $otherChar = self::substr($otherStr, $j - 1, 1, $encoding);
6071
6072 9
        if ($strChar == $otherChar) {
6073 8
          $table[$i][$j] = $table[$i - 1][$j - 1] + 1;
6074 8
          if ($table[$i][$j] > $len) {
6075 8
            $len = $table[$i][$j];
6076 8
            $end = $i;
6077
          }
6078
        } else {
6079 9
          $table[$i][$j] = 0;
6080
        }
6081
      }
6082
    }
6083
6084 9
    $returnTmp = self::substr($str, $end - $len, $len, $encoding);
6085
6086 9
    return ($returnTmp === false ? '' : $returnTmp);
6087
  }
6088
6089
  /**
6090
   * Returns the longest common suffix between the string and $otherStr.
6091
   *
6092
   * @param string $str
6093
   * @param string $otherStr <p>Second string for comparison.</p>
6094
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6095
   *
6096
   * @return string
6097
   */
6098 10
  public static function str_longest_common_suffix(string $str, string $otherStr, string $encoding = 'UTF-8'): string
6099
  {
6100 10
    $maxLength = \min(self::strlen($str, $encoding), self::strlen($otherStr, $encoding));
6101
6102 10
    $longestCommonSuffix = '';
6103 10
    for ($i = 1; $i <= $maxLength; $i++) {
6104 8
      $char = self::substr($str, -$i, 1, $encoding);
6105
6106 8
      if ($char == self::substr($otherStr, -$i, 1, $encoding)) {
6107 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

6107
        $longestCommonSuffix = /** @scrutinizer ignore-type */ $char . $longestCommonSuffix;
Loading history...
6108
      } else {
6109 6
        break;
6110
      }
6111
    }
6112
6113 10
    return $longestCommonSuffix;
6114
  }
6115
6116
  /**
6117
   * Returns true if $str matches the supplied pattern, false otherwise.
6118
   *
6119
   * @param string $str     <p>The input string.</p>
6120
   * @param string $pattern <p>Regex pattern to match against.</p>
6121
   *
6122
   * @return bool Whether or not $str matches the pattern.
6123
   */
6124 126
  public static function str_matches_pattern(string $str, string $pattern): bool
6125
  {
6126 126
    if (\preg_match('/' . $pattern . '/u', $str)) {
6127 87
      return true;
6128
    }
6129
6130 39
    return false;
6131
  }
6132
6133
  /**
6134
   * Returns whether or not a character exists at an index. Offsets may be
6135
   * negative to count from the last character in the string. Implements
6136
   * part of the ArrayAccess interface.
6137
   *
6138
   * @param string $str      <p>The input string.</p>
6139
   * @param int    $offset   <p>The index to check.</p>
6140
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
6141
   *
6142
   *
6143
   * @return bool Whether or not the index exists.
6144
   */
6145 6
  public static function str_offset_exists(string $str, int $offset, string $encoding = 'UTF-8'): bool
6146
  {
6147
    // init
6148 6
    $length = self::strlen($str, $encoding);
6149
6150 6
    if ($offset >= 0) {
6151 3
      return ($length > $offset);
6152
    }
6153
6154 3
    return ($length >= \abs($offset));
6155
  }
6156
6157
  /**
6158
   * Returns the character at the given index. Offsets may be negative to
6159
   * count from the last character in the string. Implements part of the
6160
   * ArrayAccess interface, and throws an OutOfBoundsException if the index
6161
   * does not exist.
6162
   *
6163
   * @param string $str      <p>The input string.</p>
6164
   * @param int    $index    <p>The <strong>index</strong> from which to retrieve the char.</p>
6165
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6166
   *
6167
   * @return string The character at the specified index.
6168
   *
6169
   * @throws \OutOfBoundsException If the positive or negative offset does not exist.
6170
   */
6171 2
  public static function str_offset_get(string $str, int $index, string $encoding = 'UTF-8'): string
6172
  {
6173
    // init
6174 2
    $length = self::strlen($str);
6175
6176
    if (
6177 2
        ($index >= 0 && $length <= $index)
6178
        ||
6179 2
        $length < \abs($index)
6180
    ) {
6181 1
      throw new \OutOfBoundsException('No character exists at the index');
6182
    }
6183
6184 1
    return self::char_at($str, $index, $encoding);
6185
  }
6186
6187
  /**
6188
   * Pad a UTF-8 string to given length with another string.
6189
   *
6190
   * @param string $str        <p>The input string.</p>
6191
   * @param int    $pad_length <p>The length of return string.</p>
6192
   * @param string $pad_string [optional] <p>String to use for padding the input string.</p>
6193
   * @param int    $pad_type   [optional] <p>
6194
   *                           Can be <strong>STR_PAD_RIGHT</strong> (default),
6195
   *                           <strong>STR_PAD_LEFT</strong> or <strong>STR_PAD_BOTH</strong>
6196
   *                           </p>
6197
   * @param string $encoding   [optional] <p>Default: UTF-8</p>
6198
   *
6199
   * @return string Returns the padded string.
6200
   */
6201 41
  public static function str_pad(string $str, int $pad_length, string $pad_string = ' ', $pad_type = STR_PAD_RIGHT, string $encoding = 'UTF-8'): string
6202
  {
6203 41
    if ('' === $str) {
6204
      return '';
6205
    }
6206
6207 41
    if ($pad_type !== (int)$pad_type) {
6208 13
      if ($pad_type == 'left') {
6209 3
        $pad_type = STR_PAD_LEFT;
6210 10
      } elseif ($pad_type == 'right') {
6211 6
        $pad_type = STR_PAD_RIGHT;
6212 4
      } elseif ($pad_type == 'both') {
6213 3
        $pad_type = STR_PAD_BOTH;
6214
      } else {
6215 1
        throw new \InvalidArgumentException(
6216 1
            'Pad expects $padType to be "STR_PAD_*" or ' . "to be one of 'left', 'right' or 'both'"
6217
        );
6218
      }
6219
    }
6220
6221 40
    $str_length = self::strlen($str, $encoding);
6222
6223
    if (
6224 40
        $pad_length > 0
6225
        &&
6226 40
        $pad_length >= $str_length
6227
    ) {
6228 39
      $ps_length = self::strlen($pad_string, $encoding);
6229
6230 39
      $diff = ($pad_length - $str_length);
6231
6232
      switch ($pad_type) {
6233 39
        case STR_PAD_LEFT:
6234 13
          $pre = \str_repeat($pad_string, (int)\ceil($diff / $ps_length));
6235 13
          $pre = (string)self::substr($pre, 0, $diff, $encoding);
6236 13
          $post = '';
6237 13
          break;
6238
6239 29
        case STR_PAD_BOTH:
6240 14
          $pre = \str_repeat($pad_string, (int)\ceil($diff / $ps_length / 2));
6241 14
          $pre = (string)self::substr($pre, 0, (int)\floor($diff / 2), $encoding);
6242 14
          $post = \str_repeat($pad_string, (int)\ceil($diff / $ps_length / 2));
6243 14
          $post = (string)self::substr($post, 0, (int)\ceil($diff / 2), $encoding);
6244 14
          break;
6245
6246 18
        case STR_PAD_RIGHT:
6247
        default:
6248 18
          $post = \str_repeat($pad_string, (int)\ceil($diff / $ps_length));
6249 18
          $post = (string)self::substr($post, 0, $diff, $encoding);
6250 18
          $pre = '';
6251
      }
6252
6253 39
      return $pre . $str . $post;
6254
    }
6255
6256 4
    return $str;
6257
  }
6258
6259
  /**
6260
   * Returns a new string of a given length such that both sides of the
6261
   * string are padded. Alias for pad() with a $padType of 'both'.
6262
   *
6263
   * @param string $str
6264
   * @param int    $length   <p>Desired string length after padding.</p>
6265
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6266
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6267
   *
6268
   * @return string String with padding applied.
6269
   */
6270 11
  public static function str_pad_both(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6271
  {
6272 11
    $padding = $length - self::strlen($str, $encoding);
6273
6274 11
    return self::apply_padding($str, (int)\floor($padding / 2), (int)\ceil($padding / 2), $padStr, $encoding);
6275
  }
6276
6277
  /**
6278
   * Returns a new string of a given length such that the beginning of the
6279
   * string is padded. Alias for pad() with a $padType of 'left'.
6280
   *
6281
   * @param string $str
6282
   * @param int    $length   <p>Desired string length after padding.</p>
6283
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6284
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6285
   *
6286
   * @return string String with left padding.
6287
   */
6288 7
  public static function str_pad_left(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6289
  {
6290 7
    return self::apply_padding($str, $length - self::strlen($str), 0, $padStr, $encoding);
6291
  }
6292
6293
  /**
6294
   * Returns a new string of a given length such that the end of the string
6295
   * is padded. Alias for pad() with a $padType of 'right'.
6296
   *
6297
   * @param string $str
6298
   * @param int    $length   <p>Desired string length after padding.</p>
6299
   * @param string $padStr   [optional] <p>String used to pad, defaults to space. Default: ' '</p>
6300
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6301
   *
6302
   * @return string String with right padding.
6303
   */
6304 7
  public static function str_pad_right(string $str, int $length, string $padStr = ' ', string $encoding = 'UTF-8'): string
6305
  {
6306 7
    return self::apply_padding($str, 0, $length - self::strlen($str), $padStr, $encoding);
6307
  }
6308
6309
  /**
6310
   * Repeat a string.
6311
   *
6312
   * @param string $str        <p>
6313
   *                           The string to be repeated.
6314
   *                           </p>
6315
   * @param int    $multiplier <p>
6316
   *                           Number of time the input string should be
6317
   *                           repeated.
6318
   *                           </p>
6319
   *                           <p>
6320
   *                           multiplier has to be greater than or equal to 0.
6321
   *                           If the multiplier is set to 0, the function
6322
   *                           will return an empty string.
6323
   *                           </p>
6324
   *
6325
   * @return string The repeated string.
6326
   */
6327 9
  public static function str_repeat(string $str, int $multiplier): string
6328
  {
6329 9
    $str = self::filter($str);
6330
6331 9
    return \str_repeat($str, $multiplier);
6332
  }
6333
6334
  /**
6335
   * INFO: This is only a wrapper for "str_replace()"  -> the original functions is already UTF-8 safe.
6336
   *
6337
   * Replace all occurrences of the search string with the replacement string
6338
   *
6339
   * @link http://php.net/manual/en/function.str-replace.php
6340
   *
6341
   * @param mixed $search  <p>
6342
   *                       The value being searched for, otherwise known as the needle.
6343
   *                       An array may be used to designate multiple needles.
6344
   *                       </p>
6345
   * @param mixed $replace <p>
6346
   *                       The replacement value that replaces found search
6347
   *                       values. An array may be used to designate multiple replacements.
6348
   *                       </p>
6349
   * @param mixed $subject <p>
6350
   *                       The string or array being searched and replaced on,
6351
   *                       otherwise known as the haystack.
6352
   *                       </p>
6353
   *                       <p>
6354
   *                       If subject is an array, then the search and
6355
   *                       replace is performed with every entry of
6356
   *                       subject, and the return value is an array as
6357
   *                       well.
6358
   *                       </p>
6359
   * @param int   $count   [optional] If passed, this will hold the number of matched and replaced needles.
6360
   *
6361
   * @return mixed This function returns a string or an array with the replaced values.
6362
   */
6363 92
  public static function str_replace($search, $replace, $subject, int &$count = null)
6364
  {
6365 92
    return \str_replace($search, $replace, $subject, $count);
6366
  }
6367
6368
  /**
6369
   * Replaces all occurrences of $search from the beginning of string with $replacement.
6370
   *
6371
   * @param string $str         <p>The input string.</p>
6372
   * @param string $search      <p>The string to search for.</p>
6373
   * @param string $replacement <p>The replacement.</p>
6374
   *
6375
   * @return string String after the replacements.
6376
   */
6377 16
  public static function str_replace_beginning(string $str, string $search, string $replacement): string
6378
  {
6379 16
    return self::regex_replace(
6380 16
        $str,
6381 16
        '^' . \preg_quote($search, '/'),
6382 16
        self::str_replace('\\', '\\\\', $replacement)
6383
    );
6384
  }
6385
6386
  /**
6387
   * Replaces all occurrences of $search from the ending of string with $replacement.
6388
   *
6389
   * @param string $str         <p>The input string.</p>
6390
   * @param string $search      <p>The string to search for.</p>
6391
   * @param string $replacement <p>The replacement.</p>
6392
   *
6393
   * @return string String after the replacements.
6394
   */
6395 16
  public static function str_replace_ending(string $str, string $search, string $replacement): string
6396
  {
6397 16
    return self::regex_replace(
6398 16
        $str,
6399 16
        \preg_quote($search, '/') . '$',
6400 16
        self::str_replace('\\', '\\\\', $replacement)
6401
    );
6402
  }
6403
6404
  /**
6405
   * Replace the first "$search"-term with the "$replace"-term.
6406
   *
6407
   * @param string $search
6408
   * @param string $replace
6409
   * @param string $subject
6410
   *
6411
   * @return string
6412
   */
6413 2
  public static function str_replace_first(string $search, string $replace, string $subject): string
6414
  {
6415 2
    $pos = self::strpos($subject, $search);
6416 2
    if ($pos !== false) {
6417 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[]|null|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

6417
      return self::substr_replace($subject, $replace, $pos, /** @scrutinizer ignore-type */ self::strlen($search));
Loading history...
6418
    }
6419
6420 2
    return $subject;
6421
  }
6422
6423
  /**
6424
   * Replace the last "$search"-term with the "$replace"-term.
6425
   *
6426
   * @param string $search
6427
   * @param string $replace
6428
   * @param string $subject
6429
   *
6430
   * @return string
6431
   */
6432 2
  public static function str_replace_last(string $search, string $replace, string $subject): string
6433
  {
6434 2
    $pos = self::strrpos($subject, $search);
6435 2
    if ($pos !== false) {
6436 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[]|null|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

6436
      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...
6437
    }
6438
6439 2
    return $subject;
6440
  }
6441
6442
  /**
6443
   * Shuffles all the characters in the string.
6444
   *
6445
   * PS: uses random algorithm which is weak for cryptography purposes
6446
   *
6447
   * @param string $str <p>The input string</p>
6448
   *
6449
   * @return string The shuffled string.
6450
   */
6451 5
  public static function str_shuffle(string $str): string
6452
  {
6453 5
    $indexes = \range(0, self::strlen($str) - 1);
6454
    /** @noinspection NonSecureShuffleUsageInspection */
6455 5
    \shuffle($indexes);
6456
6457 5
    $shuffledStr = '';
6458 5
    foreach ($indexes as $i) {
6459 5
      $shuffledStr .= self::substr($str, $i, 1);
6460
    }
6461
6462 5
    return $shuffledStr;
6463
  }
6464
6465
  /**
6466
   * Returns the substring beginning at $start, and up to, but not including
6467
   * the index specified by $end. If $end is omitted, the function extracts
6468
   * the remaining string. If $end is negative, it is computed from the end
6469
   * of the string.
6470
   *
6471
   * @param string $str
6472
   * @param int    $start    <p>Initial index from which to begin extraction.</p>
6473
   * @param int    $end      [optional] <p>Index at which to end extraction. Default: null</p>
6474
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6475
   *
6476
   * @return string|false
6477
   *                     <p>The extracted substring.</p><p>If <i>str</i> is shorter than <i>start</i>
6478
   *                     characters long, <b>FALSE</b> will be returned.
6479
   */
6480 18
  public static function str_slice(string $str, int $start, int $end = null, string $encoding = 'UTF-8')
6481
  {
6482 18
    if ($end === null) {
6483 6
      $length = self::strlen($str);
6484 12
    } elseif ($end >= 0 && $end <= $start) {
6485 4
      return '';
6486 8
    } elseif ($end < 0) {
6487 2
      $length = self::strlen($str) + $end - $start;
6488
    } else {
6489 6
      $length = $end - $start;
6490
    }
6491
6492 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 null|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

6492
    return self::substr($str, $start, /** @scrutinizer ignore-type */ $length, $encoding);
Loading history...
6493
  }
6494
6495
  /**
6496
   * Convert a string to e.g.: "snake_case"
6497
   *
6498
   * @param string $str
6499
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6500
   *
6501
   * @return string String in snake_case.
6502
   */
6503 20
  public static function str_snakeize(string $str, string $encoding = 'UTF-8'): string
6504
  {
6505 20
    $str = self::normalize_whitespace($str);
6506 20
    $str = \str_replace('-', '_', $str);
6507
6508 20
    $str = (string)\preg_replace_callback(
6509 20
        '/([\d|A-Z])/u',
6510 20
        function ($matches) use ($encoding) {
6511 8
          $match = $matches[1];
6512 8
          $matchInt = (int)$match;
6513
6514 8
          if ((string)$matchInt == $match) {
6515 4
            return '_' . $match . '_';
6516
          }
6517
6518 4
          return '_' . UTF8::strtolower($match, $encoding);
6519 20
        },
6520 20
        $str
6521
    );
6522
6523 20
    $str = (string)\preg_replace(
6524
        [
6525 20
            '/\s+/',        // convert spaces to "_"
6526
            '/^\s+|\s+$/',  // trim leading & trailing spaces
6527
            '/_+/',         // remove double "_"
6528
        ],
6529
        [
6530 20
            '_',
6531
            '',
6532
            '_',
6533
        ],
6534 20
        $str
6535
    );
6536
6537 20
    $str = self::trim($str, '_'); // trim leading & trailing "_"
6538 20
    $str = self::trim($str); // trim leading & trailing whitespace
6539
6540 20
    return $str;
6541
  }
6542
6543
  /**
6544
   * Sort all characters according to code points.
6545
   *
6546
   * @param string $str    <p>A UTF-8 string.</p>
6547
   * @param bool   $unique <p>Sort unique. If <strong>true</strong>, repeated characters are ignored.</p>
6548
   * @param bool   $desc   <p>If <strong>true</strong>, will sort characters in reverse code point order.</p>
6549
   *
6550
   * @return string String of sorted characters.
6551
   */
6552 2
  public static function str_sort(string $str, bool $unique = false, bool $desc = false): string
6553
  {
6554 2
    $array = self::codepoints($str);
6555
6556 2
    if ($unique) {
6557 2
      $array = \array_flip(\array_flip($array));
6558
    }
6559
6560 2
    if ($desc) {
6561 2
      \arsort($array);
6562
    } else {
6563 2
      \asort($array);
6564
    }
6565
6566 2
    return self::string($array);
6567
  }
6568
6569
  /**
6570
   * alias for "UTF8::split()"
6571
   *
6572
   * @see UTF8::split()
6573
   *
6574
   * @param string|string[] $str
6575
   * @param int             $len
6576
   *
6577
   * @return string[]
6578
   */
6579 25
  public static function str_split($str, int $len = 1): array
6580
  {
6581 25
    return self::split($str, $len);
6582
  }
6583
6584
  /**
6585
   * Splits the string with the provided regular expression, returning an
6586
   * array of Stringy objects. An optional integer $limit will truncate the
6587
   * results.
6588
   *
6589
   * @param string $str
6590
   * @param string $pattern <p>The regex with which to split the string.</p>
6591
   * @param int    $limit   [optional] <p>Maximum number of results to return. Default: -1 === no limit</p>
6592
   *
6593
   * @return string[] An array of strings.
6594
   */
6595 16
  public static function str_split_pattern(string $str, string $pattern, int $limit = -1): array
6596
  {
6597 16
    if ($limit === 0) {
6598 2
      return [];
6599
    }
6600
6601
    // this->split errors when supplied an empty pattern in < PHP 5.4.13
6602
    // and current versions of HHVM (3.8 and below)
6603 14
    if ($pattern === '') {
6604 1
      return [$str];
6605
    }
6606
6607
    // this->split returns the remaining unsplit string in the last index when
6608
    // supplying a limit
6609 13
    if ($limit > 0) {
6610 8
      ++$limit;
6611
    } else {
6612 5
      $limit = -1;
6613
    }
6614
6615 13
    $array = \preg_split('/' . \preg_quote($pattern, '/') . '/u', $str, $limit);
6616
6617 13
    if ($array === false) {
6618
      return [];
6619
    }
6620
6621 13
    if ($limit > 0 && \count($array) === $limit) {
6622 4
      \array_pop($array);
6623
    }
6624
6625 13
    return $array;
6626
  }
6627
6628
  /**
6629
   * Check if the string starts with the given substring.
6630
   *
6631
   * @param string $haystack <p>The string to search in.</p>
6632
   * @param string $needle   <p>The substring to search for.</p>
6633
   *
6634
   * @return bool
6635
   */
6636 41
  public static function str_starts_with(string $haystack, string $needle): bool
6637
  {
6638 41
    if ('' === $haystack || '' === $needle) {
6639 4
      return false;
6640
    }
6641
6642 39
    if (\strpos($haystack, $needle) === 0) {
6643 19
      return true;
6644
    }
6645
6646 24
    return false;
6647
  }
6648
6649
  /**
6650
   * Returns true if the string begins with any of $substrings, false otherwise.
6651
   *
6652
   * - case-sensitive
6653
   *
6654
   * @param string $str        <p>The input string.</p>
6655
   * @param array  $substrings <p>Substrings to look for.</p>
6656
   *
6657
   * @return bool Whether or not $str starts with $substring.
6658
   */
6659 8
  public static function str_starts_with_any(string $str, array $substrings): bool
6660
  {
6661 8
    if ('' === $str) {
6662
      return false;
6663
    }
6664
6665 8
    if (empty($substrings)) {
6666
      return false;
6667
    }
6668
6669 8
    foreach ($substrings as $substring) {
6670 8
      if (self::str_starts_with($str, $substring)) {
6671 8
        return true;
6672
      }
6673
    }
6674
6675 6
    return false;
6676
  }
6677
6678
  /**
6679
   * Gets the substring after the first occurrence of a separator.
6680
   *
6681
   * @param string $str       <p>The input string.</p>
6682
   * @param string $separator <p>The string separator.</p>
6683
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6684
   *
6685
   * @return string
6686
   */
6687 1
  public static function str_substr_after_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6688
  {
6689
    if (
6690 1
        $separator === ''
6691
        ||
6692 1
        $str === ''
6693
    ) {
6694 1
      return '';
6695
    }
6696
6697 1
    $offset = self::str_index_first($str, $separator);
6698 1
    if ($offset === false) {
6699 1
      return '';
6700
    }
6701
6702 1
    return (string)self::substr(
6703 1
        $str,
6704 1
        $offset + self::strlen($separator, $encoding),
6705 1
        null,
6706 1
        $encoding
6707
    );
6708
  }
6709
6710
  /**
6711
   * Gets the substring after the last occurrence of a separator.
6712
   *
6713
   * @param string $str       <p>The input string.</p>
6714
   * @param string $separator <p>The string separator.</p>
6715
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6716
   *
6717
   * @return string
6718
   */
6719 1
  public static function str_substr_after_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6720
  {
6721
    if (
6722 1
        $separator === ''
6723
        ||
6724 1
        $str === ''
6725
    ) {
6726 1
      return '';
6727
    }
6728
6729 1
    $offset = self::str_index_last($str, $separator);
6730 1
    if ($offset === false) {
6731 1
      return '';
6732
    }
6733
6734 1
    return (string)self::substr(
6735 1
        $str,
6736 1
        $offset + self::strlen($separator, $encoding),
6737 1
        null,
6738 1
        $encoding
6739
    );
6740
  }
6741
6742
  /**
6743
   * Gets the substring before the first occurrence of a separator.
6744
   *
6745
   * @param string $str       <p>The input string.</p>
6746
   * @param string $separator <p>The string separator.</p>
6747
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6748
   *
6749
   * @return string
6750
   */
6751 1
  public static function str_substr_before_first_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6752
  {
6753
    if (
6754 1
        $separator === ''
6755
        ||
6756 1
        $str === ''
6757
    ) {
6758 1
      return '';
6759
    }
6760
6761 1
    $offset = self::str_index_first($str, $separator);
6762 1
    if ($offset === false) {
6763 1
      return '';
6764
    }
6765
6766 1
    return (string)self::substr(
6767 1
        $str,
6768 1
        0,
6769 1
        $offset,
6770 1
        $encoding
6771
    );
6772
  }
6773
6774
  /**
6775
   * Gets the substring before the last occurrence of a separator.
6776
   *
6777
   * @param string $str       <p>The input string.</p>
6778
   * @param string $separator <p>The string separator.</p>
6779
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
6780
   *
6781
   * @return string
6782
   */
6783 1
  public static function str_substr_before_last_separator(string $str, string $separator, string $encoding = 'UTF-8'): string
6784
  {
6785
    if (
6786 1
        $separator === ''
6787
        ||
6788 1
        $str === ''
6789
    ) {
6790 1
      return '';
6791
    }
6792
6793 1
    $offset = self::str_index_last($str, $separator);
6794 1
    if ($offset === false) {
6795 1
      return '';
6796
    }
6797
6798 1
    return (string)self::substr(
6799 1
        $str,
6800 1
        0,
6801 1
        $offset,
6802 1
        $encoding
6803
    );
6804
  }
6805
6806
  /**
6807
   * Gets the substring after (or before via "$beforeNeedle") the first occurrence of the "$needle".
6808
   *
6809
   * @param string $str          <p>The input string.</p>
6810
   * @param string $needle       <p>The string to look for.</p>
6811
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
6812
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
6813
   *
6814
   * @return string
6815
   */
6816 2
  public static function str_substr_first(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
6817
  {
6818
    if (
6819 2
        '' === $str
6820
        ||
6821 2
        '' === $needle
6822
    ) {
6823 2
      return '';
6824
    }
6825
6826 2
    $part = self::strstr(
6827 2
        $str,
6828 2
        $needle,
6829 2
        $beforeNeedle,
6830 2
        $encoding
6831
    );
6832 2
    if (false === $part) {
6833 2
      return '';
6834
    }
6835
6836 2
    return $part;
6837
  }
6838
6839
  /**
6840
   * Gets the substring after (or before via "$beforeNeedle") the last occurrence of the "$needle".
6841
   *
6842
   * @param string $str          <p>The input string.</p>
6843
   * @param string $needle       <p>The string to look for.</p>
6844
   * @param bool   $beforeNeedle [optional] <p>Default: false</p>
6845
   * @param string $encoding     [optional] <p>Default: UTF-8</p>
6846
   *
6847
   * @return string
6848
   */
6849 2
  public static function str_substr_last(string $str, string $needle, bool $beforeNeedle = false, string $encoding = 'UTF-8'): string
6850
  {
6851
    if (
6852 2
        '' === $str
6853
        ||
6854 2
        '' === $needle
6855
    ) {
6856 2
      return '';
6857
    }
6858
6859 2
    $part = self::strrchr($str, $needle, $beforeNeedle, $encoding);
6860 2
    if (false === $part) {
6861 2
      return '';
6862
    }
6863
6864 2
    return $part;
6865
  }
6866
6867
  /**
6868
   * Surrounds $str with the given substring.
6869
   *
6870
   * @param string $str
6871
   * @param string $substring <p>The substring to add to both sides.</P>
6872
   *
6873
   * @return string String with the substring both prepended and appended.
6874
   */
6875 5
  public static function str_surround(string $str, string $substring): string
6876
  {
6877 5
    return \implode('', [$substring, $str, $substring]);
6878
  }
6879
6880
  /**
6881
   * Returns a trimmed string with the first letter of each word capitalized.
6882
   * Also accepts an array, $ignore, allowing you to list words not to be
6883
   * capitalized.
6884
   *
6885
   * @param string              $str
6886
   * @param string[]|array|null $ignore   [optional] <p>An array of words not to capitalize or null. Default: null</p>
6887
   * @param string              $encoding [optional] <p>Default: UTF-8</p>
6888
   *
6889
   * @return string The titleized string.
6890
   */
6891 5
  public static function str_titleize(string $str, array $ignore = null, string $encoding = 'UTF-8'): string
6892
  {
6893 5
    $str = self::trim($str);
6894
6895 5
    $str = (string)\preg_replace_callback(
6896 5
        '/([\S]+)/u',
6897 5
        function ($match) use ($encoding, $ignore) {
6898 5
          if ($ignore && \in_array($match[0], $ignore, true)) {
6899 2
            return $match[0];
6900
          }
6901
6902 5
          return self::str_upper_first(self::strtolower($match[0], $encoding));
6903 5
        },
6904 5
        $str
6905
    );
6906
6907 5
    return $str;
6908
  }
6909
6910
  /**
6911
   * Returns a trimmed string in proper title case.
6912
   *
6913
   * Also accepts an array, $ignore, allowing you to list words not to be
6914
   * capitalized.
6915
   *
6916
   * Adapted from John Gruber's script.
6917
   *
6918
   * @see https://gist.github.com/gruber/9f9e8650d68b13ce4d78
6919
   *
6920
   * @param string $str
6921
   * @param array  $ignore   <p>An array of words not to capitalize.</p>
6922
   * @param string $encoding [optional] <p>Default: UTF-8</p>
6923
   *
6924
   * @return string The titleized string.
6925
   */
6926 35
  public static function str_titleize_for_humans(string $str, array $ignore = [], string $encoding = 'UTF-8'): string
6927
  {
6928 35
    $smallWords = \array_merge(
6929
        [
6930 35
            '(?<!q&)a',
6931
            'an',
6932
            'and',
6933
            'as',
6934
            'at(?!&t)',
6935
            'but',
6936
            'by',
6937
            'en',
6938
            'for',
6939
            'if',
6940
            'in',
6941
            'of',
6942
            'on',
6943
            'or',
6944
            'the',
6945
            'to',
6946
            'v[.]?',
6947
            'via',
6948
            'vs[.]?',
6949
        ],
6950 35
        $ignore
6951
    );
6952
6953 35
    $smallWordsRx = \implode('|', $smallWords);
6954 35
    $apostropheRx = '(?x: [\'’] [[:lower:]]* )?';
6955
6956 35
    $str = self::trim($str);
6957
6958 35
    if (self::has_lowercase($str) === false) {
6959 2
      $str = self::strtolower($str);
6960
    }
6961
6962
    // The main substitutions
6963 35
    $str = (string)\preg_replace_callback(
6964
        '~\b (_*) (?:                                                              # 1. Leading underscore and
6965
                        ( (?<=[ ][/\\\\]) [[:alpha:]]+ [-_[:alpha:]/\\\\]+ |              # 2. file path or 
6966 35
                          [-_[:alpha:]]+ [@.:] [-_[:alpha:]@.:/]+ ' . $apostropheRx . ' ) #    URL, domain, or email
6967
                        |
6968 35
                        ( (?i: ' . $smallWordsRx . ' ) ' . $apostropheRx . ' )            # 3. or small word (case-insensitive)
6969
                        |
6970 35
                        ( [[:alpha:]] [[:lower:]\'’()\[\]{}]* ' . $apostropheRx . ' )     # 4. or word w/o internal caps
6971
                        |
6972 35
                        ( [[:alpha:]] [[:alpha:]\'’()\[\]{}]* ' . $apostropheRx . ' )     # 5. or some other word
6973
                      ) (_*) \b                                                           # 6. With trailing underscore
6974
                    ~ux',
6975 35
        function ($matches) use ($encoding) {
6976
          // Preserve leading underscore
6977 35
          $str = $matches[1];
6978 35
          if ($matches[2]) {
6979
            // Preserve URLs, domains, emails and file paths
6980 5
            $str .= $matches[2];
6981 35
          } elseif ($matches[3]) {
6982
            // Lower-case small words
6983 25
            $str .= self::strtolower($matches[3], $encoding);
6984 35
          } elseif ($matches[4]) {
6985
            // Capitalize word w/o internal caps
6986 34
            $str .= static::str_upper_first($matches[4], $encoding);
6987
          } else {
6988
            // Preserve other kinds of word (iPhone)
6989 7
            $str .= $matches[5];
6990
          }
6991
          // Preserve trailing underscore
6992 35
          $str .= $matches[6];
6993
6994 35
          return $str;
6995 35
        },
6996 35
        $str
6997
    );
6998
6999
    // Exceptions for small words: capitalize at start of title...
7000 35
    $str = (string)\preg_replace_callback(
7001
        '~(  \A [[:punct:]]*                # start of title...
7002
                      |  [:.;?!][ ]+               # or of subsentence...
7003
                      |  [ ][\'"“‘(\[][ ]* )       # or of inserted subphrase...
7004 35
                      ( ' . $smallWordsRx . ' ) \b # ...followed by small word
7005
                     ~uxi',
7006 35
        function ($matches) use ($encoding) {
7007 11
          return $matches[1] . static::str_upper_first($matches[2], $encoding);
7008 35
        },
7009 35
        $str
7010
    );
7011
7012
    // ...and end of title
7013 35
    $str = (string)\preg_replace_callback(
7014 35
        '~\b ( ' . $smallWordsRx . ' ) # small word...
7015
                      (?= [[:punct:]]* \Z     # ...at the end of the title...
7016
                      |   [\'"’”)\]] [ ] )    # ...or of an inserted subphrase?
7017
                     ~uxi',
7018 35
        function ($matches) use ($encoding) {
7019 3
          return static::str_upper_first($matches[1], $encoding);
7020 35
        },
7021 35
        $str
7022
    );
7023
7024
    // Exceptions for small words in hyphenated compound words
7025
    // e.g. "in-flight" -> In-Flight
7026 35
    $str = (string)\preg_replace_callback(
7027
        '~\b
7028
                        (?<! -)                   # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (in-flight)
7029 35
                        ( ' . $smallWordsRx . ' )
7030
                        (?= -[[:alpha:]]+)        # lookahead for "-someword"
7031
                       ~uxi',
7032 35
        function ($matches) use ($encoding) {
7033
          return static::str_upper_first($matches[1], $encoding);
7034 35
        },
7035 35
        $str
7036
    );
7037
7038
    // e.g. "Stand-in" -> "Stand-In" (Stand is already capped at this point)
7039 35
    $str = (string)\preg_replace_callback(
7040
        '~\b
7041
                      (?<!…)                    # Negative lookbehind for a hyphen; we do not want to match man-in-the-middle but do want (stand-in)
7042
                      ( [[:alpha:]]+- )         # $1 = first word and hyphen, should already be properly capped
7043 35
                      ( ' . $smallWordsRx . ' ) # ...followed by small word
7044
                      (?!	- )                   # Negative lookahead for another -
7045
                     ~uxi',
7046 35
        function ($matches) use ($encoding) {
7047
          return $matches[1] . static::str_upper_first($matches[2], $encoding);
7048 35
        },
7049 35
        $str
7050
    );
7051
7052 35
    return $str;
7053
  }
7054
7055
  /**
7056
   * Get a binary representation of a specific string.
7057
   *
7058
   * @param string $str <p>The input string.</p>
7059
   *
7060
   * @return string
7061
   */
7062 2
  public static function str_to_binary(string $str): string
7063
  {
7064 2
    $value = \unpack('H*', $str);
7065
7066 2
    return \base_convert($value[1], 16, 2);
7067
  }
7068
7069
  /**
7070
   * @param string   $str
7071
   * @param bool     $removeEmptyValues <p>Remove empty values.</p>
7072
   * @param null|int $removeShortValues <p>The min. string length or null to disable</p>
7073
   *
7074
   * @return string[]
7075
   */
7076 17
  public static function str_to_lines(string $str, bool $removeEmptyValues = false, int $removeShortValues = null): array
7077
  {
7078 17
    if ('' === $str) {
7079 1
      return ($removeEmptyValues === true ? [] : ['']);
7080
    }
7081
7082 16
    $return = \preg_split("/[\r\n]{1,2}/u", $str);
7083
7084 16
    if ($return === false) {
7085
      return ($removeEmptyValues === true ? [] : ['']);
7086
    }
7087
7088
    if (
7089 16
        $removeShortValues === null
7090
        &&
7091 16
        $removeEmptyValues === false
7092
    ) {
7093 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...
7094
    }
7095
7096
    $tmpReturn = self::reduce_string_array(
7097
        $return,
7098
        $removeEmptyValues,
7099
        $removeShortValues
7100
    );
7101
7102
    return $tmpReturn;
7103
  }
7104
7105
  /**
7106
   * Convert a string into an array of words.
7107
   *
7108
   * @param string   $str
7109
   * @param string   $charList          <p>Additional chars for the definition of "words".</p>
7110
   * @param bool     $removeEmptyValues <p>Remove empty values.</p>
7111
   * @param null|int $removeShortValues <p>The min. string length or null to disable</p>
7112
   *
7113
   * @return string[]
7114
   */
7115 14
  public static function str_to_words(string $str, string $charList = '', bool $removeEmptyValues = false, int $removeShortValues = null): array
7116
  {
7117 14
    if ('' === $str) {
7118 4
      return ($removeEmptyValues === true ? [] : ['']);
7119
    }
7120
7121 14
    $charList = self::rxClass($charList, '\pL');
7122
7123 14
    $return = \preg_split("/({$charList}+(?:[\p{Pd}’']{$charList}+)*)/u", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
7124
7125 14
    if ($return === false) {
7126
      return ($removeEmptyValues === true ? [] : ['']);
7127
    }
7128
7129
    if (
7130 14
        $removeShortValues === null
7131
        &&
7132 14
        $removeEmptyValues === false
7133
    ) {
7134 14
      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...
7135
    }
7136
7137 2
    $tmpReturn = self::reduce_string_array(
7138 2
        $return,
7139 2
        $removeEmptyValues,
7140 2
        $removeShortValues
7141
    );
7142
7143 2
    foreach ($tmpReturn as &$item) {
7144 2
      $item = (string)$item;
7145
    }
7146
7147 2
    return $tmpReturn;
7148
  }
7149
7150
  /**
7151
   * alias for "UTF8::to_ascii()"
7152
   *
7153
   * @see UTF8::to_ascii()
7154
   *
7155
   * @param string $str
7156
   * @param string $unknown
7157
   * @param bool   $strict
7158
   *
7159
   * @return string
7160
   */
7161 7
  public static function str_transliterate(string $str, string $unknown = '?', bool $strict = false): string
7162
  {
7163 7
    return self::to_ascii($str, $unknown, $strict);
7164
  }
7165
7166
  /**
7167
   * Truncates the string to a given length. If $substring is provided, and
7168
   * truncating occurs, the string is further truncated so that the substring
7169
   * may be appended without exceeding the desired length.
7170
   *
7171
   * @param string $str
7172
   * @param int    $length    <p>Desired length of the truncated string.</p>
7173
   * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
7174
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
7175
   *
7176
   * @return string String after truncating.
7177
   */
7178 22
  public static function str_truncate($str, int $length, string $substring = '', string $encoding = 'UTF-8'): string
7179
  {
7180
    // init
7181 22
    $str = (string)$str;
7182
7183 22
    if ('' === $str) {
7184
      return '';
7185
    }
7186
7187 22
    if ($length >= self::strlen($str, $encoding)) {
7188 4
      return $str;
7189
    }
7190
7191
    // Need to further trim the string so we can append the substring
7192 18
    $substringLength = self::strlen($substring, $encoding);
7193 18
    $length -= $substringLength;
7194
7195 18
    $truncated = self::substr($str, 0, $length, $encoding);
7196
7197 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

7197
    return /** @scrutinizer ignore-type */ $truncated . $substring;
Loading history...
7198
  }
7199
7200
  /**
7201
   * Truncates the string to a given length, while ensuring that it does not
7202
   * split words. If $substring is provided, and truncating occurs, the
7203
   * string is further truncated so that the substring may be appended without
7204
   * exceeding the desired length.
7205
   *
7206
   * @param string $str
7207
   * @param int    $length    <p>Desired length of the truncated string.</p>
7208
   * @param string $substring [optional] <p>The substring to append if it can fit. Default: ''</p>
7209
   * @param string $encoding  [optional] <p>Default: UTF-8</p>
7210
   *
7211
   * @return string String after truncating.
7212
   */
7213 23
  public static function str_truncate_safe(string $str, int $length, string $substring = '', string $encoding = 'UTF-8'): string
7214
  {
7215 23
    if ($length >= self::strlen($str, $encoding)) {
7216 4
      return $str;
7217
    }
7218
7219
    // need to further trim the string so we can append the substring
7220 19
    $substringLength = self::strlen($substring, $encoding);
7221 19
    $length -= $substringLength;
7222
7223 19
    $truncated = self::substr($str, 0, $length, $encoding);
7224 19
    if ($truncated === false) {
7225
      return '';
7226
    }
7227
7228
    // if the last word was truncated
7229 19
    $strPosSpace = self::strpos($str, ' ', $length - 1, $encoding);
7230 19
    if ($strPosSpace != $length) {
7231
      // find pos of the last occurrence of a space, get up to that
7232 12
      $lastPos = self::strrpos($truncated, ' ', 0, $encoding);
7233
7234 12
      if ($lastPos !== false || $strPosSpace !== false) {
7235 11
        $truncated = self::substr($truncated, 0, (int)$lastPos, $encoding);
7236
      }
7237
    }
7238
7239 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

7239
    $str = /** @scrutinizer ignore-type */ $truncated . $substring;
Loading history...
7240
7241 19
    return $str;
7242
  }
7243
7244
  /**
7245
   * Returns a lowercase and trimmed string separated by underscores.
7246
   * Underscores are inserted before uppercase characters (with the exception
7247
   * of the first character of the string), and in place of spaces as well as
7248
   * dashes.
7249
   *
7250
   * @param string $str
7251
   *
7252
   * @return string The underscored string.
7253
   */
7254 16
  public static function str_underscored(string $str): string
7255
  {
7256 16
    return self::str_delimit($str, '_');
7257
  }
7258
7259
  /**
7260
   * Returns an UpperCamelCase version of the supplied string. It trims
7261
   * surrounding spaces, capitalizes letters following digits, spaces, dashes
7262
   * and underscores, and removes spaces, dashes, underscores.
7263
   *
7264
   * @param string $str      <p>The input string.</p>
7265
   * @param string $encoding [optional] <p>Default: UTF-8</p>
7266
   *
7267
   * @return string String in UpperCamelCase.
7268
   */
7269 13
  public static function str_upper_camelize(string $str, string $encoding = 'UTF-8'): string
7270
  {
7271 13
    return self::str_upper_first(self::str_camelize($str, $encoding), $encoding);
7272
  }
7273
7274
  /**
7275
   * alias for "UTF8::ucfirst()"
7276
   *
7277
   * @see UTF8::ucfirst()
7278
   *
7279
   * @param string $str
7280
   * @param string $encoding
7281
   * @param bool   $cleanUtf8
7282
   *
7283
   * @return string
7284
   */
7285 58
  public static function str_upper_first(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
7286
  {
7287 58
    return self::ucfirst($str, $encoding, $cleanUtf8);
7288
  }
7289
7290
  /**
7291
   * Counts number of words in the UTF-8 string.
7292
   *
7293
   * @param string $str      <p>The input string.</p>
7294
   * @param int    $format   [optional] <p>
7295
   *                         <strong>0</strong> => return a number of words (default)<br>
7296
   *                         <strong>1</strong> => return an array of words<br>
7297
   *                         <strong>2</strong> => return an array of words with word-offset as key
7298
   *                         </p>
7299
   * @param string $charlist [optional] <p>Additional chars that contains to words and do not start a new word.</p>
7300
   *
7301
   * @return string[]|int The number of words in the string
7302
   */
7303 2
  public static function str_word_count(string $str, int $format = 0, string $charlist = '')
7304
  {
7305 2
    $strParts = self::str_to_words($str, $charlist);
7306
7307 2
    $len = \count($strParts);
7308
7309 2
    if ($format === 1) {
7310
7311 2
      $numberOfWords = [];
7312 2
      for ($i = 1; $i < $len; $i += 2) {
7313 2
        $numberOfWords[] = $strParts[$i];
7314
      }
7315
7316 2
    } elseif ($format === 2) {
7317
7318 2
      $numberOfWords = [];
7319 2
      $offset = self::strlen($strParts[0]);
7320 2
      for ($i = 1; $i < $len; $i += 2) {
7321 2
        $numberOfWords[$offset] = $strParts[$i];
7322 2
        $offset += self::strlen($strParts[$i]) + self::strlen($strParts[$i + 1]);
7323
      }
7324
7325
    } else {
7326
7327 2
      $numberOfWords = (int)(($len - 1) / 2);
7328
7329
    }
7330
7331 2
    return $numberOfWords;
7332
  }
7333
7334
  /**
7335
   * Case-insensitive string comparison.
7336
   *
7337
   * INFO: Case-insensitive version of UTF8::strcmp()
7338
   *
7339
   * @param string $str1     <p>The first string.</p>
7340
   * @param string $str2     <p>The second string.</p>
7341
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7342
   *
7343
   * @return int
7344
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
7345
   *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
7346
   *             <strong>0</strong> if they are equal.
7347
   */
7348 23
  public static function strcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
7349
  {
7350 23
    return self::strcmp(
7351 23
        self::strtocasefold($str1, true, false, $encoding, null, false),
7352 23
        self::strtocasefold($str2, true, false, $encoding, null, false)
7353
    );
7354
  }
7355
7356
  /**
7357
   * alias for "UTF8::strstr()"
7358
   *
7359
   * @see UTF8::strstr()
7360
   *
7361
   * @param string $haystack
7362
   * @param string $needle
7363
   * @param bool   $before_needle
7364
   * @param string $encoding
7365
   * @param bool   $cleanUtf8
7366
   *
7367
   * @return string|false
7368
   */
7369 2
  public static function strchr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7370
  {
7371 2
    return self::strstr($haystack, $needle, $before_needle, $encoding, $cleanUtf8);
7372
  }
7373
7374
  /**
7375
   * Case-sensitive string comparison.
7376
   *
7377
   * @param string $str1 <p>The first string.</p>
7378
   * @param string $str2 <p>The second string.</p>
7379
   *
7380
   * @return int
7381
   *              <strong>&lt; 0</strong> if str1 is less than str2<br>
7382
   *              <strong>&gt; 0</strong> if str1 is greater than str2<br>
7383
   *              <strong>0</strong> if they are equal.
7384
   */
7385 29
  public static function strcmp(string $str1, string $str2): int
7386
  {
7387
    /** @noinspection PhpUndefinedClassInspection */
7388 29
    return $str1 . '' === $str2 . '' ? 0 : \strcmp(
7389 24
        \Normalizer::normalize($str1, \Normalizer::NFD),
7390 29
        \Normalizer::normalize($str2, \Normalizer::NFD)
7391
    );
7392
  }
7393
7394
  /**
7395
   * Find length of initial segment not matching mask.
7396
   *
7397
   * @param string $str
7398
   * @param string $charList
7399
   * @param int    $offset
7400
   * @param int    $length
7401
   *
7402
   * @return int|null
7403
   */
7404 15
  public static function strcspn(string $str, string $charList, int $offset = 0, int $length = null)
7405
  {
7406 15
    if ('' === $charList .= '') {
7407 1
      return null;
7408
    }
7409
7410 14
    if ($offset || $length !== null) {
7411 2
      $strTmp = self::substr($str, $offset, $length);
7412 2
      if ($strTmp === false) {
7413
        return null;
7414
      }
7415 2
      $str = (string)$strTmp;
7416
    }
7417
7418 14
    if ('' === $str) {
7419 1
      return null;
7420
    }
7421
7422 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 null|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

7422
    if (\preg_match('/^(.*?)' . self::rxClass($charList) . '/us', $str, /** @scrutinizer ignore-type */ $length)) {
Loading history...
7423 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 null|integer. 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...
7424
    }
7425
7426 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 null|integer. 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...
7427
  }
7428
7429
  /**
7430
   * alias for "UTF8::stristr()"
7431
   *
7432
   * @see UTF8::stristr()
7433
   *
7434
   * @param string $haystack
7435
   * @param string $needle
7436
   * @param bool   $before_needle
7437
   * @param string $encoding
7438
   * @param bool   $cleanUtf8
7439
   *
7440
   * @return string|false
7441
   */
7442 1
  public static function strichr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7443
  {
7444 1
    return self::stristr($haystack, $needle, $before_needle, $encoding, $cleanUtf8);
7445
  }
7446
7447
  /**
7448
   * Create a UTF-8 string from code points.
7449
   *
7450
   * INFO: opposite to UTF8::codepoints()
7451
   *
7452
   * @param array $array <p>Integer or Hexadecimal codepoints.</p>
7453
   *
7454
   * @return string UTF-8 encoded string.
7455
   */
7456 4
  public static function string(array $array): string
7457
  {
7458 4
    return \implode(
7459 4
        '',
7460 4
        \array_map(
7461
            [
7462 4
                self::class,
7463
                'chr',
7464
            ],
7465 4
            $array
7466
        )
7467
    );
7468
  }
7469
7470
  /**
7471
   * Checks if string starts with "BOM" (Byte Order Mark Character) character.
7472
   *
7473
   * @param string $str <p>The input string.</p>
7474
   *
7475
   * @return bool
7476
   *              <strong>true</strong> if the string has BOM at the start,<br>
7477
   *              <strong>false</strong> otherwise.
7478
   */
7479 6
  public static function string_has_bom(string $str): bool
7480
  {
7481 6
    foreach (self::$BOM as $bomString => $bomByteLength) {
7482 6
      if (0 === \strpos($str, $bomString)) {
7483 6
        return true;
7484
      }
7485
    }
7486
7487 6
    return false;
7488
  }
7489
7490
  /**
7491
   * Strip HTML and PHP tags from a string + clean invalid UTF-8.
7492
   *
7493
   * @link http://php.net/manual/en/function.strip-tags.php
7494
   *
7495
   * @param string $str             <p>
7496
   *                                The input string.
7497
   *                                </p>
7498
   * @param string $allowable_tags  [optional] <p>
7499
   *                                You can use the optional second parameter to specify tags which should
7500
   *                                not be stripped.
7501
   *                                </p>
7502
   *                                <p>
7503
   *                                HTML comments and PHP tags are also stripped. This is hardcoded and
7504
   *                                can not be changed with allowable_tags.
7505
   *                                </p>
7506
   * @param bool   $cleanUtf8       [optional] <p>Remove non UTF-8 chars from the string.</p>
7507
   *
7508
   * @return string The stripped string.
7509
   */
7510 4
  public static function strip_tags(string $str, string $allowable_tags = null, bool $cleanUtf8 = false): string
7511
  {
7512 4
    if ('' === $str) {
7513 1
      return '';
7514
    }
7515
7516 4
    if ($cleanUtf8 === true) {
7517 2
      $str = self::clean($str);
7518
    }
7519
7520 4
    return \strip_tags($str, $allowable_tags);
7521
  }
7522
7523
  /**
7524
   * Strip all whitespace characters. This includes tabs and newline
7525
   * characters, as well as multibyte whitespace such as the thin space
7526
   * and ideographic space.
7527
   *
7528
   * @param string $str
7529
   *
7530
   * @return string
7531
   */
7532 36
  public static function strip_whitespace(string $str): string
7533
  {
7534 36
    if ('' === $str) {
7535 3
      return '';
7536
    }
7537
7538 33
    return (string)\preg_replace('/[[:space:]]+/u', '', $str);
7539
  }
7540
7541
  /**
7542
   * Finds position of first occurrence of a string within another, case insensitive.
7543
   *
7544
   * @link http://php.net/manual/en/function.mb-stripos.php
7545
   *
7546
   * @param string $haystack  <p>The string from which to get the position of the first occurrence of needle.</p>
7547
   * @param string $needle    <p>The string to find in haystack.</p>
7548
   * @param int    $offset    [optional] <p>The position in haystack to start searching.</p>
7549
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
7550
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
7551
   *
7552
   * @return int|false
7553
   *                   Return the <strong>(int)</strong> numeric position of the first occurrence of needle in the
7554
   *                   haystack string,<br> or <strong>false</strong> if needle is not found.
7555
   */
7556 75
  public static function stripos(string $haystack, string $needle, int $offset = 0, $encoding = 'UTF-8', bool $cleanUtf8 = false)
7557
  {
7558 75
    if ('' === $haystack || '' === $needle) {
7559 5
      return false;
7560
    }
7561
7562 74
    if ($cleanUtf8 === true) {
7563
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
7564
      // if invalid characters are found in $haystack before $needle
7565 1
      $haystack = self::clean($haystack);
7566 1
      $needle = self::clean($needle);
7567
    }
7568
7569 74
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7570 23
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7571
    }
7572
7573 74
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7574
      self::checkForSupport();
7575
    }
7576
7577 74
    if (self::$SUPPORT['mbstring'] === true) {
7578 74
      $returnTmp = \mb_stripos($haystack, $needle, $offset, $encoding);
7579 74
      if ($returnTmp !== false) {
7580 54
        return $returnTmp;
7581
      }
7582
    }
7583
7584
    if (
7585 31
        $encoding === 'UTF-8' // INFO: "grapheme_stripos()" can't handle other encodings
7586
        &&
7587 31
        $offset >= 0 // grapheme_stripos() can't handle negative offset
7588
        &&
7589 31
        self::$SUPPORT['intl'] === true
7590
    ) {
7591 31
      $returnTmp = \grapheme_stripos($haystack, $needle, $offset);
7592 31
      if ($returnTmp !== false) {
7593
        return $returnTmp;
7594
      }
7595
    }
7596
7597
    //
7598
    // fallback for ascii only
7599
    //
7600
7601 31
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
7602 15
      return \stripos($haystack, $needle, $offset);
7603
    }
7604
7605
    //
7606
    // fallback via vanilla php
7607
    //
7608
7609 20
    $haystack = self::strtocasefold($haystack, true, false, $encoding, null, false);
7610 20
    $needle = self::strtocasefold($needle, true, false, $encoding, null, false);
7611
7612 20
    return self::strpos($haystack, $needle, $offset, $encoding);
7613
  }
7614
7615
  /**
7616
   * Returns all of haystack starting from and including the first occurrence of needle to the end.
7617
   *
7618
   * @param string $haystack       <p>The input string. Must be valid UTF-8.</p>
7619
   * @param string $needle         <p>The string to look for. Must be valid UTF-8.</p>
7620
   * @param bool   $before_needle  [optional] <p>
7621
   *                               If <b>TRUE</b>, it returns the part of the
7622
   *                               haystack before the first occurrence of the needle (excluding the needle).
7623
   *                               </p>
7624
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
7625
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
7626
   *
7627
   * @return false|string A sub-string,<br>or <strong>false</strong> if needle is not found.
7628
   */
7629 19
  public static function stristr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7630
  {
7631 19
    if ('' === $haystack || '' === $needle) {
7632 6
      return false;
7633
    }
7634
7635 13
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7636 1
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7637
    }
7638
7639 13
    if ($cleanUtf8 === true) {
7640
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
7641
      // if invalid characters are found in $haystack before $needle
7642 1
      $needle = self::clean($needle);
7643 1
      $haystack = self::clean($haystack);
7644
    }
7645
7646 13
    if (!$needle) {
7647
      return $haystack;
7648
    }
7649
7650 13
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7651
      self::checkForSupport();
7652
    }
7653
7654
    if (
7655 13
        $encoding !== 'UTF-8'
7656
        &&
7657 13
        self::$SUPPORT['mbstring'] === false
7658
    ) {
7659
      \trigger_error('UTF8::stristr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
7660
    }
7661
7662 13
    if (self::$SUPPORT['mbstring'] === true) {
7663 13
      return \mb_stristr($haystack, $needle, $before_needle, $encoding);
7664
    }
7665
7666
    if (
7667
        $encoding === 'UTF-8' // INFO: "grapheme_stristr()" can't handle other encodings
7668
        &&
7669
        self::$SUPPORT['intl'] === true
7670
    ) {
7671
      $returnTmp = \grapheme_stristr($haystack, $needle, $before_needle);
7672
      if ($returnTmp !== false) {
7673
        return $returnTmp;
7674
      }
7675
    }
7676
7677
    if (self::is_ascii($needle) && self::is_ascii($haystack)) {
7678
      return \stristr($haystack, $needle, $before_needle);
7679
    }
7680
7681
    \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/usi', $haystack, $match);
7682
7683
    if (!isset($match[1])) {
7684
      return false;
7685
    }
7686
7687
    if ($before_needle) {
7688
      return $match[1];
7689
    }
7690
7691
    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

7691
    return self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($match[1]));
Loading history...
7692
  }
7693
7694
  /**
7695
   * Get the string length, not the byte-length!
7696
   *
7697
   * @link     http://php.net/manual/en/function.mb-strlen.php
7698
   *
7699
   * @param string $str       <p>The string being checked for length.</p>
7700
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
7701
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
7702
   *
7703
   * @return int|false
7704
   *             The number <strong>(int)</strong> of characters in the string $str having character encoding $encoding.
7705
   *             (One multi-byte character counted as +1).
7706
   *             <br>
7707
   *             Can return <strong>false</strong>, if e.g. mbstring is not installed and we process invalid chars.
7708
   */
7709 284
  public static function strlen(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
7710
  {
7711 284
    if ('' === $str) {
7712 37
      return 0;
7713
    }
7714
7715 282
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7716 81
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7717
    }
7718
7719
    //
7720
    // fallback for binary || ascii only
7721
    //
7722
7723
    if (
7724 282
        $encoding === 'CP850'
7725
        ||
7726 282
        $encoding === 'ASCII'
7727
    ) {
7728 2
      return self::strlen_in_byte($str);
7729
    }
7730
7731 282
    if ($cleanUtf8 === true) {
7732
      // "mb_strlen" and "\iconv_strlen" returns wrong length,
7733
      // if invalid characters are found in $str
7734 4
      $str = self::clean($str);
7735
    }
7736
7737 282
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7738
      self::checkForSupport();
7739
    }
7740
7741
    if (
7742 282
        $encoding !== 'UTF-8'
7743
        &&
7744 282
        self::$SUPPORT['mbstring'] === false
7745
        &&
7746 282
        self::$SUPPORT['iconv'] === false
7747
    ) {
7748
      \trigger_error('UTF8::strlen() without mbstring / iconv cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
7749
    }
7750
7751
    //
7752
    // fallback via mbstring
7753
    //
7754
7755 282
    if (self::$SUPPORT['mbstring'] === true) {
7756 282
      $returnTmp = \mb_strlen($str, $encoding);
7757 282
      if ($returnTmp !== false) {
7758 282
        return $returnTmp;
7759
      }
7760
    }
7761
7762
    //
7763
    // fallback via iconv
7764
    //
7765
7766
    if (self::$SUPPORT['iconv'] === true) {
7767
      $returnTmp = \iconv_strlen($str, $encoding);
7768
      if ($returnTmp !== false) {
7769
        return $returnTmp;
7770
      }
7771
    }
7772
7773
    //
7774
    // fallback via intl
7775
    //
7776
7777
    if (
7778
        $encoding === 'UTF-8' // INFO: "grapheme_strlen()" can't handle other encodings
7779
        &&
7780
        self::$SUPPORT['intl'] === true
7781
    ) {
7782
      $returnTmp = \grapheme_strlen($str);
7783
      if ($returnTmp !== null) {
7784
        return $returnTmp;
7785
      }
7786
    }
7787
7788
    //
7789
    // fallback for ascii only
7790
    //
7791
7792
    if (self::is_ascii($str)) {
7793
      return \strlen($str);
7794
    }
7795
7796
    //
7797
    // fallback via vanilla php
7798
    //
7799
7800
    \preg_match_all('/./us', $str, $parts);
7801
7802
    $returnTmp = \count($parts[0]);
7803
    if ($returnTmp === 0 && isset($str[0])) {
7804
      return false;
7805
    }
7806
7807
    return $returnTmp;
7808
  }
7809
7810
  /**
7811
   * Get string length in byte.
7812
   *
7813
   * @param string $str
7814
   *
7815
   * @return int
7816
   */
7817 192
  public static function strlen_in_byte(string $str): int
7818
  {
7819 192
    if ($str === '') {
7820
      return 0;
7821
    }
7822
7823 192
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7824
      self::checkForSupport();
7825
    }
7826
7827 192
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
7828
      // "mb_" is available if overload is used, so use it ...
7829 192
      return \mb_strlen($str, 'CP850'); // 8-BIT
7830
    }
7831
7832
    return \strlen($str);
7833
  }
7834
7835
  /**
7836
   * Case insensitive string comparisons using a "natural order" algorithm.
7837
   *
7838
   * INFO: natural order version of UTF8::strcasecmp()
7839
   *
7840
   * @param string $str1     <p>The first string.</p>
7841
   * @param string $str2     <p>The second string.</p>
7842
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7843
   *
7844
   * @return int
7845
   *             <strong>&lt; 0</strong> if str1 is less than str2<br>
7846
   *             <strong>&gt; 0</strong> if str1 is greater than str2<br>
7847
   *             <strong>0</strong> if they are equal
7848
   */
7849 2
  public static function strnatcasecmp(string $str1, string $str2, string $encoding = 'UTF-8'): int
7850
  {
7851 2
    return self::strnatcmp(
7852 2
        self::strtocasefold($str1, true, false, $encoding, null, false),
7853 2
        self::strtocasefold($str2, true, false, $encoding, null, false)
7854
    );
7855
  }
7856
7857
  /**
7858
   * String comparisons using a "natural order" algorithm
7859
   *
7860
   * INFO: natural order version of UTF8::strcmp()
7861
   *
7862
   * @link  http://php.net/manual/en/function.strnatcmp.php
7863
   *
7864
   * @param string $str1 <p>The first string.</p>
7865
   * @param string $str2 <p>The second string.</p>
7866
   *
7867
   * @return int
7868
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
7869
   *             <strong>&gt; 0</strong> if str1 is greater than str2;<br>
7870
   *             <strong>0</strong> if they are equal
7871
   */
7872 4
  public static function strnatcmp(string $str1, string $str2): int
7873
  {
7874 4
    return $str1 . '' === $str2 . '' ? 0 : \strnatcmp(self::strtonatfold($str1), self::strtonatfold($str2));
7875
  }
7876
7877
  /**
7878
   * Case-insensitive string comparison of the first n characters.
7879
   *
7880
   * @link  http://php.net/manual/en/function.strncasecmp.php
7881
   *
7882
   * @param string $str1     <p>The first string.</p>
7883
   * @param string $str2     <p>The second string.</p>
7884
   * @param int    $len      <p>The length of strings to be used in the comparison.</p>
7885
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
7886
   *
7887
   * @return int
7888
   *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
7889
   *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
7890
   *             <strong>0</strong> if they are equal
7891
   */
7892 2
  public static function strncasecmp(string $str1, string $str2, int $len, string $encoding = 'UTF-8'): int
7893
  {
7894 2
    return self::strncmp(
7895 2
        self::strtocasefold($str1, true, false, $encoding, null, false),
7896 2
        self::strtocasefold($str2, true, false, $encoding, null, false),
7897 2
        $len
7898
    );
7899
  }
7900
7901
  /**
7902
   * String comparison of the first n characters.
7903
   *
7904
   * @link  http://php.net/manual/en/function.strncmp.php
7905
   *
7906
   * @param string $str1 <p>The first string.</p>
7907
   * @param string $str2 <p>The second string.</p>
7908
   * @param int    $len  <p>Number of characters to use in the comparison.</p>
7909
   *
7910
   * @return int
7911
   *             <strong>&lt; 0</strong> if <i>str1</i> is less than <i>str2</i>;<br>
7912
   *             <strong>&gt; 0</strong> if <i>str1</i> is greater than <i>str2</i>;<br>
7913
   *             <strong>0</strong> if they are equal
7914
   */
7915 4
  public static function strncmp(string $str1, string $str2, int $len): int
7916
  {
7917 4
    $str1 = (string)self::substr($str1, 0, $len);
7918 4
    $str2 = (string)self::substr($str2, 0, $len);
7919
7920 4
    return self::strcmp($str1, $str2);
7921
  }
7922
7923
  /**
7924
   * Search a string for any of a set of characters.
7925
   *
7926
   * @link  http://php.net/manual/en/function.strpbrk.php
7927
   *
7928
   * @param string $haystack  <p>The string where char_list is looked for.</p>
7929
   * @param string $char_list <p>This parameter is case sensitive.</p>
7930
   *
7931
   * @return string|false String starting from the character found, or false if it is not found.
7932
   */
7933 2
  public static function strpbrk(string $haystack, string $char_list)
7934
  {
7935 2
    if ('' === $haystack || '' === $char_list) {
7936 2
      return false;
7937
    }
7938
7939 2
    if (\preg_match('/' . self::rxClass($char_list) . '/us', $haystack, $m)) {
7940 2
      return \substr($haystack, (int)\strpos($haystack, $m[0]));
7941
    }
7942
7943 2
    return false;
7944
  }
7945
7946
  /**
7947
   * Find position of first occurrence of string in a string.
7948
   *
7949
   * @link http://php.net/manual/en/function.mb-strpos.php
7950
   *
7951
   * @param string     $haystack  <p>The string from which to get the position of the first occurrence of needle.</p>
7952
   * @param string|int $needle    <p>The string to find in haystack.<br>Or a code point as int.</p>
7953
   * @param int        $offset    [optional] <p>The search offset. If it is not specified, 0 is used.</p>
7954
   * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
7955
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
7956
   *
7957
   * @return int|false
7958
   *                   The <strong>(int)</strong> numeric position of the first occurrence of needle in the haystack
7959
   *                   string.<br> If needle is not found it returns false.
7960
   */
7961 142
  public static function strpos(string $haystack, $needle, int $offset = 0, $encoding = 'UTF-8', bool $cleanUtf8 = false)
7962
  {
7963 142
    if ('' === $haystack) {
7964 4
      return false;
7965
    }
7966
7967
    // iconv and mbstring do not support integer $needle
7968 141
    if ((int)$needle === $needle && $needle >= 0) {
7969
      $needle = (string)self::chr($needle);
7970
    }
7971 141
    $needle = (string)$needle;
7972
7973 141
    if ('' === $needle) {
7974 2
      return false;
7975
    }
7976
7977 141
    if ($cleanUtf8 === true) {
7978
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
7979
      // if invalid characters are found in $haystack before $needle
7980 3
      $needle = self::clean($needle);
7981 3
      $haystack = self::clean($haystack);
7982
    }
7983
7984 141
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
7985 55
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
7986
    }
7987
7988 141
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
7989
      self::checkForSupport();
7990
    }
7991
7992
    //
7993
    // fallback for binary || ascii only
7994
    //
7995
7996
    if (
7997 141
        $encoding === 'CP850'
7998
        ||
7999 141
        $encoding === 'ASCII'
8000
    ) {
8001 2
      return self::strpos_in_byte($haystack, $needle, $offset);
8002
    }
8003
8004
    if (
8005 141
        $encoding !== 'UTF-8'
8006
        &&
8007 141
        self::$SUPPORT['iconv'] === false
8008
        &&
8009 141
        self::$SUPPORT['mbstring'] === false
8010
    ) {
8011
      \trigger_error('UTF8::strpos() without mbstring / iconv cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8012
    }
8013
8014
    //
8015
    // fallback via mbstring
8016
    //
8017
8018 141
    if (self::$SUPPORT['mbstring'] === true) {
8019 141
      $returnTmp = \mb_strpos($haystack, $needle, $offset, $encoding);
8020 141
      if ($returnTmp !== false) {
8021 86
        return $returnTmp;
8022
      }
8023
    }
8024
8025
    //
8026
    // fallback via intl
8027
    //
8028
8029
    if (
8030 69
        $encoding === 'UTF-8' // INFO: "grapheme_strpos()" can't handle other encodings
8031
        &&
8032 69
        $offset >= 0 // grapheme_strpos() can't handle negative offset
8033
        &&
8034 69
        self::$SUPPORT['intl'] === true
8035
    ) {
8036 69
      $returnTmp = \grapheme_strpos($haystack, $needle, $offset);
8037 69
      if ($returnTmp !== false) {
8038
        return $returnTmp;
8039
      }
8040
    }
8041
8042
    //
8043
    // fallback via iconv
8044
    //
8045
8046
    if (
8047 69
        $offset >= 0 // iconv_strpos() can't handle negative offset
8048
        &&
8049 69
        self::$SUPPORT['iconv'] === true
8050
    ) {
8051
      // ignore invalid negative offset to keep compatibility
8052
      // with php < 5.5.35, < 5.6.21, < 7.0.6
8053 69
      $returnTmp = \iconv_strpos($haystack, $needle, $offset > 0 ? $offset : 0, $encoding);
8054 69
      if ($returnTmp !== false) {
8055
        return $returnTmp;
8056
      }
8057
    }
8058
8059
    //
8060
    // fallback for ascii only
8061
    //
8062
8063 69
    if (($haystackIsAscii = self::is_ascii($haystack)) && self::is_ascii($needle)) {
8064 35
      return \strpos($haystack, $needle, $offset);
8065
    }
8066
8067
    //
8068
    // fallback via vanilla php
8069
    //
8070
8071 39
    if ($haystackIsAscii) {
8072
      $haystackTmp = \substr($haystack, $offset);
8073
    } else {
8074 39
      $haystackTmp = self::substr($haystack, $offset, null, $encoding);
8075
    }
8076 39
    if ($haystackTmp === false) {
8077
      $haystackTmp = '';
8078
    }
8079 39
    $haystack = (string)$haystackTmp;
8080
8081 39
    if ($offset < 0) {
8082 2
      $offset = 0;
8083
    }
8084
8085 39
    $pos = \strpos($haystack, $needle);
8086 39
    if ($pos === false) {
8087 39
      return false;
8088
    }
8089
8090 2
    if ($pos) {
8091 2
      return ($offset + (self::strlen(substr($haystack, 0, $pos), $encoding)));
8092
    }
8093
8094
    return ($offset + 0);
8095
  }
8096
8097
  /**
8098
   * Find position of first occurrence of string in a string.
8099
   *
8100
   * @param string $haystack <p>
8101
   *                         The string being checked.
8102
   *                         </p>
8103
   * @param string $needle   <p>
8104
   *                         The position counted from the beginning of haystack.
8105
   *                         </p>
8106
   * @param int    $offset   [optional] <p>
8107
   *                         The search offset. If it is not specified, 0 is used.
8108
   *                         </p>
8109
   *
8110
   * @return int|false The numeric position of the first occurrence of needle in the
8111
   *                   haystack string. If needle is not found, it returns false.
8112
   */
8113 77
  public static function strpos_in_byte(string $haystack, string $needle, int $offset = 0)
8114
  {
8115 77
    if ($haystack === '' || $needle === '') {
8116
      return false;
8117
    }
8118
8119 77
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8120
      self::checkForSupport();
8121
    }
8122
8123 77
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8124
      // "mb_" is available if overload is used, so use it ...
8125 77
      return \mb_strpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8126
    }
8127
8128
    return \strpos($haystack, $needle, $offset);
8129
  }
8130
8131
  /**
8132
   * Finds the last occurrence of a character in a string within another.
8133
   *
8134
   * @link http://php.net/manual/en/function.mb-strrchr.php
8135
   *
8136
   * @param string $haystack      <p>The string from which to get the last occurrence of needle.</p>
8137
   * @param string $needle        <p>The string to find in haystack</p>
8138
   * @param bool   $before_needle [optional] <p>
8139
   *                              Determines which portion of haystack
8140
   *                              this function returns.
8141
   *                              If set to true, it returns all of haystack
8142
   *                              from the beginning to the last occurrence of needle.
8143
   *                              If set to false, it returns all of haystack
8144
   *                              from the last occurrence of needle to the end,
8145
   *                              </p>
8146
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
8147
   * @param bool   $cleanUtf8     [optional] <p>Remove non UTF-8 chars from the string.</p>
8148
   *
8149
   * @return string|false The portion of haystack or false if needle is not found.
8150
   */
8151 4
  public static function strrchr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8152
  {
8153 4
    if ('' === $haystack || '' === $needle) {
8154 2
      return false;
8155
    }
8156
8157 4
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8158 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8159
    }
8160
8161 4
    if ($cleanUtf8 === true) {
8162
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8163
      // if invalid characters are found in $haystack before $needle
8164 2
      $needle = self::clean($needle);
8165 2
      $haystack = self::clean($haystack);
8166
    }
8167
8168 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8169
      self::checkForSupport();
8170
    }
8171
8172
    if (
8173 4
        $encoding !== 'UTF-8'
8174
        &&
8175 4
        self::$SUPPORT['mbstring'] === false
8176
    ) {
8177
      \trigger_error('UTF8::strrchr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8178
    }
8179
8180 4
    if (self::$SUPPORT['mbstring'] === true) {
8181 4
      return \mb_strrchr($haystack, $needle, $before_needle, $encoding);
8182
    }
8183
8184
    //
8185
    // fallback for binary || ascii only
8186
    //
8187
8188
    if (
8189
        $before_needle === false
8190
        &&
8191
        (
8192
            $encoding === 'CP850'
8193
            ||
8194
            $encoding === 'ASCII'
8195
        )
8196
    ) {
8197
      return \strrchr($haystack, $needle);
8198
    }
8199
8200
    //
8201
    // fallback via iconv
8202
    //
8203
8204
    if (self::$SUPPORT['iconv'] === true) {
8205
      $needleTmp = self::substr($needle, 0, 1, $encoding);
8206
      if ($needleTmp === false) {
8207
        return false;
8208
      }
8209
      $needle = (string)$needleTmp;
8210
8211
      $pos = \iconv_strrpos($haystack, $needle, $encoding);
8212
      if (false === $pos) {
8213
        return false;
8214
      }
8215
8216
      if ($before_needle) {
8217
        return self::substr($haystack, 0, $pos, $encoding);
8218
      }
8219
8220
      return self::substr($haystack, $pos, null, $encoding);
8221
    }
8222
8223
    //
8224
    // fallback via vanilla php
8225
    //
8226
8227
    $needleTmp = self::substr($needle, 0, 1, $encoding);
8228
    if ($needleTmp === false) {
8229
      return false;
8230
    }
8231
    $needle = (string)$needleTmp;
8232
8233
    $pos = self::strrpos($haystack, $needle, null, $encoding);
8234
    if ($pos === false) {
8235
      return false;
8236
    }
8237
8238
    if ($before_needle) {
8239
      return self::substr($haystack, 0, $pos, $encoding);
8240
    }
8241
8242
    return self::substr($haystack, $pos, null, $encoding);
8243
  }
8244
8245
  /**
8246
   * Reverses characters order in the string.
8247
   *
8248
   * @param string $str <p>The input string.</p>
8249
   *
8250
   * @return string The string with characters in the reverse sequence.
8251
   */
8252 10
  public static function strrev(string $str): string
8253
  {
8254 10
    if ('' === $str) {
8255 4
      return '';
8256
    }
8257
8258 8
    $reversed = '';
8259 8
    $i = self::strlen($str);
8260 8
    while ($i--) {
8261 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

8261
      $reversed .= self::substr($str, /** @scrutinizer ignore-type */ $i, 1);
Loading history...
8262
    }
8263
8264 8
    return $reversed;
8265
  }
8266
8267
  /**
8268
   * Finds the last occurrence of a character in a string within another, case insensitive.
8269
   *
8270
   * @link http://php.net/manual/en/function.mb-strrichr.php
8271
   *
8272
   * @param string $haystack       <p>The string from which to get the last occurrence of needle.</p>
8273
   * @param string $needle         <p>The string to find in haystack.</p>
8274
   * @param bool   $before_needle  [optional] <p>
8275
   *                               Determines which portion of haystack
8276
   *                               this function returns.
8277
   *                               If set to true, it returns all of haystack
8278
   *                               from the beginning to the last occurrence of needle.
8279
   *                               If set to false, it returns all of haystack
8280
   *                               from the last occurrence of needle to the end,
8281
   *                               </p>
8282
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
8283
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
8284
   *
8285
   * @return string|false The portion of haystack or<br>false if needle is not found.
8286
   */
8287 3
  public static function strrichr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8288
  {
8289 3
    if ('' === $haystack || '' === $needle) {
8290 2
      return false;
8291
    }
8292
8293 3
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8294 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8295
    }
8296
8297 3
    if ($cleanUtf8 === true) {
8298
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8299
      // if invalid characters are found in $haystack before $needle
8300 2
      $needle = self::clean($needle);
8301 2
      $haystack = self::clean($haystack);
8302
    }
8303
8304 3
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8305
      self::checkForSupport();
8306
    }
8307
8308
    //
8309
    // fallback via mbstring
8310
    //
8311
8312 3
    if (self::$SUPPORT['mbstring'] === true) {
8313 3
      return \mb_strrichr($haystack, $needle, $before_needle, $encoding);
8314
    }
8315
8316
    //
8317
    // fallback via vanilla php
8318
    //
8319
8320
    $needleTmp = self::substr($needle, 0, 1, $encoding);
8321
    if ($needleTmp === false) {
8322
      return false;
8323
    }
8324
    $needle = (string)$needleTmp;
8325
8326
    $pos = self::strripos($haystack, $needle, 0, $encoding);
8327
    if ($pos === false) {
8328
      return false;
8329
    }
8330
8331
    if ($before_needle) {
8332
      return self::substr($haystack, 0, $pos, $encoding);
8333
    }
8334
8335
    return self::substr($haystack, $pos, null, $encoding);
8336
  }
8337
8338
  /**
8339
   * Find position of last occurrence of a case-insensitive string.
8340
   *
8341
   * @param string     $haystack  <p>The string to look in.</p>
8342
   * @param string|int $needle    <p>The string to look for.</p>
8343
   * @param int        $offset    [optional] <p>Number of characters to ignore in the beginning or end.</p>
8344
   * @param string     $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
8345
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8346
   *
8347
   * @return int|false
8348
   *                   The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
8349
   *                   string.<br>If needle is not found, it returns false.
8350
   */
8351 4
  public static function strripos(string $haystack, $needle, int $offset = 0, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8352
  {
8353 4
    if ('' === $haystack) {
8354
      return false;
8355
    }
8356
8357
    // iconv and mbstring do not support integer $needle
8358 4
    if ((int)$needle === $needle && $needle >= 0) {
8359
      $needle = (string)self::chr($needle);
8360
    }
8361 4
    $needle = (string)$needle;
8362
8363 4
    if ('' === $needle) {
8364
      return false;
8365
    }
8366
8367 4
    if ($cleanUtf8 === true) {
8368
      // mb_strripos() && iconv_strripos() is not tolerant to invalid characters
8369 2
      $needle = self::clean($needle);
8370 2
      $haystack = self::clean($haystack);
8371
    }
8372
8373 4
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8374 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8375
    }
8376
8377
    //
8378
    // fallback for binary || ascii only
8379
    //
8380
8381
    if (
8382 4
        $encoding === 'CP850'
8383
        ||
8384 4
        $encoding === 'ASCII'
8385
    ) {
8386
      return self::strripos_in_byte($haystack, $needle, $offset);
8387
    }
8388
8389 4
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8390
      self::checkForSupport();
8391
    }
8392
8393
    if (
8394 4
        $encoding !== 'UTF-8'
8395
        &&
8396 4
        self::$SUPPORT['mbstring'] === false
8397
    ) {
8398
      \trigger_error('UTF8::strripos() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8399
    }
8400
8401
    //
8402
    // fallback via mbstrig
8403
    //
8404
8405 4
    if (self::$SUPPORT['mbstring'] === true) {
8406 4
      return \mb_strripos($haystack, $needle, $offset, $encoding);
8407
    }
8408
8409
    //
8410
    // fallback via intl
8411
    //
8412
8413
    if (
8414
        $encoding === 'UTF-8' // INFO: "grapheme_strripos()" can't handle other encodings
8415
        &&
8416
        $offset >= 0 // grapheme_strripos() can't handle negative offset
8417
        &&
8418
        self::$SUPPORT['intl'] === true
8419
    ) {
8420
      $returnTmp = \grapheme_strripos($haystack, $needle, $offset);
8421
      if ($returnTmp !== false) {
8422
        return $returnTmp;
8423
      }
8424
    }
8425
8426
    //
8427
    // fallback for ascii only
8428
    //
8429
8430
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
8431
      return self::strripos_in_byte($haystack, $needle, $offset);
8432
    }
8433
8434
    //
8435
    // fallback via vanilla php
8436
    //
8437
8438
    $haystack = self::strtocasefold($haystack, true, false, $encoding);
8439
    $needle = self::strtocasefold($needle, true, false, $encoding);
8440
8441
    return self::strrpos($haystack, $needle, $offset, $encoding, $cleanUtf8);
8442
  }
8443
8444
  /**
8445
   * Finds position of last occurrence of a string within another, case insensitive.
8446
   *
8447
   * @param string $haystack <p>
8448
   *                         The string from which to get the position of the last occurrence
8449
   *                         of needle.
8450
   *                         </p>
8451
   * @param string $needle   <p>
8452
   *                         The string to find in haystack.
8453
   *                         </p>
8454
   * @param int    $offset   [optional] <p>
8455
   *                         The position in haystack
8456
   *                         to start searching.
8457
   *                         </p>
8458
   *
8459
   * @return int|false Return the numeric position of the last occurrence of needle in the
8460
   *                   haystack string, or false if needle is not found.
8461
   */
8462
  public static function strripos_in_byte(string $haystack, string $needle, int $offset = 0)
8463
  {
8464
    if ($haystack === '' || $needle === '') {
8465
      return false;
8466
    }
8467
8468
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8469
      self::checkForSupport();
8470
    }
8471
8472
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8473
      // "mb_" is available if overload is used, so use it ...
8474
      return \mb_strripos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8475
    }
8476
8477
    return \strripos($haystack, $needle, $offset);
8478
  }
8479
8480
  /**
8481
   * Find position of last occurrence of a string in a string.
8482
   *
8483
   * @link http://php.net/manual/en/function.mb-strrpos.php
8484
   *
8485
   * @param string     $haystack  <p>The string being checked, for the last occurrence of needle</p>
8486
   * @param string|int $needle    <p>The string to find in haystack.<br>Or a code point as int.</p>
8487
   * @param int        $offset    [optional] <p>May be specified to begin searching an arbitrary number of characters
8488
   *                              into the string. Negative values will stop searching at an arbitrary point prior to
8489
   *                              the end of the string.
8490
   *                              </p>
8491
   * @param string     $encoding  [optional] <p>Set the charset.</p>
8492
   * @param bool       $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8493
   *
8494
   * @return int|false
8495
   *                   The <strong>(int)</strong> numeric position of the last occurrence of needle in the haystack
8496
   *                   string.<br>If needle is not found, it returns false.
8497
   */
8498 38
  public static function strrpos(string $haystack, $needle, int $offset = null, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
8499
  {
8500 38
    if ('' === $haystack) {
8501 3
      return false;
8502
    }
8503
8504
    // iconv and mbstring do not support integer $needle
8505 37
    if ((int)$needle === $needle && $needle >= 0) {
8506 1
      $needle = (string)self::chr($needle);
8507
    }
8508 37
    $needle = (string)$needle;
8509
8510 37
    if ('' === $needle) {
8511 2
      return false;
8512
    }
8513
8514 37
    if ($cleanUtf8 === true) {
8515
      // \mb_strrpos && iconv_strrpos is not tolerant to invalid characters
8516 4
      $needle = self::clean($needle);
8517 4
      $haystack = self::clean($haystack);
8518
    }
8519
8520 37
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8521 14
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8522
    }
8523
8524
    //
8525
    // fallback for binary || ascii only
8526
    //
8527
8528
    if (
8529 37
        $encoding === 'CP850'
8530
        ||
8531 37
        $encoding === 'ASCII'
8532
    ) {
8533 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

8533
      return self::strrpos_in_byte($haystack, $needle, /** @scrutinizer ignore-type */ $offset);
Loading history...
8534
    }
8535
8536 37
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8537
      self::checkForSupport();
8538
    }
8539
8540
    if (
8541 37
        $encoding !== 'UTF-8'
8542
        &&
8543 37
        self::$SUPPORT['mbstring'] === false
8544
    ) {
8545
      \trigger_error('UTF8::strrpos() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8546
    }
8547
8548
    //
8549
    // fallback via mbstring
8550
    //
8551
8552 37
    if (self::$SUPPORT['mbstring'] === true) {
8553 37
      return \mb_strrpos($haystack, $needle, $offset, $encoding);
8554
    }
8555
8556
    //
8557
    // fallback via intl
8558
    //
8559
8560
    if (
8561
        $offset !== null
8562
        &&
8563
        $offset >= 0 // grapheme_strrpos() can't handle negative offset
8564
        &&
8565
        $encoding === 'UTF-8' // INFO: "grapheme_strrpos()" can't handle other encodings
8566
        &&
8567
        self::$SUPPORT['intl'] === true
8568
    ) {
8569
      $returnTmp = \grapheme_strrpos($haystack, $needle, $offset);
8570
      if ($returnTmp !== false) {
8571
        return $returnTmp;
8572
      }
8573
    }
8574
8575
    //
8576
    // fallback for ascii only
8577
    //
8578
8579
    if (
8580
        $offset !== null
8581
        &&
8582
        self::is_ascii($haystack)
8583
        &&
8584
        self::is_ascii($needle)
8585
    ) {
8586
      return self::strrpos_in_byte($haystack, $needle, $offset);
8587
    }
8588
8589
    //
8590
    // fallback via vanilla php
8591
    //
8592
8593
    $haystackTmp = null;
8594
    if ($offset > 0) {
8595
      $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

8595
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ $offset);
Loading history...
8596
    } elseif ($offset < 0) {
8597
      $haystackTmp = self::substr($haystack, 0, $offset);
8598
      $offset = 0;
8599
    }
8600
8601
    if ($haystackTmp !== null) {
8602
      if ($haystackTmp === false) {
8603
        $haystackTmp = '';
8604
      }
8605
      $haystack = (string)$haystackTmp;
8606
    }
8607
8608
    $pos = self::strrpos_in_byte($haystack, $needle);
8609
    if ($pos === false) {
8610
      return false;
8611
    }
8612
8613
    return $offset + self::strlen(self::substr_in_byte($haystack, 0, $pos));
8614
  }
8615
8616
  /**
8617
   * Find position of last occurrence of a string in a string.
8618
   *
8619
   * @param string $haystack <p>
8620
   *                         The string being checked, for the last occurrence
8621
   *                         of needle.
8622
   *                         </p>
8623
   * @param string $needle   <p>
8624
   *                         The string to find in haystack.
8625
   *                         </p>
8626
   * @param int    $offset   [optional] May be specified to begin searching an arbitrary number of characters into
8627
   *                         the string. Negative values will stop searching at an arbitrary point
8628
   *                         prior to the end of the string.
8629
   *
8630
   * @return int|false The numeric position of the last occurrence of needle in the
8631
   *                   haystack string. If needle is not found, it returns false.
8632
   */
8633 2
  public static function strrpos_in_byte(string $haystack, string $needle, int $offset = 0)
8634
  {
8635 2
    if ($haystack === '' || $needle === '') {
8636
      return false;
8637
    }
8638
8639 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8640
      self::checkForSupport();
8641
    }
8642
8643 2
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8644
      // "mb_" is available if overload is used, so use it ...
8645 2
      return \mb_strrpos($haystack, $needle, $offset, 'CP850'); // 8-BIT
8646
    }
8647
8648
    return \strrpos($haystack, $needle, $offset);
8649
  }
8650
8651
  /**
8652
   * Finds the length of the initial segment of a string consisting entirely of characters contained within a given
8653
   * mask.
8654
   *
8655
   * @param string $str    <p>The input string.</p>
8656
   * @param string $mask   <p>The mask of chars</p>
8657
   * @param int    $offset [optional]
8658
   * @param int    $length [optional]
8659
   *
8660
   * @return int
8661
   */
8662 10
  public static function strspn(string $str, string $mask, int $offset = 0, int $length = null): int
8663
  {
8664 10
    if ($offset || $length !== null) {
8665 2
      $strTmp = self::substr($str, $offset, $length);
8666 2
      if ($strTmp === false) {
8667
        $strTmp = '';
8668
      }
8669 2
      $str = (string)$strTmp;
8670
    }
8671
8672 10
    if ('' === $str || '' === $mask) {
8673 2
      return 0;
8674
    }
8675
8676 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 null|array 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

8676
    return \preg_match('/^' . self::rxClass($mask) . '+/u', $str, /** @scrutinizer ignore-type */ $str) ? self::strlen($str[0]) : 0;
Loading history...
8677
  }
8678
8679
  /**
8680
   * Returns part of haystack string from the first occurrence of needle to the end of haystack.
8681
   *
8682
   * @param string $haystack       <p>The input string. Must be valid UTF-8.</p>
8683
   * @param string $needle         <p>The string to look for. Must be valid UTF-8.</p>
8684
   * @param bool   $before_needle  [optional] <p>
8685
   *                               If <b>TRUE</b>, strstr() returns the part of the
8686
   *                               haystack before the first occurrence of the needle (excluding the needle).
8687
   *                               </p>
8688
   * @param string $encoding       [optional] <p>Set the charset for e.g. "mb_" function</p>
8689
   * @param bool   $cleanUtf8      [optional] <p>Remove non UTF-8 chars from the string.</p>
8690
   *
8691
   * @return string|false
8692
   *                       A sub-string,<br>or <strong>false</strong> if needle is not found.
8693
   */
8694 5
  public static function strstr(string $haystack, string $needle, bool $before_needle = false, string $encoding = 'UTF-8', $cleanUtf8 = false)
8695
  {
8696 5
    if ('' === $haystack || '' === $needle) {
8697 2
      return false;
8698
    }
8699
8700 5
    if ($cleanUtf8 === true) {
8701
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8702
      // if invalid characters are found in $haystack before $needle
8703
      $needle = self::clean($needle);
8704
      $haystack = self::clean($haystack);
8705
    }
8706
8707 5
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8708 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8709
    }
8710
8711
    //
8712
    // fallback for binary || ascii only
8713
    //
8714
8715
    if (
8716 5
        $encoding === 'CP850'
8717
        ||
8718 5
        $encoding === 'ASCII'
8719
    ) {
8720
      return self::strstr_in_byte($haystack, $needle, $before_needle);
8721
    }
8722
8723 5
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8724
      self::checkForSupport();
8725
    }
8726
8727
    if (
8728 5
        $encoding !== 'UTF-8'
8729
        &&
8730 5
        self::$SUPPORT['mbstring'] === false
8731
    ) {
8732
      \trigger_error('UTF8::strstr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
8733
    }
8734
8735
    //
8736
    // fallback via mbstring
8737
    //
8738
8739 5
    if (self::$SUPPORT['mbstring'] === true) {
8740 5
      return \mb_strstr($haystack, $needle, $before_needle, $encoding);
8741
    }
8742
8743
    //
8744
    // fallback via intl
8745
    //
8746
8747
    if (
8748
        $encoding === 'UTF-8' // INFO: "grapheme_strstr()" can't handle other encodings
8749
        &&
8750
        self::$SUPPORT['intl'] === true
8751
    ) {
8752
      $returnTmp = \grapheme_strstr($haystack, $needle, $before_needle);
8753
      if ($returnTmp !== false) {
8754
        return $returnTmp;
8755
      }
8756
    }
8757
8758
    //
8759
    // fallback for ascii only
8760
    //
8761
8762
    if (self::is_ascii($haystack) && self::is_ascii($needle)) {
8763
      return self::strstr_in_byte($haystack, $needle, $before_needle);
8764
    }
8765
8766
    //
8767
    // fallback via vanilla php
8768
    //
8769
8770
    \preg_match('/^(.*?)' . \preg_quote($needle, '/') . '/us', $haystack, $match);
8771
8772
    if (!isset($match[1])) {
8773
      return false;
8774
    }
8775
8776
    if ($before_needle) {
8777
      return $match[1];
8778
    }
8779
8780
    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

8780
    return self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($match[1]));
Loading history...
8781
  }
8782
8783
  /**
8784
   *  * Finds first occurrence of a string within another.
8785
   *
8786
   * @param string $haystack      <p>
8787
   *                              The string from which to get the first occurrence
8788
   *                              of needle.
8789
   *                              </p>
8790
   * @param string $needle        <p>
8791
   *                              The string to find in haystack.
8792
   *                              </p>
8793
   * @param bool   $before_needle [optional] <p>
8794
   *                              Determines which portion of haystack
8795
   *                              this function returns.
8796
   *                              If set to true, it returns all of haystack
8797
   *                              from the beginning to the first occurrence of needle.
8798
   *                              If set to false, it returns all of haystack
8799
   *                              from the first occurrence of needle to the end,
8800
   *                              </p>
8801
   *
8802
   * @return string|false The portion of haystack,
8803
   *                      or false if needle is not found.
8804
   */
8805
  public static function strstr_in_byte(string $haystack, string $needle, bool $before_needle = false)
8806
  {
8807
    if ($haystack === '' || $needle === '') {
8808
      return false;
8809
    }
8810
8811
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8812
      self::checkForSupport();
8813
    }
8814
8815
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
8816
      // "mb_" is available if overload is used, so use it ...
8817
      return \mb_strstr($haystack, $needle, $before_needle, 'CP850'); // 8-BIT
8818
    }
8819
8820
    return \strstr($haystack, $needle, $before_needle);
8821
  }
8822
8823
  /**
8824
   * Unicode transformation for case-less matching.
8825
   *
8826
   * @link http://unicode.org/reports/tr21/tr21-5.html
8827
   *
8828
   * @param string      $str       <p>The input string.</p>
8829
   * @param bool        $full      [optional] <p>
8830
   *                               <b>true</b>, replace full case folding chars (default)<br>
8831
   *                               <b>false</b>, use only limited static array [UTF8::$COMMON_CASE_FOLD]
8832
   *                               </p>
8833
   * @param bool        $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
8834
   * @param string      $encoding  [optional] <p>Set the charset.</p>
8835
   * @param string|null $lang      [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8836
   * @param bool        $lower     [optional] <p>Use lowercase string, otherwise use uppercase string. PS: uppercase is
8837
   *                               for some languages better ...</p>
8838
   *
8839
   * @return string
8840
   */
8841 53
  public static function strtocasefold(
8842
      string $str,
8843
      bool $full = true,
8844
      bool $cleanUtf8 = false,
8845
      string $encoding = 'UTF-8',
8846
      string $lang = null,
8847
      $lower = true
8848
  ): string
8849
  {
8850 53
    if ('' === $str) {
8851 5
      return '';
8852
    }
8853
8854 52
    $str = self::fixStrCaseHelper($str, $lower, $full);
8855
8856 52
    if ($lower === true) {
8857 2
      return self::strtolower($str, $encoding, $cleanUtf8, $lang);
8858
    }
8859
8860 50
    return self::strtoupper($str, $encoding, $cleanUtf8, $lang);
8861
  }
8862
8863
  /**
8864
   * Make a string lowercase.
8865
   *
8866
   * @link http://php.net/manual/en/function.mb-strtolower.php
8867
   *
8868
   * @param string      $str                   <p>The string being lowercased.</p>
8869
   * @param string      $encoding              [optional] <p>Set the charset for e.g. "mb_" function</p>
8870
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
8871
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8872
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
8873
   *
8874
   * @return string String with all alphabetic characters converted to lowercase.
8875
   */
8876 151
  public static function strtolower($str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
8877
  {
8878
    // init
8879 151
    $str = (string)$str;
8880
8881 151
    if ('' === $str) {
8882 4
      return '';
8883
    }
8884
8885 149
    if ($cleanUtf8 === true) {
8886
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8887
      // if invalid characters are found in $haystack before $needle
8888 4
      $str = self::clean($str);
8889
    }
8890
8891 149
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8892 94
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8893
    }
8894
8895
    // hack for old php version or for the polyfill ...
8896 149
    if ($tryToKeepStringLength === true) {
8897
      $str = self::fixStrCaseHelper($str, true);
8898
    }
8899
8900 149
    if ($lang !== null) {
8901
8902 2
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8903
        self::checkForSupport();
8904
      }
8905
8906 2
      if (self::$SUPPORT['intl'] === true) {
8907
8908 2
        $langCode = $lang . '-Lower';
8909 2
        if (!\in_array($langCode, self::$SUPPORT['intl__transliterator_list_ids'], true)) {
8910
          \trigger_error('UTF8::strtolower() cannot handle special language: ' . $lang, E_USER_WARNING);
8911
8912
          $langCode = 'Any-Lower';
8913
        }
8914
8915
        /** @noinspection PhpComposerExtensionStubsInspection */
8916 2
        return transliterator_transliterate($langCode, $str);
8917
      }
8918
8919
      \trigger_error('UTF8::strtolower() without intl cannot handle the "lang" parameter: ' . $lang, E_USER_WARNING);
8920
    }
8921
8922
    // always fallback via symfony polyfill
8923 149
    return \mb_strtolower($str, $encoding);
8924
  }
8925
8926
  /**
8927
   * Generic case sensitive transformation for collation matching.
8928
   *
8929
   * @param string $str <p>The input string</p>
8930
   *
8931
   * @return string
8932
   */
8933 6
  private static function strtonatfold(string $str): string
8934
  {
8935
    /** @noinspection PhpUndefinedClassInspection */
8936 6
    return \preg_replace('/\p{Mn}+/u', '', \Normalizer::normalize($str, \Normalizer::NFD));
8937
  }
8938
8939
  /**
8940
   * Make a string uppercase.
8941
   *
8942
   * @link http://php.net/manual/en/function.mb-strtoupper.php
8943
   *
8944
   * @param string      $str                   <p>The string being uppercased.</p>
8945
   * @param string      $encoding              [optional] <p>Set the charset.</p>
8946
   * @param bool        $cleanUtf8             [optional] <p>Remove non UTF-8 chars from the string.</p>
8947
   * @param string|null $lang                  [optional] <p>Set the language for special cases: az, el, lt, tr</p>
8948
   * @param bool        $tryToKeepStringLength [optional] <p>true === try to keep the string length: e.g. ẞ -> ß</p>
8949
   *
8950
   * @return string String with all alphabetic characters converted to uppercase.
8951
   */
8952 160
  public static function strtoupper($str, string $encoding = 'UTF-8', bool $cleanUtf8 = false, string $lang = null, bool $tryToKeepStringLength = false): string
8953
  {
8954
    // init
8955 160
    $str = (string)$str;
8956
8957 160
    if ('' === $str) {
8958 4
      return '';
8959
    }
8960
8961 158
    if ($cleanUtf8 === true) {
8962
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
8963
      // if invalid characters are found in $haystack before $needle
8964 3
      $str = self::clean($str);
8965
    }
8966
8967 158
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
8968 72
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
8969
    }
8970
8971
    // hack for old php version or for the polyfill ...
8972 158
    if ($tryToKeepStringLength === true) {
8973 2
      $str = self::fixStrCaseHelper($str, false);
8974
    }
8975
8976 158
    if ($lang !== null) {
8977
8978 2
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
8979
        self::checkForSupport();
8980
      }
8981
8982 2
      if (self::$SUPPORT['intl'] === true) {
8983
8984 2
        $langCode = $lang . '-Upper';
8985 2
        if (!\in_array($langCode, self::$SUPPORT['intl__transliterator_list_ids'], true)) {
8986
          \trigger_error('UTF8::strtoupper() without intl for special language: ' . $lang, E_USER_WARNING);
8987
8988
          $langCode = 'Any-Upper';
8989
        }
8990
8991
        /** @noinspection PhpComposerExtensionStubsInspection */
8992 2
        return transliterator_transliterate($langCode, $str);
8993
      }
8994
8995
      \trigger_error('UTF8::strtolower() without intl + PHP >= 5.4 cannot handle the "lang"-parameter: ' . $lang, E_USER_WARNING);
8996
    }
8997
8998
    // always fallback via symfony polyfill
8999 158
    return \mb_strtoupper($str, $encoding);
9000
  }
9001
9002
  /**
9003
   * Translate characters or replace sub-strings.
9004
   *
9005
   * @link  http://php.net/manual/en/function.strtr.php
9006
   *
9007
   * @param string          $str  <p>The string being translated.</p>
9008
   * @param string|string[] $from <p>The string replacing from.</p>
9009
   * @param string|string[] $to   <p>The string being translated to to.</p>
9010
   *
9011
   * @return string
9012
   *                This function returns a copy of str, translating all occurrences of each character in from to the
9013
   *                corresponding character in to.
9014
   */
9015 2
  public static function strtr(string $str, $from, $to = INF): string
9016
  {
9017 2
    if ('' === $str) {
9018
      return '';
9019
    }
9020
9021 2
    if ($from === $to) {
9022
      return $str;
9023
    }
9024
9025 2
    if (INF !== $to) {
9026 2
      $from = self::str_split($from);
9027 2
      $to = self::str_split($to);
9028 2
      $countFrom = \count($from);
9029 2
      $countTo = \count($to);
9030
9031 2
      if ($countFrom > $countTo) {
9032 2
        $from = \array_slice($from, 0, $countTo);
9033 2
      } elseif ($countFrom < $countTo) {
9034 2
        $to = \array_slice($to, 0, $countFrom);
9035
      }
9036
9037 2
      $from = \array_combine($from, $to);
9038
    }
9039
9040 2
    if (\is_string($from)) {
9041 2
      return \str_replace($from, '', $str);
9042
    }
9043
9044 2
    return \strtr($str, $from);
9045
  }
9046
9047
  /**
9048
   * Return the width of a string.
9049
   *
9050
   * @param string $str       <p>The input string.</p>
9051
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9052
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9053
   *
9054
   * @return int
9055
   */
9056 2
  public static function strwidth(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): int
9057
  {
9058 2
    if ('' === $str) {
9059 2
      return 0;
9060
    }
9061
9062 2
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9063 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9064
    }
9065
9066 2
    if ($cleanUtf8 === true) {
9067
      // iconv and mbstring are not tolerant to invalid encoding
9068
      // further, their behaviour is inconsistent with that of PHP's substr
9069 2
      $str = self::clean($str);
9070
    }
9071
9072 2
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9073
      self::checkForSupport();
9074
    }
9075
9076
    //
9077
    // fallback via mbstring
9078
    //
9079
9080 2
    if (self::$SUPPORT['mbstring'] === true) {
9081 2
      return \mb_strwidth($str, $encoding);
9082
    }
9083
9084
    //
9085
    // fallback via vanilla php
9086
    //
9087
9088
    if ('UTF-8' !== $encoding) {
9089
      $str = self::encode('UTF-8', $str, false, $encoding);
9090
    }
9091
9092
    $wide = 0;
9093
    $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);
9094
9095
    return ($wide << 1) + self::strlen($str, 'UTF-8');
9096
  }
9097
9098
  /**
9099
   * Get part of a string.
9100
   *
9101
   * @link http://php.net/manual/en/function.mb-substr.php
9102
   *
9103
   * @param string $str       <p>The string being checked.</p>
9104
   * @param int    $offset    <p>The first position used in str.</p>
9105
   * @param int    $length    [optional] <p>The maximum length of the returned string.</p>
9106
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9107
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9108
   *
9109
   * @return string|false
9110
   *                      The portion of <i>str</i> specified by the <i>offset</i> and
9111
   *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
9112
   *                      characters long, <b>FALSE</b> will be returned.
9113
   */
9114 392
  public static function substr(string $str, int $offset = 0, int $length = null, string $encoding = 'UTF-8', bool $cleanUtf8 = false)
9115
  {
9116 392
    if ('' === $str) {
9117 19
      return '';
9118
    }
9119
9120
    // Empty string
9121 386
    if ($length === 0) {
9122 14
      return '';
9123
    }
9124
9125 383
    if ($cleanUtf8 === true) {
9126
      // iconv and mbstring are not tolerant to invalid encoding
9127
      // further, their behaviour is inconsistent with that of PHP's substr
9128 2
      $str = self::clean($str);
9129
    }
9130
9131
    // Whole string
9132 383
    if (!$offset && $length === null) {
9133 38
      return $str;
9134
    }
9135
9136 354
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9137 157
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9138
    }
9139
9140 354
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9141
      self::checkForSupport();
9142
    }
9143
9144
    //
9145
    // fallback for binary || ascii only
9146
    //
9147
9148
    if (
9149 354
        $encoding === 'CP850'
9150
        ||
9151 354
        $encoding === 'ASCII'
9152
    ) {
9153 3
      return self::substr_in_byte($str, $offset, $length);
9154
    }
9155
9156
    //
9157
    // fallback via mbstring
9158
    //
9159
9160 351
    if (self::$SUPPORT['mbstring'] === true) {
9161 351
      $return = \mb_substr($str, $offset, $length ?? 2147483647, $encoding);
9162 351
      if ($return !== false) {
9163 346
        return $return;
9164
      }
9165
    }
9166
9167
    // otherwise we need the string-length and can't fake it via "2147483647"
9168 29
    $str_length = 0;
9169 29
    if ($offset || $length === null) {
9170 29
      $str_length = self::strlen($str, $encoding);
9171
    }
9172
9173
    // e.g.: invalid chars + mbstring not installed
9174 29
    if ($str_length === false) {
9175
      return false;
9176
    }
9177
9178
    // Empty string
9179 29
    if ($offset === $str_length && !$length) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $length of type null|integer 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...
9180 21
      return '';
9181
    }
9182
9183
    // Impossible
9184 8
    if ($offset && $offset > $str_length) {
9185
      // "false" is the php native return type here,
9186
      //  but we optimized this for performance ... see "2147483647" instead of "strlen"
9187 3
      return '';
9188
9189
    }
9190
9191 5
    if ($length === null) {
9192
      $length = (int)$str_length;
9193
    } else {
9194 5
      $length = (int)$length;
9195
    }
9196
9197
    if (
9198 5
        $encoding !== 'UTF-8'
9199
        &&
9200 5
        self::$SUPPORT['mbstring'] === false
9201
    ) {
9202
      \trigger_error('UTF8::substr() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
9203
    }
9204
9205
    //
9206
    // fallback via intl
9207
    //
9208
9209
    if (
9210 5
        $encoding === 'UTF-8' // INFO: "grapheme_substr()" can't handle other encodings
9211
        &&
9212 5
        $offset >= 0 // grapheme_substr() can't handle negative offset
9213
        &&
9214 5
        self::$SUPPORT['intl'] === true
9215
    ) {
9216 5
      $returnTmp = \grapheme_substr($str, $offset, $length);
9217 5
      if ($returnTmp !== false) {
9218
        return $returnTmp;
9219
      }
9220
    }
9221
9222
    //
9223
    // fallback via iconv
9224
    //
9225
9226
    if (
9227 5
        $length >= 0 // "iconv_substr()" can't handle negative length
9228
        &&
9229 5
        self::$SUPPORT['iconv'] === true
9230
    ) {
9231 5
      $returnTmp = \iconv_substr($str, $offset, $length);
9232 5
      if ($returnTmp !== false) {
9233 5
        return $returnTmp;
9234
      }
9235
    }
9236
9237
    //
9238
    // fallback for ascii only
9239
    //
9240
9241
    if (self::is_ascii($str)) {
9242
      return \substr($str, $offset, $length);
9243
    }
9244
9245
    //
9246
    // fallback via vanilla php
9247
    //
9248
9249
    // split to array, and remove invalid characters
9250
    $array = self::split($str);
9251
9252
    // extract relevant part, and join to make sting again
9253
    return \implode('', \array_slice($array, $offset, $length));
9254
  }
9255
9256
  /**
9257
   * Binary safe comparison of two strings from an offset, up to length characters.
9258
   *
9259
   * @param string   $str1               <p>The main string being compared.</p>
9260
   * @param string   $str2               <p>The secondary string being compared.</p>
9261
   * @param int      $offset             [optional] <p>The start position for the comparison. If negative, it starts
9262
   *                                     counting from the end of the string.</p>
9263
   * @param int|null $length             [optional] <p>The length of the comparison. The default value is the largest of
9264
   *                                     the length of the str compared to the length of main_str less the offset.</p>
9265
   * @param bool     $case_insensitivity [optional] <p>If case_insensitivity is TRUE, comparison is case
9266
   *                                     insensitive.</p>
9267
   *
9268
   * @return int
9269
   *             <strong>&lt; 0</strong> if str1 is less than str2;<br>
9270
   *             <strong>&gt; 0</strong> if str1 is greater than str2,<br>
9271
   *             <strong>0</strong> if they are equal.
9272
   */
9273 2
  public static function substr_compare(string $str1, string $str2, int $offset = 0, int $length = null, bool $case_insensitivity = false): int
9274
  {
9275
    if (
9276 2
        $offset !== 0
9277
        ||
9278 2
        $length !== null
9279
    ) {
9280 2
      $str1Tmp = self::substr($str1, $offset, $length);
9281 2
      if ($str1Tmp === false) {
9282
        $str1Tmp = '';
9283
      }
9284 2
      $str1 = (string)$str1Tmp;
9285
9286 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 null|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

9286
      $str2Tmp = self::substr($str2, 0, /** @scrutinizer ignore-type */ self::strlen($str1));
Loading history...
9287 2
      if ($str2Tmp === false) {
9288
        $str2Tmp = '';
9289
      }
9290 2
      $str2 = (string)$str2Tmp;
9291
    }
9292
9293 2
    if ($case_insensitivity === true) {
9294 2
      return self::strcasecmp($str1, $str2);
9295
    }
9296
9297 2
    return self::strcmp($str1, $str2);
9298
  }
9299
9300
  /**
9301
   * Count the number of substring occurrences.
9302
   *
9303
   * @link  http://php.net/manual/en/function.substr-count.php
9304
   *
9305
   * @param string $haystack   <p>The string to search in.</p>
9306
   * @param string $needle     <p>The substring to search for.</p>
9307
   * @param int    $offset     [optional] <p>The offset where to start counting.</p>
9308
   * @param int    $length     [optional] <p>
9309
   *                           The maximum length after the specified offset to search for the
9310
   *                           substring. It outputs a warning if the offset plus the length is
9311
   *                           greater than the haystack length.
9312
   *                           </p>
9313
   * @param string $encoding   [optional] <p>Set the charset for e.g. "mb_" function</p>
9314
   * @param bool   $cleanUtf8  [optional] <p>Remove non UTF-8 chars from the string.</p>
9315
   *
9316
   * @return int|false This functions returns an integer or false if there isn't a string.
9317
   */
9318 18
  public static function substr_count(
9319
      string $haystack,
9320
      string $needle,
9321
      int $offset = 0,
9322
      int $length = null,
9323
      string $encoding = 'UTF-8',
9324
      bool $cleanUtf8 = false
9325
  )
9326
  {
9327 18
    if ('' === $haystack || '' === $needle) {
9328 2
      return false;
9329
    }
9330
9331 18
    if ($offset || $length !== null) {
9332
9333 2
      if ($length === null) {
9334 2
        $lengthTmp = self::strlen($haystack);
9335 2
        if ($lengthTmp === false) {
9336
          return false;
9337
        }
9338 2
        $length = (int)$lengthTmp;
9339
      }
9340
9341
      if (
9342
          (
9343 2
              $length !== 0
9344
              &&
9345 2
              $offset !== 0
9346
          )
9347
          &&
9348 2
          ($length + $offset) <= 0
9349
          &&
9350 2
          Bootup::is_php('7.1') === false // output from "substr_count()" have changed in PHP 7.1
9351
      ) {
9352 2
        return false;
9353
      }
9354
9355 2
      $haystackTmp = self::substr($haystack, $offset, $length, $encoding);
9356 2
      if ($haystackTmp === false) {
9357
        $haystackTmp = '';
9358
      }
9359 2
      $haystack = (string)$haystackTmp;
9360
    }
9361
9362 18
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9363 8
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9364
    }
9365
9366 18
    if ($cleanUtf8 === true) {
9367
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9368
      // if invalid characters are found in $haystack before $needle
9369
      $needle = self::clean($needle);
9370
      $haystack = self::clean($haystack);
9371
    }
9372
9373 18
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9374
      self::checkForSupport();
9375
    }
9376
9377
    if (
9378 18
        $encoding !== 'UTF-8'
9379
        &&
9380 18
        self::$SUPPORT['mbstring'] === false
9381
    ) {
9382
      \trigger_error('UTF8::substr_count() without mbstring cannot handle "' . $encoding . '" encoding', E_USER_WARNING);
9383
    }
9384
9385 18
    if (self::$SUPPORT['mbstring'] === true) {
9386 18
      return \mb_substr_count($haystack, $needle, $encoding);
9387
    }
9388
9389
    \preg_match_all('/' . \preg_quote($needle, '/') . '/us', $haystack, $matches, PREG_SET_ORDER);
9390
9391
    return \count($matches);
9392
  }
9393
9394
  /**
9395
   * Count the number of substring occurrences.
9396
   *
9397
   * @param string $haystack <p>
9398
   *                         The string being checked.
9399
   *                         </p>
9400
   * @param string $needle   <p>
9401
   *                         The string being found.
9402
   *                         </p>
9403
   * @param int    $offset   [optional] <p>
9404
   *                         The offset where to start counting
9405
   *                         </p>
9406
   * @param int    $length   [optional] <p>
9407
   *                         The maximum length after the specified offset to search for the
9408
   *                         substring. It outputs a warning if the offset plus the length is
9409
   *                         greater than the haystack length.
9410
   *                         </p>
9411
   *
9412
   * @return int|false The number of times the
9413
   *                   needle substring occurs in the
9414
   *                   haystack string.
9415
   */
9416 38
  public static function substr_count_in_byte(string $haystack, string $needle, int $offset = 0, int $length = null)
9417
  {
9418 38
    if ($haystack === '' || $needle === '') {
9419
      return 0;
9420
    }
9421
9422 38
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9423
      self::checkForSupport();
9424
    }
9425
9426
    if (
9427 38
        ($offset || $length !== null)
9428
        &&
9429 38
        self::$SUPPORT['mbstring_func_overload'] === true
9430
    ) {
9431
9432 38
      if ($length === null) {
9433
        $lengthTmp = self::strlen($haystack);
9434
        if ($lengthTmp === false) {
9435
          return false;
9436
        }
9437
        $length = (int)$lengthTmp;
9438
      }
9439
9440
      if (
9441
          (
9442 38
              $length !== 0
9443
              &&
9444 38
              $offset !== 0
9445
          )
9446
          &&
9447 38
          ($length + $offset) <= 0
9448
          &&
9449 38
          Bootup::is_php('7.1') === false // output from "substr_count()" have changed in PHP 7.1
9450
      ) {
9451
        return false;
9452
      }
9453
9454 38
      $haystackTmp = self::substr_in_byte($haystack, $offset, $length);
9455 38
      if ($haystackTmp === false) {
0 ignored issues
show
introduced by
The condition $haystackTmp === false is always false.
Loading history...
9456
        $haystackTmp = '';
9457
      }
9458 38
      $haystack = (string)$haystackTmp;
9459
    }
9460
9461 38
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
9462
      // "mb_" is available if overload is used, so use it ...
9463 38
      return \mb_substr_count($haystack, $needle, 'CP850'); // 8-BIT
9464
    }
9465
9466
    return \substr_count($haystack, $needle, $offset, $length);
9467
  }
9468
9469
  /**
9470
   * Returns the number of occurrences of $substring in the given string.
9471
   * By default, the comparison is case-sensitive, but can be made insensitive
9472
   * by setting $caseSensitive to false.
9473
   *
9474
   * @param string $str           <p>The input string.</p>
9475
   * @param string $substring     <p>The substring to search for.</p>
9476
   * @param bool   $caseSensitive [optional] <p>Whether or not to enforce case-sensitivity. Default: true</p>
9477
   * @param string $encoding      [optional] <p>Set the charset for e.g. "mb_" function</p>
9478
   *
9479
   * @return int
9480
   */
9481 15
  public static function substr_count_simple(string $str, string $substring, $caseSensitive = true, string $encoding = 'UTF-8'): int
9482
  {
9483 15
    if ('' === $str || '' === $substring) {
9484 2
      return 0;
9485
    }
9486
9487
    // only a fallback to prevent BC in the api ...
9488 13
    if ($caseSensitive !== false && $caseSensitive !== true) {
0 ignored issues
show
introduced by
The condition $caseSensitive !== true is always false.
Loading history...
9489 4
      $encoding = (string)$caseSensitive;
9490
    }
9491
9492 13
    if (!$caseSensitive) {
9493 6
      $str = self::strtocasefold($str, true, false, $encoding, null, false);
9494 6
      $substring = self::strtocasefold($substring, true, false, $encoding, null, false);
9495
    }
9496
9497 13
    return (int)self::substr_count($str, $substring, 0, null, $encoding);
9498
  }
9499
9500
  /**
9501
   * Removes an prefix ($needle) from start of the string ($haystack), case insensitive.
9502
   *
9503
   * @param string $haystack <p>The string to search in.</p>
9504
   * @param string $needle   <p>The substring to search for.</p>
9505
   *
9506
   * @return string Return the sub-string.
9507
   */
9508 2
  public static function substr_ileft(string $haystack, string $needle): string
9509
  {
9510 2
    if ('' === $haystack) {
9511 2
      return '';
9512
    }
9513
9514 2
    if ('' === $needle) {
9515 2
      return $haystack;
9516
    }
9517
9518 2
    if (self::str_istarts_with($haystack, $needle) === true) {
9519 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

9519
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($needle));
Loading history...
9520 2
      if ($haystackTmp === false) {
9521
        $haystackTmp = '';
9522
      }
9523 2
      $haystack = (string)$haystackTmp;
9524
    }
9525
9526 2
    return $haystack;
9527
  }
9528
9529
  /**
9530
   * Get part of a string process in bytes.
9531
   *
9532
   * @param string $str    <p>The string being checked.</p>
9533
   * @param int    $offset <p>The first position used in str.</p>
9534
   * @param int    $length [optional] <p>The maximum length of the returned string.</p>
9535
   *
9536
   * @return string|false
9537
   *                      The portion of <i>str</i> specified by the <i>offset</i> and
9538
   *                      <i>length</i> parameters.</p><p>If <i>str</i> is shorter than <i>offset</i>
9539
   *                      characters long, <b>FALSE</b> will be returned.
9540
   */
9541 54
  public static function substr_in_byte(string $str, int $offset = 0, int $length = null)
9542
  {
9543 54
    if ($str === '') {
9544
      return '';
9545
    }
9546
9547
    // Empty string
9548 54
    if ($length === 0) {
9549
      return '';
9550
    }
9551
9552
    // Whole string
9553 54
    if (!$offset && $length === null) {
9554
      return $str;
9555
    }
9556
9557 54
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9558
      self::checkForSupport();
9559
    }
9560
9561 54
    if (self::$SUPPORT['mbstring_func_overload'] === true) {
9562
      // "mb_" is available if overload is used, so use it ...
9563 54
      return \mb_substr($str, $offset, $length ?? 2147483647, 'CP850'); // 8-BIT
9564
    }
9565
9566
    return \substr($str, $offset, $length ?? 2147483647);
9567
  }
9568
9569
  /**
9570
   * Removes an suffix ($needle) from end of the string ($haystack), case insensitive.
9571
   *
9572
   * @param string $haystack <p>The string to search in.</p>
9573
   * @param string $needle   <p>The substring to search for.</p>
9574
   *
9575
   * @return string Return the sub-string.
9576
   */
9577 2
  public static function substr_iright(string $haystack, string $needle): string
9578
  {
9579 2
    if ('' === $haystack) {
9580 2
      return '';
9581
    }
9582
9583 2
    if ('' === $needle) {
9584 2
      return $haystack;
9585
    }
9586
9587 2
    if (self::str_iends_with($haystack, $needle) === true) {
9588 2
      $haystackTmp = self::substr($haystack, 0, self::strlen($haystack) - self::strlen($needle));
9589 2
      if ($haystackTmp === false) {
9590
        $haystackTmp = '';
9591
      }
9592 2
      $haystack = (string)$haystackTmp;
9593
    }
9594
9595 2
    return $haystack;
9596
  }
9597
9598
  /**
9599
   * Removes an prefix ($needle) from start of the string ($haystack).
9600
   *
9601
   * @param string $haystack <p>The string to search in.</p>
9602
   * @param string $needle   <p>The substring to search for.</p>
9603
   *
9604
   * @return string Return the sub-string.
9605
   */
9606 2
  public static function substr_left(string $haystack, string $needle): string
9607
  {
9608 2
    if ('' === $haystack) {
9609 2
      return '';
9610
    }
9611
9612 2
    if ('' === $needle) {
9613 2
      return $haystack;
9614
    }
9615
9616 2
    if (self::str_starts_with($haystack, $needle) === true) {
9617 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

9617
      $haystackTmp = self::substr($haystack, /** @scrutinizer ignore-type */ self::strlen($needle));
Loading history...
9618 2
      if ($haystackTmp === false) {
9619
        $haystackTmp = '';
9620
      }
9621 2
      $haystack = (string)$haystackTmp;
9622
    }
9623
9624 2
    return $haystack;
9625
  }
9626
9627
  /**
9628
   * Replace text within a portion of a string.
9629
   *
9630
   * source: https://gist.github.com/stemar/8287074
9631
   *
9632
   * @param string|string[] $str              <p>The input string or an array of stings.</p>
9633
   * @param string|string[] $replacement      <p>The replacement string or an array of stings.</p>
9634
   * @param int|int[]       $offset           <p>
9635
   *                                          If start is positive, the replacing will begin at the start'th offset
9636
   *                                          into string.
9637
   *                                          <br><br>
9638
   *                                          If start is negative, the replacing will begin at the start'th character
9639
   *                                          from the end of string.
9640
   *                                          </p>
9641
   * @param int|int[]|null  $length           [optional] <p>If given and is positive, it represents the length of the
9642
   *                                          portion of string which is to be replaced. If it is negative, it
9643
   *                                          represents the number of characters from the end of string at which to
9644
   *                                          stop replacing. If it is not given, then it will default to strlen(
9645
   *                                          string ); i.e. end the replacing at the end of string. Of course, if
9646
   *                                          length is zero then this function will have the effect of inserting
9647
   *                                          replacement into string at the given start offset.</p>
9648
   *
9649
   * @return string|string[] The result string is returned. If string is an array then array is returned.
9650
   */
9651 10
  public static function substr_replace($str, $replacement, $offset, $length = null)
9652
  {
9653 10
    if (\is_array($str) === true) {
9654 1
      $num = \count($str);
9655
9656
      // the replacement
9657 1
      if (\is_array($replacement) === true) {
9658 1
        $replacement = \array_slice($replacement, 0, $num);
9659
      } else {
9660 1
        $replacement = \array_pad([$replacement], $num, $replacement);
9661
      }
9662
9663
      // the offset
9664 1
      if (\is_array($offset) === true) {
9665 1
        $offset = \array_slice($offset, 0, $num);
9666 1
        foreach ($offset as &$valueTmp) {
9667 1
          $valueTmp = (int)$valueTmp === $valueTmp ? $valueTmp : 0;
9668
        }
9669 1
        unset($valueTmp);
9670
      } else {
9671 1
        $offset = \array_pad([$offset], $num, $offset);
9672
      }
9673
9674
      // the length
9675 1
      if (null === $length) {
9676 1
        $length = \array_fill(0, $num, 0);
9677 1
      } elseif (\is_array($length) === true) {
9678 1
        $length = \array_slice($length, 0, $num);
9679 1
        foreach ($length as &$valueTmpV2) {
9680 1
          if (null !== $valueTmpV2) {
9681 1
            $valueTmpV2 = (int)$valueTmpV2 === $valueTmpV2 ? $valueTmpV2 : $num;
9682
          } else {
9683 1
            $valueTmpV2 = 0;
9684
          }
9685
        }
9686 1
        unset($valueTmpV2);
9687
      } else {
9688 1
        $length = \array_pad([$length], $num, $length);
9689
      }
9690
9691
      // recursive call
9692 1
      return \array_map([self::class, 'substr_replace'], $str, $replacement, $offset, $length);
9693
    }
9694
9695 10
    if (\is_array($replacement) === true) {
9696 1
      if (\count($replacement) > 0) {
9697 1
        $replacement = $replacement[0];
9698
      } else {
9699 1
        $replacement = '';
9700
      }
9701
    }
9702
9703
    // init
9704 10
    $str = (string)$str;
9705 10
    $replacement = (string)$replacement;
9706
9707 10
    if ('' === $str) {
9708 1
      return $replacement;
9709
    }
9710
9711 9
    if (self::is_ascii($str)) {
9712 6
      return ($length === null) ?
9713
          \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

9713
          \substr_replace($str, $replacement, /** @scrutinizer ignore-type */ $offset) :
Loading history...
9714 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

9714
          \substr_replace($str, $replacement, $offset, /** @scrutinizer ignore-type */ $length);
Loading history...
9715
    }
9716
9717 8
    \preg_match_all('/./us', $str, $smatches);
9718 8
    \preg_match_all('/./us', $replacement, $rmatches);
9719
9720 8
    if ($length === null) {
9721 3
      $lengthTmp = self::strlen($str);
9722 3
      if ($lengthTmp === false) {
9723
        // e.g.: non mbstring support + invalid chars
9724
        return '';
9725
      }
9726 3
      $length = (int)$lengthTmp;
9727
    }
9728
9729 8
    \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

9729
    \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

9729
    \array_splice($smatches[0], /** @scrutinizer ignore-type */ $offset, $length, $rmatches[0]);
Loading history...
9730
9731 8
    return \implode('', $smatches[0]);
9732
  }
9733
9734
  /**
9735
   * Removes an suffix ($needle) from end of the string ($haystack).
9736
   *
9737
   * @param string $haystack <p>The string to search in.</p>
9738
   * @param string $needle   <p>The substring to search for.</p>
9739
   *
9740
   * @return string Return the sub-string.
9741
   */
9742 2
  public static function substr_right(string $haystack, string $needle): string
9743
  {
9744 2
    if ('' === $haystack) {
9745 2
      return '';
9746
    }
9747
9748 2
    if ('' === $needle) {
9749 2
      return $haystack;
9750
    }
9751
9752 2
    if (self::str_ends_with($haystack, $needle) === true) {
9753 2
      $haystackTmp = self::substr($haystack, 0, self::strlen($haystack) - self::strlen($needle));
9754 2
      if ($haystackTmp === false) {
9755
        $haystackTmp = '';
9756
      }
9757 2
      $haystack = (string)$haystackTmp;
9758
    }
9759
9760 2
    return $haystack;
9761
  }
9762
9763
  /**
9764
   * Returns a case swapped version of the string.
9765
   *
9766
   * @param string $str       <p>The input string.</p>
9767
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
9768
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
9769
   *
9770
   * @return string Each character's case swapped.
9771
   */
9772 6
  public static function swapCase(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
9773
  {
9774 6
    if ('' === $str) {
9775 1
      return '';
9776
    }
9777
9778 6
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9779 4
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9780
    }
9781
9782 6
    if ($cleanUtf8 === true) {
9783
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
9784
      // if invalid characters are found in $haystack before $needle
9785 2
      $str = self::clean($str);
9786
    }
9787
9788 6
    return (string)(self::strtolower($str, $encoding) ^ self::strtoupper($str, $encoding) ^ $str);
9789
  }
9790
9791
  /**
9792
   * Checks whether mbstring is available on the server.
9793
   *
9794
   * @return bool
9795
   *              <strong>true</strong> if available, <strong>false</strong> otherwise.
9796
   */
9797
  public static function symfony_polyfill_used(): bool
9798
  {
9799
    // init
9800
    $return = false;
9801
9802
    $returnTmp = \extension_loaded('mbstring') ? true : false;
9803
    if ($returnTmp === false && \function_exists('mb_strlen')) {
9804
      $return = true;
9805
    }
9806
9807
    $returnTmp = \extension_loaded('iconv') ? true : false;
9808
    if ($returnTmp === false && \function_exists('iconv')) {
9809
      $return = true;
9810
    }
9811
9812
    return $return;
9813
  }
9814
9815
  /**
9816
   * @param string $str
9817
   * @param int    $tabLength
9818
   *
9819
   * @return string
9820
   */
9821 6
  public static function tabs_to_spaces(string $str, int $tabLength = 4): string
9822
  {
9823 6
    return \str_replace("\t", \str_repeat(' ', $tabLength), $str);
9824
  }
9825
9826
  /**
9827
   * Converts the first character of each word in the string to uppercase
9828
   * and all other chars to lowercase.
9829
   *
9830
   * @param string $str      <p>The input string.</p>
9831
   * @param string $encoding [optional] <p>Set the charset for e.g. "mb_" function</p>
9832
   *
9833
   * @return string String with all characters of $str being title-cased.
9834
   */
9835 5
  public static function titlecase(string $str, string $encoding = 'UTF-8'): string
9836
  {
9837 5
    if ($encoding !== 'UTF-8' && $encoding !== 'CP850') {
9838 2
      $encoding = self::normalize_encoding($encoding, 'UTF-8');
9839
    }
9840
9841
    // always fallback via symfony polyfill
9842 5
    return \mb_convert_case($str, MB_CASE_TITLE, $encoding);
9843
  }
9844
9845
  /**
9846
   * alias for "UTF8::to_ascii()"
9847
   *
9848
   * @see        UTF8::to_ascii()
9849
   *
9850
   * @param string $str
9851
   * @param string $subst_chr
9852
   * @param bool   $strict
9853
   *
9854
   * @return string
9855
   *
9856
   * @deprecated <p>use "UTF8::to_ascii()"</p>
9857
   */
9858 7
  public static function toAscii(string $str, string $subst_chr = '?', bool $strict = false): string
9859
  {
9860 7
    return self::to_ascii($str, $subst_chr, $strict);
9861
  }
9862
9863
  /**
9864
   * alias for "UTF8::to_iso8859()"
9865
   *
9866
   * @see        UTF8::to_iso8859()
9867
   *
9868
   * @param string|string[] $str
9869
   *
9870
   * @return string|string[]
9871
   *
9872
   * @deprecated <p>use "UTF8::to_iso8859()"</p>
9873
   */
9874 2
  public static function toIso8859($str)
9875
  {
9876 2
    return self::to_iso8859($str);
9877
  }
9878
9879
  /**
9880
   * alias for "UTF8::to_latin1()"
9881
   *
9882
   * @see        UTF8::to_latin1()
9883
   *
9884
   * @param string|string[] $str
9885
   *
9886
   * @return string|string[]
9887
   *
9888
   * @deprecated <p>use "UTF8::to_latin1()"</p>
9889
   */
9890 2
  public static function toLatin1($str)
9891
  {
9892 2
    return self::to_latin1($str);
9893
  }
9894
9895
  /**
9896
   * alias for "UTF8::to_utf8()"
9897
   *
9898
   * @see        UTF8::to_utf8()
9899
   *
9900
   * @param string|string[] $str
9901
   *
9902
   * @return string|string[]
9903
   *
9904
   * @deprecated <p>use "UTF8::to_utf8()"</p>
9905
   */
9906 2
  public static function toUTF8($str)
9907
  {
9908 2
    return self::to_utf8($str);
9909
  }
9910
9911
  /**
9912
   * Convert a string into ASCII.
9913
   *
9914
   * @param string $str     <p>The input string.</p>
9915
   * @param string $unknown [optional] <p>Character use if character unknown. (default is ?)</p>
9916
   * @param bool   $strict  [optional] <p>Use "transliterator_transliterate()" from PHP-Intl | WARNING: bad
9917
   *                        performance</p>
9918
   *
9919
   * @return string
9920
   */
9921 37
  public static function to_ascii(string $str, string $unknown = '?', bool $strict = false): string
9922
  {
9923 37
    static $UTF8_TO_ASCII;
9924
9925 37
    if ('' === $str) {
9926 3
      return '';
9927
    }
9928
9929
    // check if we only have ASCII, first (better performance)
9930 34
    if (self::is_ascii($str) === true) {
9931 6
      return $str;
9932
    }
9933
9934 29
    $str = self::clean(
9935 29
        $str,
9936 29
        true,
9937 29
        true,
9938 29
        true,
9939 29
        false,
9940 29
        true,
9941 29
        true
9942
    );
9943
9944
    // check again, if we only have ASCII, now ...
9945 29
    if (self::is_ascii($str) === true) {
9946 12
      return $str;
9947
    }
9948
9949 18
    if ($strict === true) {
9950
9951 1
      if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
9952
        self::checkForSupport();
9953
      }
9954
9955 1
      if (self::$SUPPORT['intl'] === true) {
9956
        // INFO: https://unicode.org/cldr/utility/character.jsp?a=%E2%84%8C
9957
        /** @noinspection PhpComposerExtensionStubsInspection */
9958 1
        $str = \transliterator_transliterate('NFKC; [:Nonspacing Mark:] Remove; NFKC; Any-Latin; Latin-ASCII;', $str);
9959
9960
        // check again, if we only have ASCII, now ...
9961 1
        if (self::is_ascii($str) === true) {
9962 1
          return $str;
9963
        }
9964
9965
      }
9966
    }
9967
9968 18
    if (self::$ORD === null) {
9969
      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 null|array. 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...
9970
    }
9971
9972 18
    \preg_match_all('/.{1}|[^\x00]{1,1}$/us', $str, $ar);
9973 18
    $chars = $ar[0];
9974 18
    $ord = null;
9975 18
    foreach ($chars as &$c) {
9976
9977 18
      $ordC0 = self::$ORD[$c[0]];
9978
9979 18
      if ($ordC0 >= 0 && $ordC0 <= 127) {
9980 14
        continue;
9981
      }
9982
9983 18
      $ordC1 = self::$ORD[$c[1]];
9984
9985
      // ASCII - next please
9986 18
      if ($ordC0 >= 192 && $ordC0 <= 223) {
9987 16
        $ord = ($ordC0 - 192) * 64 + ($ordC1 - 128);
9988
      }
9989
9990 18
      if ($ordC0 >= 224) {
9991 7
        $ordC2 = self::$ORD[$c[2]];
9992
9993 7
        if ($ordC0 <= 239) {
9994 6
          $ord = ($ordC0 - 224) * 4096 + ($ordC1 - 128) * 64 + ($ordC2 - 128);
9995
        }
9996
9997 7
        if ($ordC0 >= 240) {
9998 2
          $ordC3 = self::$ORD[$c[3]];
9999
10000 2
          if ($ordC0 <= 247) {
10001 2
            $ord = ($ordC0 - 240) * 262144 + ($ordC1 - 128) * 4096 + ($ordC2 - 128) * 64 + ($ordC3 - 128);
10002
          }
10003
10004 2
          if ($ordC0 >= 248) {
10005
            $ordC4 = self::$ORD[$c[4]];
10006
10007
            if ($ordC0 <= 251) {
10008
              $ord = ($ordC0 - 248) * 16777216 + ($ordC1 - 128) * 262144 + ($ordC2 - 128) * 4096 + ($ordC3 - 128) * 64 + ($ordC4 - 128);
10009
            }
10010
10011
            if ($ordC0 >= 252) {
10012
              $ordC5 = self::$ORD[$c[5]];
10013
10014
              if ($ordC0 <= 253) {
10015
                $ord = ($ordC0 - 252) * 1073741824 + ($ordC1 - 128) * 16777216 + ($ordC2 - 128) * 262144 + ($ordC3 - 128) * 4096 + ($ordC4 - 128) * 64 + ($ordC5 - 128);
10016
              }
10017
            }
10018
          }
10019
        }
10020
      }
10021
10022 18
      if ($ordC0 === 254 || $ordC0 === 255) {
10023
        $c = $unknown;
10024
        continue;
10025
      }
10026
10027 18
      if ($ord === null) {
10028
        $c = $unknown;
10029
        continue;
10030
      }
10031
10032 18
      $bank = $ord >> 8;
10033 18
      if (!isset($UTF8_TO_ASCII[$bank])) {
10034 9
        $UTF8_TO_ASCII[$bank] = self::getData(\sprintf('x%02x', $bank));
10035 9
        if ($UTF8_TO_ASCII[$bank] === false) {
10036 2
          $UTF8_TO_ASCII[$bank] = [];
10037
        }
10038
      }
10039
10040 18
      $newchar = $ord & 255;
10041
10042 18
      if (isset($UTF8_TO_ASCII[$bank][$newchar])) {
10043
10044
        // keep for debugging
10045
        /*
10046
        echo "file: " . sprintf('x%02x', $bank) . "\n";
10047
        echo "char: " . $c . "\n";
10048
        echo "ord: " . $ord . "\n";
10049
        echo "newchar: " . $newchar . "\n";
10050
        echo "ascii: " . $UTF8_TO_ASCII[$bank][$newchar] . "\n";
10051
        echo "bank:" . $bank . "\n\n";
10052
        */
10053
10054 17
        $c = $UTF8_TO_ASCII[$bank][$newchar];
10055
      } else {
10056
10057
        // keep for debugging missing chars
10058
        /*
10059
        echo "file: " . sprintf('x%02x', $bank) . "\n";
10060
        echo "char: " . $c . "\n";
10061
        echo "ord: " . $ord . "\n";
10062
        echo "newchar: " . $newchar . "\n";
10063
        echo "bank:" . $bank . "\n\n";
10064
        */
10065
10066 18
        $c = $unknown;
10067
      }
10068
    }
10069
10070 18
    return \implode('', $chars);
10071
  }
10072
10073
  /**
10074
   * @param mixed $str
10075
   *
10076
   * @return bool
10077
   */
10078 19
  public static function to_boolean($str): bool
10079
  {
10080
    // init
10081 19
    $str = (string)$str;
10082
10083 19
    if ('' === $str) {
10084 2
      return false;
10085
    }
10086
10087 17
    $key = \strtolower($str);
10088
10089
    // Info: http://php.net/manual/en/filter.filters.validate.php
10090
    $map = [
10091 17
        'true'  => true,
10092
        '1'     => true,
10093
        'on'    => true,
10094
        'yes'   => true,
10095
        'false' => false,
10096
        '0'     => false,
10097
        'off'   => false,
10098
        'no'    => false,
10099
    ];
10100
10101 17
    if (isset($map[$key])) {
10102 13
      return $map[$key];
10103
    }
10104
10105
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
10106 4
    if (\is_numeric($str)) {
10107 2
      return (((float)$str + 0) > 0);
10108
    }
10109
10110 2
    return (bool)self::trim($str);
10111
  }
10112
10113
  /**
10114
   * Convert a string into "ISO-8859"-encoding (Latin-1).
10115
   *
10116
   * @param string|string[] $str
10117
   *
10118
   * @return string|string[]
10119
   */
10120 8
  public static function to_iso8859($str)
10121
  {
10122 8
    if (\is_array($str) === true) {
10123 2
      foreach ($str as $k => $v) {
10124 2
        $str[$k] = self::to_iso8859($v);
10125
      }
10126
10127 2
      return $str;
10128
    }
10129
10130 8
    $str = (string)$str;
10131 8
    if ('' === $str) {
10132 2
      return '';
10133
    }
10134
10135 8
    return self::utf8_decode($str);
10136
  }
10137
10138
  /**
10139
   * alias for "UTF8::to_iso8859()"
10140
   *
10141
   * @see UTF8::to_iso8859()
10142
   *
10143
   * @param string|string[] $str
10144
   *
10145
   * @return string|string[]
10146
   */
10147 2
  public static function to_latin1($str)
10148
  {
10149 2
    return self::to_iso8859($str);
10150
  }
10151
10152
  /**
10153
   * This function leaves UTF-8 characters alone, while converting almost all non-UTF8 to UTF8.
10154
   *
10155
   * <ul>
10156
   * <li>It decode UTF-8 codepoints and unicode escape sequences.</li>
10157
   * <li>It assumes that the encoding of the original string is either WINDOWS-1252 or ISO-8859.</li>
10158
   * <li>WARNING: It does not remove invalid UTF-8 characters, so you maybe need to use "UTF8::clean()" for this
10159
   * case.</li>
10160
   * </ul>
10161
   *
10162
   * @param string|string[] $str                    <p>Any string or array.</p>
10163
   * @param bool            $decodeHtmlEntityToUtf8 <p>Set to true, if you need to decode html-entities.</p>
10164
   *
10165
   * @return string|string[] The UTF-8 encoded string.
10166
   */
10167 38
  public static function to_utf8($str, bool $decodeHtmlEntityToUtf8 = false)
10168
  {
10169 38
    if (\is_array($str) === true) {
10170 4
      foreach ($str as $k => $v) {
10171 4
        $str[$k] = self::to_utf8($v, $decodeHtmlEntityToUtf8);
10172
      }
10173
10174 4
      return $str;
10175
    }
10176
10177 38
    $str = (string)$str;
10178 38
    if ('' === $str) {
10179 6
      return $str;
10180
    }
10181
10182 38
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
10183
      self::checkForSupport();
10184
    }
10185
10186 38
    $max = self::strlen_in_byte($str);
10187 38
    $buf = '';
10188
10189
    /** @noinspection ForeachInvariantsInspection */
10190 38
    for ($i = 0; $i < $max; $i++) {
10191 38
      $c1 = $str[$i];
10192
10193 38
      if ($c1 >= "\xC0") { // should be converted to UTF8, if it's not UTF8 already
10194
10195 34
        if ($c1 <= "\xDF") { // looks like 2 bytes UTF8
10196
10197 31
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10198
10199 31
          if ($c2 >= "\x80" && $c2 <= "\xBF") { // yeah, almost sure it's UTF8 already
10200 17
            $buf .= $c1 . $c2;
10201 17
            $i++;
10202
          } else { // not valid UTF8 - convert it
10203 31
            $buf .= self::to_utf8_convert_helper($c1);
10204
          }
10205
10206 34
        } elseif ($c1 >= "\xE0" && $c1 <= "\xEF") { // looks like 3 bytes UTF8
10207
10208 32
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10209 32
          $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
10210
10211 32
          if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF") { // yeah, almost sure it's UTF8 already
10212 14
            $buf .= $c1 . $c2 . $c3;
10213 14
            $i += 2;
10214
          } else { // not valid UTF8 - convert it
10215 32
            $buf .= self::to_utf8_convert_helper($c1);
10216
          }
10217
10218 26
        } elseif ($c1 >= "\xF0" && $c1 <= "\xF7") { // looks like 4 bytes UTF8
10219
10220 26
          $c2 = $i + 1 >= $max ? "\x00" : $str[$i + 1];
10221 26
          $c3 = $i + 2 >= $max ? "\x00" : $str[$i + 2];
10222 26
          $c4 = $i + 3 >= $max ? "\x00" : $str[$i + 3];
10223
10224 26
          if ($c2 >= "\x80" && $c2 <= "\xBF" && $c3 >= "\x80" && $c3 <= "\xBF" && $c4 >= "\x80" && $c4 <= "\xBF") { // yeah, almost sure it's UTF8 already
10225 8
            $buf .= $c1 . $c2 . $c3 . $c4;
10226 8
            $i += 3;
10227
          } else { // not valid UTF8 - convert it
10228 26
            $buf .= self::to_utf8_convert_helper($c1);
10229
          }
10230
10231
        } else { // doesn't look like UTF8, but should be converted
10232 34
          $buf .= self::to_utf8_convert_helper($c1);
10233
        }
10234
10235 35
      } elseif (($c1 & "\xC0") === "\x80") { // needs conversion
10236
10237 4
        $buf .= self::to_utf8_convert_helper($c1);
10238
10239
      } else { // it doesn't need conversion
10240 35
        $buf .= $c1;
10241
      }
10242
    }
10243
10244
    // decode unicode escape sequences
10245 38
    $buf = \preg_replace_callback(
10246 38
        '/\\\\u([0-9a-f]{4})/i',
10247 38
        function ($match) {
10248
          // always fallback via symfony polyfill
10249 8
          return \mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
10250 38
        },
10251 38
        $buf
10252
    );
10253
10254
    // decode UTF-8 codepoints
10255 38
    if ($decodeHtmlEntityToUtf8 === true) {
10256 2
      $buf = self::html_entity_decode($buf);
10257
    }
10258
10259 38
    return $buf;
10260
  }
10261
10262
  /**
10263
   * @param int|string $input
10264
   *
10265
   * @return string
10266
   */
10267 30
  private static function to_utf8_convert_helper($input): string
10268
  {
10269
    // init
10270 30
    $buf = '';
10271
10272 30
    if (self::$ORD === null) {
10273 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 null|array. 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...
10274
    }
10275
10276 30
    if (self::$CHR === null) {
10277 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 null|array. 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...
10278
    }
10279
10280 30
    if (self::$WIN1252_TO_UTF8 === null) {
10281 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 null|array. 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...
10282
    }
10283
10284 30
    $ordC1 = self::$ORD[$input];
10285 30
    if (isset(self::$WIN1252_TO_UTF8[$ordC1])) { // found in Windows-1252 special cases
10286 30
      $buf .= self::$WIN1252_TO_UTF8[$ordC1];
10287
    } else {
10288 2
      $cc1 = self::$CHR[$ordC1 / 64] | "\xC0";
10289 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...
10290 2
      $buf .= $cc1 . $cc2;
10291
    }
10292
10293 30
    return $buf;
10294
  }
10295
10296
  /**
10297
   * Strip whitespace or other characters from beginning or end of a UTF-8 string.
10298
   *
10299
   * INFO: This is slower then "trim()"
10300
   *
10301
   * We can only use the original-function, if we use <= 7-Bit in the string / chars
10302
   * but the check for ACSII (7-Bit) cost more time, then we can safe here.
10303
   *
10304
   * @param string $str   <p>The string to be trimmed</p>
10305
   * @param mixed  $chars [optional] <p>Optional characters to be stripped</p>
10306
   *
10307
   * @return string The trimmed string.
10308
   */
10309 214
  public static function trim(string $str = '', $chars = INF): string
10310
  {
10311 214
    if ('' === $str) {
10312 11
      return '';
10313
    }
10314
10315
    // Info: http://nadeausoftware.com/articles/2007/9/php_tip_how_strip_punctuation_characters_web_page#Unicodecharactercategories
10316 206
    if ($chars === INF || !$chars) {
10317 179
      $pattern = "^[\pZ\pC]+|[\pZ\pC]+\$";
10318
    } else {
10319 47
      $chars = \preg_quote($chars, '/');
10320 47
      $pattern = "^[$chars]+|[$chars]+\$";
10321
    }
10322
10323 206
    return self::regex_replace($str, $pattern, '', '', '/');
10324
  }
10325
10326
  /**
10327
   * Makes string's first char uppercase.
10328
   *
10329
   * @param string $str       <p>The input string.</p>
10330
   * @param string $encoding  [optional] <p>Set the charset for e.g. "mb_" function</p>
10331
   * @param bool   $cleanUtf8 [optional] <p>Remove non UTF-8 chars from the string.</p>
10332
   *
10333
   * @return string The resulting string.
10334
   */
10335 76
  public static function ucfirst(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
10336
  {
10337 76
    if ($cleanUtf8 === true) {
10338
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10339
      // if invalid characters are found in $haystack before $needle
10340 1
      $str = self::clean($str);
10341
    }
10342
10343 76
    $strPartTwo = self::substr($str, 1, null, $encoding);
10344 76
    if ($strPartTwo === false) {
10345
      $strPartTwo = '';
10346
    }
10347
10348 76
    $strPartOne = self::strtoupper(
10349 76
        (string)self::substr($str, 0, 1, $encoding),
10350 76
        $encoding,
10351 76
        $cleanUtf8
10352
    );
10353
10354 76
    return $strPartOne . $strPartTwo;
10355
  }
10356
10357
  /**
10358
   * alias for "UTF8::ucfirst()"
10359
   *
10360
   * @see UTF8::ucfirst()
10361
   *
10362
   * @param string $str
10363
   * @param string $encoding
10364
   * @param bool   $cleanUtf8
10365
   *
10366
   * @return string
10367
   */
10368 1
  public static function ucword(string $str, string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
10369
  {
10370 1
    return self::ucfirst($str, $encoding, $cleanUtf8);
10371
  }
10372
10373
  /**
10374
   * Uppercase for all words in the string.
10375
   *
10376
   * @param string   $str        <p>The input string.</p>
10377
   * @param string[] $exceptions [optional] <p>Exclusion for some words.</p>
10378
   * @param string   $charlist   [optional] <p>Additional chars that contains to words and do not start a new word.</p>
10379
   * @param string   $encoding   [optional] <p>Set the charset.</p>
10380
   * @param bool     $cleanUtf8  [optional] <p>Remove non UTF-8 chars from the string.</p>
10381
   *
10382
   * @return string
10383
   */
10384 9
  public static function ucwords(string $str, array $exceptions = [], string $charlist = '', string $encoding = 'UTF-8', bool $cleanUtf8 = false): string
10385
  {
10386 9
    if (!$str) {
10387 2
      return '';
10388
    }
10389
10390
    // INFO: mb_convert_case($str, MB_CASE_TITLE);
10391
    // -> MB_CASE_TITLE didn't only uppercase the first letter, it also lowercase all other letters
10392
10393 8
    if ($cleanUtf8 === true) {
10394
      // "mb_strpos()" and "iconv_strpos()" returns wrong position,
10395
      // if invalid characters are found in $haystack before $needle
10396 1
      $str = self::clean($str);
10397
    }
10398
10399 8
    $usePhpDefaultFunctions = !(bool)($charlist . \implode('', $exceptions));
10400
10401
    if (
10402 8
        $usePhpDefaultFunctions === true
10403
        &&
10404 8
        self::is_ascii($str) === true
10405
    ) {
10406
      return \ucwords($str);
10407
    }
10408
10409 8
    $words = self::str_to_words($str, $charlist);
10410 8
    $newWords = [];
10411
10412 8
    if (\count($exceptions) > 0) {
10413 1
      $useExceptions = true;
10414
    } else {
10415 8
      $useExceptions = false;
10416
    }
10417
10418 8
    foreach ($words as $word) {
10419
10420 8
      if (!$word) {
10421 8
        continue;
10422
      }
10423
10424
      if (
10425 8
          $useExceptions === false
10426
          ||
10427
          (
10428 1
              $useExceptions === true
10429
              &&
10430 8
              !\in_array($word, $exceptions, true)
10431
          )
10432
      ) {
10433 8
        $word = self::ucfirst($word, $encoding);
10434
      }
10435
10436 8
      $newWords[] = $word;
10437
    }
10438
10439 8
    return \implode('', $newWords);
10440
  }
10441
10442
  /**
10443
   * Multi decode html entity & fix urlencoded-win1252-chars.
10444
   *
10445
   * e.g:
10446
   * 'test+test'                     => 'test test'
10447
   * 'D&#252;sseldorf'               => 'Düsseldorf'
10448
   * 'D%FCsseldorf'                  => 'Düsseldorf'
10449
   * 'D&#xFC;sseldorf'               => 'Düsseldorf'
10450
   * 'D%26%23xFC%3Bsseldorf'         => 'Düsseldorf'
10451
   * 'Düsseldorf'                   => 'Düsseldorf'
10452
   * 'D%C3%BCsseldorf'               => 'Düsseldorf'
10453
   * 'D%C3%83%C2%BCsseldorf'         => 'Düsseldorf'
10454
   * 'D%25C3%2583%25C2%25BCsseldorf' => 'Düsseldorf'
10455
   *
10456
   * @param string $str          <p>The input string.</p>
10457
   * @param bool   $multi_decode <p>Decode as often as possible.</p>
10458
   *
10459
   * @return string
10460
   */
10461 2
  public static function urldecode(string $str, bool $multi_decode = true): string
10462
  {
10463 2
    if ('' === $str) {
10464 2
      return '';
10465
    }
10466
10467 2
    $pattern = '/%u([0-9a-f]{3,4})/i';
10468 2
    if (\preg_match($pattern, $str)) {
10469 2
      $str = (string)\preg_replace($pattern, '&#x\\1;', \urldecode($str));
10470
    }
10471
10472 2
    $flags = ENT_QUOTES | ENT_HTML5;
10473
10474
    do {
10475 2
      $str_compare = $str;
10476
10477 2
      $str = self::fix_simple_utf8(
10478 2
          \urldecode(
10479 2
              self::html_entity_decode(
10480 2
                  self::to_utf8($str),
10481 2
                  $flags
10482
              )
10483
          )
10484
      );
10485
10486 2
    } while ($multi_decode === true && $str_compare !== $str);
10487
10488 2
    return $str;
10489
  }
10490
10491
  /**
10492
   * Return a array with "urlencoded"-win1252 -> UTF-8
10493
   *
10494
   * @deprecated <p>use the "UTF8::urldecode()" function to decode a string</p>
10495
   *
10496
   * @return string[]
10497
   */
10498 2
  public static function urldecode_fix_win1252_chars(): array
10499
  {
10500
    return [
10501 2
        '%20' => ' ',
10502
        '%21' => '!',
10503
        '%22' => '"',
10504
        '%23' => '#',
10505
        '%24' => '$',
10506
        '%25' => '%',
10507
        '%26' => '&',
10508
        '%27' => "'",
10509
        '%28' => '(',
10510
        '%29' => ')',
10511
        '%2A' => '*',
10512
        '%2B' => '+',
10513
        '%2C' => ',',
10514
        '%2D' => '-',
10515
        '%2E' => '.',
10516
        '%2F' => '/',
10517
        '%30' => '0',
10518
        '%31' => '1',
10519
        '%32' => '2',
10520
        '%33' => '3',
10521
        '%34' => '4',
10522
        '%35' => '5',
10523
        '%36' => '6',
10524
        '%37' => '7',
10525
        '%38' => '8',
10526
        '%39' => '9',
10527
        '%3A' => ':',
10528
        '%3B' => ';',
10529
        '%3C' => '<',
10530
        '%3D' => '=',
10531
        '%3E' => '>',
10532
        '%3F' => '?',
10533
        '%40' => '@',
10534
        '%41' => 'A',
10535
        '%42' => 'B',
10536
        '%43' => 'C',
10537
        '%44' => 'D',
10538
        '%45' => 'E',
10539
        '%46' => 'F',
10540
        '%47' => 'G',
10541
        '%48' => 'H',
10542
        '%49' => 'I',
10543
        '%4A' => 'J',
10544
        '%4B' => 'K',
10545
        '%4C' => 'L',
10546
        '%4D' => 'M',
10547
        '%4E' => 'N',
10548
        '%4F' => 'O',
10549
        '%50' => 'P',
10550
        '%51' => 'Q',
10551
        '%52' => 'R',
10552
        '%53' => 'S',
10553
        '%54' => 'T',
10554
        '%55' => 'U',
10555
        '%56' => 'V',
10556
        '%57' => 'W',
10557
        '%58' => 'X',
10558
        '%59' => 'Y',
10559
        '%5A' => 'Z',
10560
        '%5B' => '[',
10561
        '%5C' => '\\',
10562
        '%5D' => ']',
10563
        '%5E' => '^',
10564
        '%5F' => '_',
10565
        '%60' => '`',
10566
        '%61' => 'a',
10567
        '%62' => 'b',
10568
        '%63' => 'c',
10569
        '%64' => 'd',
10570
        '%65' => 'e',
10571
        '%66' => 'f',
10572
        '%67' => 'g',
10573
        '%68' => 'h',
10574
        '%69' => 'i',
10575
        '%6A' => 'j',
10576
        '%6B' => 'k',
10577
        '%6C' => 'l',
10578
        '%6D' => 'm',
10579
        '%6E' => 'n',
10580
        '%6F' => 'o',
10581
        '%70' => 'p',
10582
        '%71' => 'q',
10583
        '%72' => 'r',
10584
        '%73' => 's',
10585
        '%74' => 't',
10586
        '%75' => 'u',
10587
        '%76' => 'v',
10588
        '%77' => 'w',
10589
        '%78' => 'x',
10590
        '%79' => 'y',
10591
        '%7A' => 'z',
10592
        '%7B' => '{',
10593
        '%7C' => '|',
10594
        '%7D' => '}',
10595
        '%7E' => '~',
10596
        '%7F' => '',
10597
        '%80' => '`',
10598
        '%81' => '',
10599
        '%82' => '‚',
10600
        '%83' => 'ƒ',
10601
        '%84' => '„',
10602
        '%85' => '…',
10603
        '%86' => '†',
10604
        '%87' => '‡',
10605
        '%88' => 'ˆ',
10606
        '%89' => '‰',
10607
        '%8A' => 'Š',
10608
        '%8B' => '‹',
10609
        '%8C' => 'Œ',
10610
        '%8D' => '',
10611
        '%8E' => 'Ž',
10612
        '%8F' => '',
10613
        '%90' => '',
10614
        '%91' => '‘',
10615
        '%92' => '’',
10616
        '%93' => '“',
10617
        '%94' => '”',
10618
        '%95' => '•',
10619
        '%96' => '–',
10620
        '%97' => '—',
10621
        '%98' => '˜',
10622
        '%99' => '™',
10623
        '%9A' => 'š',
10624
        '%9B' => '›',
10625
        '%9C' => 'œ',
10626
        '%9D' => '',
10627
        '%9E' => 'ž',
10628
        '%9F' => 'Ÿ',
10629
        '%A0' => '',
10630
        '%A1' => '¡',
10631
        '%A2' => '¢',
10632
        '%A3' => '£',
10633
        '%A4' => '¤',
10634
        '%A5' => '¥',
10635
        '%A6' => '¦',
10636
        '%A7' => '§',
10637
        '%A8' => '¨',
10638
        '%A9' => '©',
10639
        '%AA' => 'ª',
10640
        '%AB' => '«',
10641
        '%AC' => '¬',
10642
        '%AD' => '',
10643
        '%AE' => '®',
10644
        '%AF' => '¯',
10645
        '%B0' => '°',
10646
        '%B1' => '±',
10647
        '%B2' => '²',
10648
        '%B3' => '³',
10649
        '%B4' => '´',
10650
        '%B5' => 'µ',
10651
        '%B6' => '¶',
10652
        '%B7' => '·',
10653
        '%B8' => '¸',
10654
        '%B9' => '¹',
10655
        '%BA' => 'º',
10656
        '%BB' => '»',
10657
        '%BC' => '¼',
10658
        '%BD' => '½',
10659
        '%BE' => '¾',
10660
        '%BF' => '¿',
10661
        '%C0' => 'À',
10662
        '%C1' => 'Á',
10663
        '%C2' => 'Â',
10664
        '%C3' => 'Ã',
10665
        '%C4' => 'Ä',
10666
        '%C5' => 'Å',
10667
        '%C6' => 'Æ',
10668
        '%C7' => 'Ç',
10669
        '%C8' => 'È',
10670
        '%C9' => 'É',
10671
        '%CA' => 'Ê',
10672
        '%CB' => 'Ë',
10673
        '%CC' => 'Ì',
10674
        '%CD' => 'Í',
10675
        '%CE' => 'Î',
10676
        '%CF' => 'Ï',
10677
        '%D0' => 'Ð',
10678
        '%D1' => 'Ñ',
10679
        '%D2' => 'Ò',
10680
        '%D3' => 'Ó',
10681
        '%D4' => 'Ô',
10682
        '%D5' => 'Õ',
10683
        '%D6' => 'Ö',
10684
        '%D7' => '×',
10685
        '%D8' => 'Ø',
10686
        '%D9' => 'Ù',
10687
        '%DA' => 'Ú',
10688
        '%DB' => 'Û',
10689
        '%DC' => 'Ü',
10690
        '%DD' => 'Ý',
10691
        '%DE' => 'Þ',
10692
        '%DF' => 'ß',
10693
        '%E0' => 'à',
10694
        '%E1' => 'á',
10695
        '%E2' => 'â',
10696
        '%E3' => 'ã',
10697
        '%E4' => 'ä',
10698
        '%E5' => 'å',
10699
        '%E6' => 'æ',
10700
        '%E7' => 'ç',
10701
        '%E8' => 'è',
10702
        '%E9' => 'é',
10703
        '%EA' => 'ê',
10704
        '%EB' => 'ë',
10705
        '%EC' => 'ì',
10706
        '%ED' => 'í',
10707
        '%EE' => 'î',
10708
        '%EF' => 'ï',
10709
        '%F0' => 'ð',
10710
        '%F1' => 'ñ',
10711
        '%F2' => 'ò',
10712
        '%F3' => 'ó',
10713
        '%F4' => 'ô',
10714
        '%F5' => 'õ',
10715
        '%F6' => 'ö',
10716
        '%F7' => '÷',
10717
        '%F8' => 'ø',
10718
        '%F9' => 'ù',
10719
        '%FA' => 'ú',
10720
        '%FB' => 'û',
10721
        '%FC' => 'ü',
10722
        '%FD' => 'ý',
10723
        '%FE' => 'þ',
10724
        '%FF' => 'ÿ',
10725
    ];
10726
  }
10727
10728
  /**
10729
   * Decodes an UTF-8 string to ISO-8859-1.
10730
   *
10731
   * @param string $str <p>The input string.</p>
10732
   * @param bool   $keepUtf8Chars
10733
   *
10734
   * @return string
10735
   */
10736 14
  public static function utf8_decode(string $str, bool $keepUtf8Chars = false): string
10737
  {
10738 14
    if ('' === $str) {
10739 5
      return '';
10740
    }
10741
10742 14
    static $UTF8_TO_WIN1252_KEYS_CACHE = null;
10743 14
    static $UTF8_TO_WIN1252_VALUES_CACHE = null;
10744
10745 14
    if ($UTF8_TO_WIN1252_KEYS_CACHE === null) {
10746
10747 1
      if (self::$WIN1252_TO_UTF8 === null) {
10748
        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 null|array. 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...
10749
      }
10750
10751 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

10751
      $UTF8_TO_WIN1252_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10752 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

10752
      $UTF8_TO_WIN1252_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10753
    }
10754
10755
    /** @noinspection PhpInternalEntityUsedInspection */
10756 14
    $str = \str_replace($UTF8_TO_WIN1252_KEYS_CACHE, $UTF8_TO_WIN1252_VALUES_CACHE, $str);
10757
10758 14
    if (!isset(self::$SUPPORT['already_checked_via_portable_utf8'])) {
10759
      self::checkForSupport();
10760
    }
10761
10762
    // save for later comparision
10763 14
    $str_backup = $str;
10764 14
    $len = self::strlen_in_byte($str);
10765
10766 14
    if (self::$ORD === null) {
10767
      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 null|array. 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...
10768
    }
10769
10770 14
    if (self::$CHR === null) {
10771
      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 null|array. 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...
10772
    }
10773
10774 14
    $noCharFound = '?';
10775
    /** @noinspection ForeachInvariantsInspection */
10776 14
    for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
10777 14
      switch ($str[$i] & "\xF0") {
10778 14
        case "\xC0":
10779 12
        case "\xD0":
10780 14
          $c = (self::$ORD[$str[$i] & "\x1F"] << 6) | self::$ORD[$str[++$i] & "\x3F"];
10781 14
          $str[$j] = $c < 256 ? self::$CHR[$c] : $noCharFound;
10782 14
          break;
10783
10784
        /** @noinspection PhpMissingBreakStatementInspection */
10785 12
        case "\xF0":
10786
          ++$i;
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment if this fall-through is intended.
Loading history...
10787 12
        case "\xE0":
10788 10
          $str[$j] = $noCharFound;
10789 10
          $i += 2;
10790 10
          break;
10791
10792
        default:
10793 12
          $str[$j] = $str[$i];
10794
      }
10795
    }
10796
10797 14
    $return = self::substr_in_byte($str, 0, $j);
10798 14
    if ($return === false) {
0 ignored issues
show
introduced by
The condition $return === false is always false.
Loading history...
10799
      $return = '';
10800
    }
10801
10802
    if (
10803 14
        $keepUtf8Chars === true
10804
        &&
10805 14
        self::strlen($return) >= self::strlen($str_backup)
10806
    ) {
10807 2
      return $str_backup;
10808
    }
10809
10810 14
    return $return;
10811
  }
10812
10813
  /**
10814
   * Encodes an ISO-8859-1 string to UTF-8.
10815
   *
10816
   * @param string $str <p>The input string.</p>
10817
   *
10818
   * @return string
10819
   */
10820 14
  public static function utf8_encode(string $str): string
10821
  {
10822 14
    if ('' === $str) {
10823 13
      return '';
10824
    }
10825
10826 14
    $str = \utf8_encode($str);
10827
10828
    // the polyfill maybe return false
10829
    /** @noinspection CallableParameterUseCaseInTypeContextInspection */
10830 14
    if ($str === false) {
10831
      return '';
10832
    }
10833
10834 14
    if (false === \strpos($str, "\xC2")) {
10835 6
      return $str;
10836
    }
10837
10838 12
    static $WIN1252_TO_UTF8_KEYS_CACHE = null;
10839 12
    static $WIN1252_TO_UTF8_VALUES_CACHE = null;
10840
10841 12
    if ($WIN1252_TO_UTF8_KEYS_CACHE === null) {
10842
10843 1
      if (self::$WIN1252_TO_UTF8 === null) {
10844
        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 null|array. 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...
10845
      }
10846
10847 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

10847
      $WIN1252_TO_UTF8_KEYS_CACHE = \array_keys(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10848 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

10848
      $WIN1252_TO_UTF8_VALUES_CACHE = \array_values(/** @scrutinizer ignore-type */ self::$WIN1252_TO_UTF8);
Loading history...
10849
    }
10850
10851 12
    return \str_replace($WIN1252_TO_UTF8_KEYS_CACHE, $WIN1252_TO_UTF8_VALUES_CACHE, $str);
10852
  }
10853
10854
  /**
10855
   * fix -> utf8-win1252 chars
10856
   *
10857
   * @param string $str <p>The input string.</p>
10858
   *
10859
   * @return string
10860
   *
10861
   * @deprecated <p>use "UTF8::fix_simple_utf8()"</p>
10862
   */
10863 2
  public static function utf8_fix_win1252_chars(string $str): string
10864
  {
10865 2
    return self::fix_simple_utf8($str);
10866
  }
10867
10868
  /**
10869
   * Returns an array with all utf8 whitespace characters.
10870
   *
10871
   * @see   : http://www.bogofilter.org/pipermail/bogofilter/2003-March/001889.html
10872
   *
10873
   * @author: Derek E. [email protected]
10874
   *
10875
   * @return string[]
10876
   *                 An array with all known whitespace characters as values and the type of whitespace as keys
10877
   *                 as defined in above URL.
10878
   */
10879 2
  public static function whitespace_table(): array
10880
  {
10881 2
    return self::$WHITESPACE_TABLE;
10882
  }
10883
10884
  /**
10885
   * Limit the number of words in a string.
10886
   *
10887
   * @param string $str      <p>The input string.</p>
10888
   * @param int    $limit    <p>The limit of words as integer.</p>
10889
   * @param string $strAddOn <p>Replacement for the striped string.</p>
10890
   *
10891
   * @return string
10892
   */
10893 2
  public static function words_limit(string $str, int $limit = 100, string $strAddOn = '…'): string
10894
  {
10895 2
    if ('' === $str) {
10896 2
      return '';
10897
    }
10898
10899 2
    if ($limit < 1) {
10900 2
      return '';
10901
    }
10902
10903 2
    \preg_match('/^\s*+(?:\S++\s*+){1,' . $limit . '}/u', $str, $matches);
10904
10905
    if (
10906 2
        !isset($matches[0])
10907
        ||
10908 2
        self::strlen($str) === self::strlen($matches[0])
10909
    ) {
10910 2
      return $str;
10911
    }
10912
10913 2
    return self::rtrim($matches[0]) . $strAddOn;
10914
  }
10915
10916
  /**
10917
   * Wraps a string to a given number of characters
10918
   *
10919
   * @link  http://php.net/manual/en/function.wordwrap.php
10920
   *
10921
   * @param string $str   <p>The input string.</p>
10922
   * @param int    $width [optional] <p>The column width.</p>
10923
   * @param string $break [optional] <p>The line is broken using the optional break parameter.</p>
10924
   * @param bool   $cut   [optional] <p>
10925
   *                      If the cut is set to true, the string is
10926
   *                      always wrapped at or before the specified width. So if you have
10927
   *                      a word that is larger than the given width, it is broken apart.
10928
   *                      </p>
10929
   *
10930
   * @return string The given string wrapped at the specified column.
10931
   */
10932 10
  public static function wordwrap(string $str, int $width = 75, string $break = "\n", bool $cut = false): string
10933
  {
10934 10
    if ('' === $str || '' === $break) {
10935 3
      return '';
10936
    }
10937
10938 8
    $w = '';
10939 8
    $strSplit = \explode($break, $str);
10940 8
    if ($strSplit === false) {
10941
      $count = 0;
10942
    } else {
10943 8
      $count = \count($strSplit);
10944
    }
10945
10946 8
    $chars = [];
10947
    /** @noinspection ForeachInvariantsInspection */
10948 8
    for ($i = 0; $i < $count; ++$i) {
10949
10950 8
      if ($i) {
10951 1
        $chars[] = $break;
10952 1
        $w .= '#';
10953
      }
10954
10955 8
      $c = $strSplit[$i];
10956 8
      unset($strSplit[$i]);
10957
10958 8
      if ($c !== null) {
10959 8
        foreach (self::split($c) as $c) {
10960 8
          $chars[] = $c;
10961 8
          $w .= ' ' === $c ? ' ' : '?';
10962
        }
10963
      }
10964
    }
10965
10966 8
    $strReturn = '';
10967 8
    $j = 0;
10968 8
    $b = $i = -1;
10969 8
    $w = \wordwrap($w, $width, '#', $cut);
10970
10971 8
    while (false !== $b = self::strpos($w, '#', $b + 1)) {
10972 6
      for (++$i; $i < $b; ++$i) {
10973 6
        $strReturn .= $chars[$j];
10974 6
        unset($chars[$j++]);
10975
      }
10976
10977 6
      if ($break === $chars[$j] || ' ' === $chars[$j]) {
10978 3
        unset($chars[$j++]);
10979
      }
10980
10981 6
      $strReturn .= $break;
10982
    }
10983
10984 8
    return $strReturn . \implode('', $chars);
10985
  }
10986
10987
  /**
10988
   * Line-Wrap the string after $limit, but also after the next word.
10989
   *
10990
   * @param string $str
10991
   * @param int    $limit
10992
   *
10993
   * @return string
10994
   */
10995 1
  public static function wordwrap_per_line(string $str, int $limit): string
10996
  {
10997 1
    $strings = (array)\preg_split('/\\r\\n|\\r|\\n/', $str);
10998
10999 1
    $string = '';
11000 1
    foreach ($strings as $value) {
11001 1
      if ($value === false) {
11002
        continue;
11003
      }
11004
11005 1
      $string .= wordwrap($value, $limit);
11006 1
      $string .= "\n";
11007
    }
11008
11009 1
    return $string;
11010
  }
11011
11012
  /**
11013
   * Returns an array of Unicode White Space characters.
11014
   *
11015
   * @return string[] An array with numeric code point as key and White Space Character as value.
11016
   */
11017 2
  public static function ws(): array
11018
  {
11019 2
    return self::$WHITESPACE;
11020
  }
11021
11022
11023
}
11024