-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathMetaData.php
121 lines (104 loc) · 2.59 KB
/
MetaData.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
namespace Kodeine\Metable;
use DateTime;
use Illuminate\Database\Eloquent\Model;
/**
* @property string $type
*/
class MetaData extends Model
{
/**
* @var array
*/
protected $fillable = ['key', 'value'];
/**
* @var array
*/
protected $dataTypes = ['boolean', 'integer', 'double', 'float', 'string', 'NULL'];
/**
* Whether or not to delete the Data on save.
*
* @var bool
*/
protected $markForDeletion = false;
protected $modelCache = [];
/**
* Whether or not to delete the Data on save.
*
* @param bool $bool
*/
public function markForDeletion(bool $bool = true) {
$this->markForDeletion = $bool;
}
/**
* Check if the model needs to be deleted.
*
* @return bool
*/
public function isMarkedForDeletion(): bool {
return $this->markForDeletion;
}
/**
* Set the value and type.
*
* @param $value
*/
public function setValueAttribute($value) {
$type = gettype( $value );
if ( is_array( $value ) ) {
$this->type = 'array';
$this->attributes['value'] = json_encode( $value );
}
elseif ( $value instanceof DateTime ) {
$this->type = 'datetime';
$this->attributes['value'] = $this->fromDateTime( $value );
}
elseif ( $value instanceof Model ) {
$this->type = 'model';
$class = get_class( $value );
$this->attributes['value'] = $class . (! $value->exists ? '' : '#' . $value->getKey());
// Update the cache
$this->modelCache[$class][$value->getKey()] = $value;
}
elseif ( is_object( $value ) ) {
$this->type = 'object';
$this->attributes['value'] = json_encode( $value );
}
else {
$this->type = in_array( $type, $this->dataTypes ) ? $type : 'string';
$this->attributes['value'] = $value;
}
}
public function getValueAttribute($value) {
$type = $this->type ?: 'null';
switch ($type) {
case 'array':
return json_decode( $value, true );
case 'object':
return json_decode( $value );
case 'datetime':
return $this->asDateTime( $value );
case 'model':
{
if ( strpos( $value, '#' ) === false ) {
return new $value();
}
list( $class, $id ) = explode( '#', $value );
return $this->resolveModelInstance( $class, $id );
}
}
if ( in_array( $type, $this->dataTypes ) ) {
settype( $value, $type );
}
return $value;
}
protected function resolveModelInstance($model, $Key) {
if ( ! isset( $this->modelCache[$model] ) ) {
$this->modelCache[$model] = [];
}
if ( ! isset( $this->modelCache[$model][$Key] ) ) {
$this->modelCache[$model][$Key] = (new $model())->findOrFail( $Key );
}
return $this->modelCache[$model][$Key];
}
}