| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- namespace App\Module\GameItems\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Database\Eloquent\Model;
- /**
- * 宝箱开启结果类型转换器
- *
- * 用于将数据库中存储的JSON格式的宝箱开启结果转换为PHP数组,以及将PHP数组转换回JSON格式。
- * 宝箱开启结果记录了用户开启宝箱获得的物品列表,包括物品ID、数量、是否为保底物品等信息。
- * 该类提供了自定义的序列化和反序列化逻辑,确保数据的一致性和有效性。
- */
- class ChestOpenResultsCast extends \UCore\Model\CastsAttributes
- {
- /**
- * 将给定的值转换为存储格式
- *
- * @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)) {
- return json_encode($value, JSON_UNESCAPED_UNICODE);
- }
- if (is_string($value) && $this->isJson($value)) {
- 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;
- }
- }
|