forked from octobercms/library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpandoModel.php
More file actions
98 lines (83 loc) · 2.61 KB
/
ExpandoModel.php
File metadata and controls
98 lines (83 loc) · 2.61 KB
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
<?php namespace October\Rain\Database;
/**
* ExpandoModel treats all attributes as dynamic that are serialized to a single JSON column
* in the database. This is useful for settings and user preference model base classes.
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
class ExpandoModel extends Model
{
/**
* @var string expandoColumn name to store the data
*/
protected $expandoColumn = 'value';
/**
* @var array expandoPassthru attributes that should not be serialized
*/
protected $expandoPassthru = [];
/**
* __construct
*/
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->bindEvent('model.afterFetch', [$this, 'expandoAfterFetch']);
$this->bindEvent('model.afterSave', [$this, 'expandoAfterSave']);
// Process attributes last for traits with attribute modifiers
$this->bindEvent('model.beforeSaveDone', [$this, 'expandoBeforeSaveDone'], -1);
$this->addCasts([$this->expandoColumn => 'array']);
}
/**
* setExpandoAttributes on the model and protects the passthru values
*/
public function setExpandoAttributes(array $attributes = [])
{
$this->attributes = array_merge(
$this->attributes,
array_diff_key($attributes, array_flip($this->getExpandoPassthru()))
);
}
/**
* expandoAfterFetch constructor event
*/
public function expandoAfterFetch()
{
$this->attributes = array_merge((array) $this->{$this->expandoColumn}, $this->attributes);
$this->syncOriginal();
}
/**
* expandoBeforeSaveDone constructor event
*/
public function expandoBeforeSaveDone()
{
$this->{$this->expandoColumn} = array_diff_key(
$this->attributes,
array_flip($this->getExpandoPassthru())
);
$this->attributes = array_diff_key($this->attributes, $this->{$this->expandoColumn});
}
/**
* expandoAfterSave constructor event
*/
public function expandoAfterSave()
{
$this->attributes = array_merge($this->{$this->expandoColumn}, $this->attributes);
}
/**
* getExpandoPassthru
*/
protected function getExpandoPassthru()
{
$defaults = [
$this->expandoColumn,
$this->getKeyName(),
$this->getCreatedAtColumn(),
$this->getUpdatedAtColumn(),
'site_root_id',
'updated_user_id',
'created_user_id'
];
return array_merge($defaults, $this->expandoPassthru);
}
}