Issues (14)

src/DynamicObject.php (1 issue)

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
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

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:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
31
                    $values[$arr[$i - 1]] = $arr[$i];
32
                }
33
34
                return $values;
35
            }
36
        }
37
38
        return json_decode($value);
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)) {
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
}