Completed
Push — master ( df0789...8f2102 )
by Freek
01:42
created

SchemalessAttributes::replace()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
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 replace($value)
45
    {
46
        $this->schemalessAttributes = $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 forget(string $name): self
57
    {
58
        $this->model->{$this->sourceAttributeName} = array_except($this->schemalessAttributes, $name);
59
60
        return $this;
61
    }
62
63
    public function all(): array
64
    {
65
        return $this->getRawSchemalessAttributes();
66
    }
67
68
    protected function getRawSchemalessAttributes(): array
69
    {
70
        return json_decode($this->model->getAttributes()[$this->sourceAttributeName] ?? '{}', true);
71
    }
72
73
    public function offsetExists($offset)
74
    {
75
        return array_has($this->schemalessAttributes, $offset);
76
    }
77
78
    public function offsetGet($offset)
79
    {
80
        return $this->$offset;
81
    }
82
83
    public function offsetSet($offset, $value)
84
    {
85
        $this->{$offset} = $value;
86
    }
87
88
    public function offsetUnset($offset)
89
    {
90
        $this->forget($offset);
91
    }
92
93
    public function count()
94
    {
95
        return count($this->schemalessAttributes);
96
    }
97
}
98