| 1 |
<?php |
| 2 |
|
| 3 |
declare (strict_types=1); |
| 4 |
namespace WCPOS\Vendor\GuzzleHttp\Psr7; |
| 5 |
|
| 6 |
/** |
| 7 |
* Escapes control characters and malformed UTF-8 for use in diagnostics. |
| 8 |
*/ |
| 9 |
final class DiagnosticValue |
| 10 |
{ |
| 11 |
private function __construct() |
| 12 |
{ |
| 13 |
} |
| 14 |
/** |
| 15 |
* Escapes C0, DEL, and C1 controls as uppercase `\xNN` sequences. |
| 16 |
* |
| 17 |
* ASCII bytes from 0x20 through 0x7E and valid UTF-8 characters outside |
| 18 |
* those control ranges remain unchanged. If the input is malformed UTF-8 or |
| 19 |
* PCRE cannot process it, every byte outside printable ASCII is escaped. |
| 20 |
* Valid C1 characters are rendered as `\xNN` using their Unicode code |
| 21 |
* points. During bytewise fallback, each original byte outside printable |
| 22 |
* ASCII is rendered in the same form. The result is diagnostic text, not a |
| 23 |
* reversible encoding. |
| 24 |
* |
| 25 |
* This does not encode values for HTML, JSON, shells, terminals, URLs, or |
| 26 |
* protocol fields. |
| 27 |
*/ |
| 28 |
public static function escape(string $value) : string |
| 29 |
{ |
| 30 |
$escaped = \preg_replace_callback('/[\\x{0000}-\\x{001F}\\x{007F}-\\x{009F}]/u', static function (array $matches) : string { |
| 31 |
$character = $matches[0]; |
| 32 |
$codePoint = \strlen($character) === 1 ? \ord($character) : \ord($character[1]); |
| 33 |
return \sprintf('\\x%02X', $codePoint); |
| 34 |
}, $value); |
| 35 |
return $escaped ?? self::escapeBytes($value); |
| 36 |
} |
| 37 |
private static function escapeBytes(string $value) : string |
| 38 |
{ |
| 39 |
$escaped = ''; |
| 40 |
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) { |
| 41 |
$byte = \ord($value[$offset]); |
| 42 |
if ($byte >= 0x20 && $byte <= 0x7e) { |
| 43 |
$escaped .= $value[$offset]; |
| 44 |
continue; |
| 45 |
} |
| 46 |
$escaped .= \sprintf('\\x%02X', $byte); |
| 47 |
} |
| 48 |
return $escaped; |
| 49 |
} |
| 50 |
} |
| 51 |
|