| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- namespace App\Module\Transfer\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Database\Eloquent\Model;
- /**
- * 回调数据转换器
- */
- class CallbackDataCast implements CastsAttributes
- {
- /**
- * 将取出的数据进行转换
- */
- public function get(Model $model, string $key, mixed $value, array $attributes): mixed
- {
- if (is_null($value)) {
- return [];
- }
- if (is_string($value)) {
- $decoded = json_decode($value, true);
- return is_array($decoded) ? $decoded : [];
- }
- return is_array($value) ? $value : [];
- }
- /**
- * 转换成将要进行存储的值
- */
- public function set(Model $model, string $key, mixed $value, array $attributes): mixed
- {
- if (is_null($value)) {
- return null;
- }
- if (is_array($value)) {
- return json_encode($value, JSON_UNESCAPED_UNICODE);
- }
- if (is_string($value)) {
- // 验证是否为有效的JSON
- $decoded = json_decode($value, true);
- if (json_last_error() === JSON_ERROR_NONE) {
- return $value;
- }
- }
- // 其他类型转换为JSON
- return json_encode($value, JSON_UNESCAPED_UNICODE);
- }
- }
|