BinaryTextCast.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Support\Facades\DB;
  5. class BinaryTextCast implements CastsAttributes
  6. {
  7. public function get($model, string $key, $value, array $attributes)
  8. {
  9. if (is_null($value)) {
  10. return null;
  11. }
  12. if (ctype_xdigit($value) && str_starts_with(strtolower($value), '0x')) {
  13. $binary_data = hex2bin(substr($value, 2));
  14. } else {
  15. $binary_data = $value;
  16. }
  17. return rtrim(mb_convert_encoding($binary_data, 'UTF-8', 'Windows-1251'));
  18. }
  19. /**
  20. * Подготавливает строку к сохранению в VARBINARY: CP1251 → двойной base64 → HEX 0x...
  21. */
  22. public function set($model, string $key, $value, array $attributes)
  23. {
  24. if (is_null($value)) {
  25. return [$key => null];
  26. }
  27. $win1251_string = mb_convert_encoding($value, 'Windows-1251', 'UTF-8');
  28. $hex_string = bin2hex($win1251_string);
  29. $binary_literal = '0x' . $hex_string;
  30. return [
  31. $key => DB::raw("CONVERT(VARBINARY(MAX), " . $binary_literal . ")")
  32. ];
  33. }
  34. }