| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- namespace App\Module\GameItems\Casts;
- use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
- use Illuminate\Database\Eloquent\Model;
- class TransactionDetailsCast 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)) {
- 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;
- }
- }
|