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
|
|
|
|