HalalSoft /
laravel-dynamic-column
| 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 DynamicObject 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) { |
||||
|
0 ignored issues
–
show
|
|||||
| 31 | $values[$arr[$i - 1]] = $arr[$i]; |
||||
| 32 | } |
||||
| 33 | |||||
| 34 | return $values; |
||||
| 35 | } |
||||
| 36 | } |
||||
| 37 | |||||
| 38 | return json_decode($value); |
||||
|
0 ignored issues
–
show
It seems like
$value can also be of type object; however, parameter $json of json_decode() does only seem to accept string, maybe add an additional type check?
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
Loading history...
|
|||||
| 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 | |||||
| 54 | if (is_array($value)) { |
||||
|
0 ignored issues
–
show
|
|||||
| 55 | $values = ''; |
||||
| 56 | foreach ($value as $k => $v) { |
||||
| 57 | $values .= ($values ? ',' : '')."'$k','$v'"; |
||||
| 58 | } |
||||
| 59 | |||||
| 60 | return DB::raw("column_create($values)"); |
||||
| 61 | } |
||||
| 62 | // elseif(object) |
||||
| 63 | else { |
||||
| 64 | return $value; |
||||
| 65 | } |
||||
| 66 | } |
||||
| 67 | } |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: