| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
if (!defined('ABSPATH')) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
/** |
| 9 |
* mbstring-backed implementation of ABJ_404_Solution_MbStringAdapter. |
| 10 |
* |
| 11 |
* Use when the PHP mbstring extension is loaded. Regex primitives live |
| 12 |
* on ABJ_404_Solution_RegexHelperMb (sibling extraction, task i826). |
| 13 |
*/ |
| 14 |
class ABJ_404_Solution_MbStringAdapterMb extends ABJ_404_Solution_MbStringAdapter { |
| 15 |
|
| 16 |
/** @var self|null */ |
| 17 |
private static $instance = null; |
| 18 |
/** |
| 19 |
* Test seam: install or clear the cached singleton instance without |
| 20 |
* private-field reflection. Pass null to reset between tests; pass a |
| 21 |
* configured instance (or double) to install it (M105 singleton-reset seam). |
| 22 |
* |
| 23 |
* @param self|null $instance |
| 24 |
* @return void |
| 25 |
*/ |
| 26 |
public static function setInstance($instance) { |
| 27 |
self::$instance = $instance; |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
public static function getInstance(): self { |
| 32 |
if (self::$instance === null) { |
| 33 |
self::$instance = new self(); |
| 34 |
} |
| 35 |
return self::$instance; |
| 36 |
} |
| 37 |
|
| 38 |
public function ord(string $char): int { |
| 39 |
return mb_ord($char); |
| 40 |
} |
| 41 |
|
| 42 |
public function strtolower(?string $string): string { |
| 43 |
if ($string === null) { |
| 44 |
return ''; |
| 45 |
} |
| 46 |
return mb_strtolower($string); |
| 47 |
} |
| 48 |
|
| 49 |
public function strlen(string $string): int { |
| 50 |
return mb_strlen($string); |
| 51 |
} |
| 52 |
|
| 53 |
/** @return int|false */ |
| 54 |
public function strpos(string $haystack, string $needle, int $offset = 0) { |
| 55 |
return mb_strpos($haystack, $needle, $offset); |
| 56 |
} |
| 57 |
|
| 58 |
public function substr(?string $str, int $start, ?int $length = null): string { |
| 59 |
if ($str === null) { |
| 60 |
return ''; |
| 61 |
} |
| 62 |
return mb_substr($str, $start, $length); |
| 63 |
} |
| 64 |
|
| 65 |
public function sanitizeInvalidUTF8(?string $string): string { |
| 66 |
if ($string === null || $string === '') { |
| 67 |
return ''; |
| 68 |
} |
| 69 |
// Converting UTF-8 to UTF-8 drops invalid sequences. mb_convert_encoding |
| 70 |
// can return false on hard failure; treat that as "nothing salvageable". |
| 71 |
$sanitized = mb_convert_encoding($string, 'UTF-8', 'UTF-8'); |
| 72 |
if (!is_string($sanitized)) { |
| 73 |
return ''; |
| 74 |
} |
| 75 |
// Remove null bytes and C0 control characters (keep \t, \n, \r). |
| 76 |
$sanitized = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/u', '', $sanitized) ?? $sanitized; |
| 77 |
return $sanitized; |
| 78 |
} |
| 79 |
} |
| 80 |
|