| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
- namespace App\Module\GameItems\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Database\Eloquent\Model;
- class DisplayAttributesCast implements CastsAttributes
- {
- /**
- * 将取出的数据转换为对应的类型
- *
- * @param Model $model
- * @param string $key
- * @param mixed $value
- * @param array $attributes
- * @return array
- */
- public function get($model, string $key, $value, array $attributes)
- {
- if (is_null($value)) {
- return [];
- }
- $decoded = json_decode($value, true);
- return is_array($decoded) ? $decoded : [];
- }
- /**
- * 将给定的值转换为存储格式
- *
- * @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;
- }
- }
|