Completed
Push — master ( 7f1ae7...cc37ee )
by Freek
01:40
created

SchemalessAttributes::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace Spatie\SchemalessAttributes;
4
5
use Countable;
6
use ArrayAccess;
7
use Illuminate\Database\Eloquent\Model;
8
9
class SchemalessAttributes implements ArrayAccess, Countable
10
{
11
    /** @var \Illuminate\Database\Eloquent\Model */
12
    protected $model;
13
14
    /** @var string */
15
    protected $sourceAttributeName;
16
17
    /** @var array */
18
    protected $schemalessAttributes = [];
19
20
    public static function createForModel(Model $model, string $sourceAttributeName): self
21
    {
22
        return new static($model, $sourceAttributeName);
23
    }
24
25
    public function __construct(Model $model, string $sourceAttributeName)
26
    {
27
        $this->model = $model;
28
29
        $this->sourceAttributeName = $sourceAttributeName;
30
31
        $this->schemalessAttributes = $this->getRawSchemalessAttributes();
32
    }
33
34
    public function __get(string $name)
35
    {
36
        return $this->get($name);
37
    }
38
39
    public function get(string $name)
40
    {
41
        return array_get($this->schemalessAttributes, $name);
42
    }
43
44
    public function __set(string $name, $value)
45
    {
46
        $this->set($name, $value);
47
    }
48
49
    public function set(string $name, $value)
50
    {
51
        array_set($this->schemalessAttributes, $name, $value);
52
53
        $this->model->{$this->sourceAttributeName} = $this->schemalessAttributes;
54
    }
55
56
    public function replace($value)
57
    {
58
        $this->schemalessAttributes = $value;
59
    }
60
61
62
63
    public function forget(string $name): self
64
    {
65
        $this->model->{$this->sourceAttributeName} = array_except($this->schemalessAttributes, $name);
66
67
        return $this;
68
    }
69
70
    public function all(): array
71
    {
72
        return $this->getRawSchemalessAttributes();
73
    }
74
75
    protected function getRawSchemalessAttributes(): array
76
    {
77
        return json_decode($this->model->getAttributes()[$this->sourceAttributeName] ?? '{}', true);
78
    }
79
80
    public function offsetExists($offset)
81
    {
82
        return array_has($this->schemalessAttributes, $offset);
83
    }
84
85
    public function offsetGet($offset)
86
    {
87
        return $this->$offset;
88
    }
89
90
    public function offsetSet($offset, $value)
91
    {
92
        $this->{$offset} = $value;
93
    }
94
95
    public function offsetUnset($offset)
96
    {
97
        $this->forget($offset);
98
    }
99
100
    public function count()
101
    {
102
        return count($this->schemalessAttributes);
103
    }
104
}
105