BinaryTextCast.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace App\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Support\Facades\DB;
  5. /**
  6. * Каст для двоичных полей MSSQL (VARBINARY).
  7. *
  8. * Чтение: удаляет нулевые байты в конце, пытается дважды декодировать base64,
  9. * затем приводит к UTF-8 и убирает управляющие символы.
  10. * Запись: принимает человекочитаемую строку, при необходимости конвертирует из UTF-8 в CP1251,
  11. * выполняет двойной base64 и сохраняет как HEX-литерал 0x... для совместимости с VARBINARY на MSSQL.
  12. * Пустая строка сохраняется как 0x, NULL — как NULL.
  13. */
  14. class BinaryTextCast implements CastsAttributes
  15. {
  16. /**
  17. * Кэш размеров колонок VARBINARY: ["connection.table.column" => int|null]
  18. */
  19. private static $maxLenCache = [];
  20. /**
  21. * Декодирует значение из двойного base64 и приводит к UTF-8.
  22. */
  23. public function get($model, string $key, $value, array $attributes)
  24. {
  25. $value = $this->stripNulls($value);
  26. if ($value === null || $value === '') {
  27. return $value;
  28. }
  29. $firstByte = ord($value[0]);
  30. if ($firstByte === 0) {
  31. return $this->ensureUtf8(substr($value, 1));
  32. }
  33. if ($firstByte === 1) {
  34. $payload = substr($value, 1);
  35. $decoded = base64_decode($payload, true);
  36. return $this->ensureUtf8($decoded !== false ? $decoded : $payload);
  37. }
  38. $decoded = $value;
  39. $hadDecode = false;
  40. for ($i = 0; $i < 2; $i++) {
  41. $tmp = base64_decode($decoded, true);
  42. if ($tmp === false) {
  43. break;
  44. }
  45. $hadDecode = true;
  46. $decoded = $this->stripNulls($tmp);
  47. if ($decoded === null || $decoded === '') {
  48. break;
  49. }
  50. if (!$this->isBase64($decoded)) {
  51. break;
  52. }
  53. }
  54. if ($hadDecode && is_string($decoded)) {
  55. return $this->ensureUtf8($decoded);
  56. }
  57. if ($this->isBase64($value)) {
  58. $single = base64_decode($value, true);
  59. if ($single !== false) {
  60. return $this->ensureUtf8($single);
  61. }
  62. }
  63. return $this->ensureUtf8($value);
  64. }
  65. /**
  66. * Подготавливает строку к сохранению в VARBINARY: CP1251 → двойной base64 → HEX 0x...
  67. */
  68. public function set($model, string $key, $value, array $attributes)
  69. {
  70. $value = $this->stripNulls($value);
  71. if ($value === null) {
  72. return $value; // сохраняем NULL как есть
  73. }
  74. if ($value === '') {
  75. // Пустая бинарная строка для VARBINARY в MSSQL
  76. return DB::raw('0x');
  77. }
  78. // Определяем максимально допустимую длину VARBINARY для данной колонки
  79. $maxLen = $this->getVarbinaryMaxLength($model, $key);
  80. $raw = $this->prepareRawPayload($value);
  81. $candidates = [
  82. base64_encode(base64_encode($raw)),
  83. "\x01" . base64_encode($raw),
  84. "\x00" . $raw,
  85. ];
  86. $payload = null;
  87. foreach ($candidates as $candidate) {
  88. if (!is_int($maxLen) || strlen($candidate) <= $maxLen) {
  89. $payload = $candidate;
  90. break;
  91. }
  92. }
  93. if ($payload === null) {
  94. if (!is_int($maxLen) || $maxLen <= 0) {
  95. return DB::raw('0x');
  96. }
  97. $allowedRaw = max(0, $maxLen - 1);
  98. $raw = substr($raw, 0, $allowedRaw);
  99. $payload = "\x00" . $raw;
  100. }
  101. return DB::raw('0x' . bin2hex($payload));
  102. }
  103. private function prepareRawPayload(string $value): string
  104. {
  105. if ($value === '') {
  106. return '';
  107. }
  108. if ($this->isBase64($value)) {
  109. $first = base64_decode($value, true);
  110. if (is_string($first)) {
  111. $first = $this->stripNulls($first) ?? '';
  112. if ($first !== '' && $this->isBase64($first)) {
  113. $second = base64_decode($first, true);
  114. if (is_string($second)) {
  115. $second = $this->stripNulls($second) ?? '';
  116. return $second;
  117. }
  118. }
  119. return $first;
  120. }
  121. }
  122. if (function_exists('iconv')) {
  123. $converted = @iconv('UTF-8', 'CP1251//IGNORE', $value);
  124. if (is_string($converted)) {
  125. return $converted;
  126. }
  127. }
  128. return $value;
  129. }
  130. /**
  131. * Удаляет завершающие нулевые байты (часто встречаются в char(n)).
  132. */
  133. private function stripNulls(?string $value): ?string
  134. {
  135. return $value === null ? null : rtrim($value, "\0");
  136. }
  137. /**
  138. * Лояльная проверка, что строка похожа на base64.
  139. */
  140. private function isBase64(string $value): bool
  141. {
  142. if ($value === '') {
  143. return false;
  144. }
  145. if (preg_match('/^[A-Za-z0-9+\/\r\n]+=*$/', $value) !== 1) {
  146. return false;
  147. }
  148. return (strlen($value) % 4 === 0);
  149. }
  150. /**
  151. * Гарантирует корректный UTF-8, пытаясь конвертацию из CP1251/ISO-8859-1
  152. * и удаляя управляющие символы.
  153. */
  154. private function ensureUtf8(string $value): string
  155. {
  156. if ($value === '') {
  157. return '';
  158. }
  159. if (mb_check_encoding($value, 'UTF-8')) {
  160. return $this->removeControlChars($value);
  161. }
  162. $candidates = [];
  163. if (function_exists('iconv')) {
  164. $candidates[] = fn () => @iconv('CP1251', 'UTF-8//IGNORE', $value);
  165. }
  166. if (function_exists('mb_convert_encoding')) {
  167. $candidates[] = fn () => @mb_convert_encoding($value, 'UTF-8', 'CP1251');
  168. $candidates[] = fn () => @mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
  169. }
  170. $candidates[] = fn () => utf8_encode($value);
  171. foreach ($candidates as $candidate) {
  172. $converted = $candidate();
  173. if (is_string($converted) && mb_check_encoding($converted, 'UTF-8')) {
  174. return $this->removeControlChars($converted);
  175. }
  176. }
  177. if (function_exists('iconv')) {
  178. $sanitized = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
  179. if (is_string($sanitized) && mb_check_encoding($sanitized, 'UTF-8')) {
  180. return $this->removeControlChars($sanitized);
  181. }
  182. }
  183. return '';
  184. }
  185. /**
  186. * Удаляет управляющие ASCII-символы (0x00–0x1F, 0x7F).
  187. */
  188. private function removeControlChars(string $value): string
  189. {
  190. $clean = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $value);
  191. return is_string($clean) ? $clean : '';
  192. }
  193. /**
  194. * Возвращает максимально допустимую длину VARBINARY для указанной колонки.
  195. * Для varbinary(max) возвращает null (без ограничения).
  196. */
  197. private function getVarbinaryMaxLength($model, string $key): ?int
  198. {
  199. try {
  200. $connection = $model->getConnectionName();
  201. $table = $model->getTable();
  202. $cacheKey = $connection . '.' . $table . '.' . $key;
  203. if (array_key_exists($cacheKey, self::$maxLenCache)) {
  204. return self::$maxLenCache[$cacheKey];
  205. }
  206. $conn = DB::connection($connection);
  207. // Запрашиваем max_length из системных таблиц
  208. $sql = "SELECT c.max_length, t.name AS type_name
  209. FROM sys.columns c
  210. JOIN sys.types t ON c.user_type_id = t.user_type_id
  211. JOIN sys.tables tb ON c.object_id = tb.object_id
  212. WHERE tb.name = ? AND c.name = ?";
  213. $rows = $conn->select($sql, [$table, $key]);
  214. if (!empty($rows)) {
  215. $row = (array) $rows[0];
  216. $type = isset($row['type_name']) ? $row['type_name'] : ($row['type_name'] ?? null);
  217. $max = isset($row['max_length']) ? (int) $row['max_length'] : null;
  218. // Для varbinary(max) max_length = -1
  219. if ($max === -1 && in_array(strtolower((string) $type), ['varbinary', 'binary'], true)) {
  220. self::$maxLenCache[$cacheKey] = null;
  221. return null;
  222. }
  223. self::$maxLenCache[$cacheKey] = $max;
  224. return $max;
  225. }
  226. } catch (\Throwable $e) {
  227. // Игнорируем ошибки определения схемы, работаем без ограничения
  228. }
  229. return null;
  230. }
  231. }