1 | <?php |
||
2 | |||
3 | namespace Halalsoft\LaravelDynamicColumn; |
||
4 | |||
5 | use Illuminate\Contracts\Database\Eloquent\CastsAttributes; |
||
6 | use Illuminate\Database\Eloquent\Model; |
||
7 | use Illuminate\Support\Facades\DB; |
||
8 | |||
9 | class Dynamic implements CastsAttributes |
||
10 | { |
||
11 | /** |
||
12 | * Cast the given value. |
||
13 | * |
||
14 | * @param Model $model |
||
15 | * @param string $key |
||
16 | * @param mixed $value |
||
17 | * @param array $attributes |
||
18 | * |
||
19 | * @return array |
||
20 | */ |
||
21 | public function get($model, $key, $value, $attributes) |
||
22 | { |
||
23 | if (gettype($value) == 'object') { |
||
24 | preg_match('#\((.*?)\)#', (string)$value, $match); |
||
25 | |||
26 | if (isset($match[1])) { |
||
27 | $match[1] = str_replace('\'', '', $match[1]); |
||
28 | $arr = explode(',', $match[1]); |
||
29 | $values = []; |
||
30 | for ($i = 1; $i < count($arr); $i += 2) { |
||
31 | $values[$arr[$i - 1]] = $arr[$i]; |
||
32 | } |
||
33 | |||
34 | return $values; |
||
35 | } |
||
36 | } |
||
37 | |||
38 | return json_decode($value, true); |
||
39 | } |
||
40 | |||
41 | /** |
||
42 | * Prepare the given value for storage. |
||
43 | * |
||
44 | * @param Model $model |
||
45 | * @param string $key |
||
46 | * @param array $value |
||
47 | * @param array $attributes |
||
48 | * |
||
49 | * @return string |
||
50 | */ |
||
51 | public function set($model, $key, $value, $attributes) |
||
52 | { |
||
53 | if (is_array($value)) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
54 | $values = ''; |
||
55 | foreach ($value as $k => $v) { |
||
56 | $values .= ($values ? ',' : '')."'$k','$v'"; |
||
57 | } |
||
58 | |||
59 | return !empty($values) ? DB::raw("column_create($values)") : null; |
||
60 | } else { |
||
61 | return $value; |
||
62 | } |
||
63 | } |
||
64 | } |
||
65 |