| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Module\GameItems\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Database\Eloquent\Model;
- use JsonMapper;
- class DisplayAttributesCast extends \UCore\Model\CastsAttributes
- {
- /**
- * 客户端图标地址
- * @var string $img
- */
- public string $img = ' ';
- /**
- * 将给定的值转换为存储格式
- *
- * @param Model $model
- * @param string $key
- * @param mixed $value
- * @param array $attributes
- * @return string|null
- */
- public function set($model, string $key, $value, array $attributes)
- {
- if (is_null($value)) {
- return json_encode([], JSON_UNESCAPED_UNICODE);
- }
- if (is_array($value)) {
- // 确保所有值都是字符串类型
- $sanitized = [];
- foreach ($value as $k => $v) {
- $sanitized[$k] = (string)$v;
- }
- return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
- }
- if (is_string($value) && $this->isJson($value)) {
- // 如果已经是JSON字符串,确保解码后的值都是字符串类型
- $decoded = json_decode($value, true);
- if (is_array($decoded)) {
- $sanitized = [];
- foreach ($decoded as $k => $v) {
- $sanitized[$k] = (string)$v;
- }
- return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
- }
- return $value;
- }
- return json_encode([], JSON_UNESCAPED_UNICODE);
- }
- /**
- * 判断字符串是否为有效的JSON
- *
- * @param string $value
- * @return bool
- */
- protected function isJson($value)
- {
- if (!is_string($value)) {
- return false;
- }
- json_decode($value);
- return json_last_error() === JSON_ERROR_NONE;
- }
- }
|