| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- <?php
- namespace App\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Support\Facades\DB;
- class BinaryTextCast implements CastsAttributes
- {
- public function get($model, string $key, $value, array $attributes)
- {
- if (is_null($value)) {
- return null;
- }
- if (ctype_xdigit($value) && str_starts_with(strtolower($value), '0x')) {
- $binary_data = hex2bin(substr($value, 2));
- } else {
- $binary_data = $value;
- }
- return rtrim(mb_convert_encoding($binary_data, 'UTF-8', 'Windows-1251'));
- }
- /**
- * Подготавливает строку к сохранению в VARBINARY: CP1251 → двойной base64 → HEX 0x...
- */
- public function set($model, string $key, $value, array $attributes)
- {
- if (is_null($value)) {
- return [$key => null];
- }
- $win1251_string = mb_convert_encoding($value, 'Windows-1251', 'UTF-8');
- $hex_string = bin2hex($win1251_string);
- $binary_literal = '0x' . $hex_string;
- return [
- $key => DB::raw("CONVERT(VARBINARY(MAX), " . $binary_literal . ")")
- ];
- }
- }
|