-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathVirtualColumn.php
More file actions
203 lines (165 loc) · 5.51 KB
/
VirtualColumn.php
File metadata and controls
203 lines (165 loc) · 5.51 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
<?php
declare(strict_types=1);
namespace Stancl\VirtualColumn;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
/**
* This trait lets you add a "data" column functionality to any Eloquent model.
* It serializes attributes which don't exist as columns on the model's table
* into a JSON column named data (customizable by overriding getDataColumn).
*
* @mixin \Illuminate\Database\Eloquent\Model
*/
trait VirtualColumn
{
/**
* Encrypted castables have to be handled using a special approach that prevents the data from getting encrypted repeatedly.
*
* The default encrypted castables ('encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object')
* are already handled, so you can use this array to add your own encrypted castables.
*/
public static array $customEncryptedCastables = [];
/**
* We need this property, because both created & saved event listeners
* decode the data (to take precedence before other created & saved)
* listeners, but we don't want the data to be decoded twice.
*/
public bool $dataEncoded = false;
protected function decodeVirtualColumn(): void
{
if (! $this->dataEncoded) {
return;
}
$encryptedCastables = array_merge(
static::$customEncryptedCastables,
['encrypted', 'encrypted:array', 'encrypted:collection', 'encrypted:json', 'encrypted:object'], // Default encrypted castables
);
foreach ($this->getAttribute(static::getDataColumn()) ?? [] as $key => $value) {
$attributeHasEncryptedCastable = in_array(data_get($this->getCasts(), $key), $encryptedCastables);
if ($value && $attributeHasEncryptedCastable && $this->valueEncrypted($value)) {
$this->attributes[$key] = $value;
} else {
$this->setAttribute($key, $value);
}
$this->syncOriginalAttribute($key);
}
$this->setAttribute(static::getDataColumn(), null);
$this->dataEncoded = false;
}
protected function encodeAttributes(): void
{
if ($this->dataEncoded) {
return;
}
$dataColumn = static::getDataColumn();
$customColumns = static::getCustomColumns();
$attributes = array_filter($this->getAttributes(), fn ($key) => ! in_array($key, $customColumns), ARRAY_FILTER_USE_KEY);
// Remove data column from the attributes
unset($attributes[$dataColumn]);
foreach ($attributes as $key => $value) {
// Remove attribute from the model
unset($this->attributes[$key]);
unset($this->original[$key]);
}
// Add attribute to the data column
$this->setAttribute($dataColumn, $attributes);
$this->dataEncoded = true;
}
public function valueEncrypted(string $value): bool
{
try {
Crypt::decryptString($value);
return true;
} catch (DecryptException) {
return false;
}
}
protected function decodeAttributes()
{
$this->dataEncoded = true;
$this->decodeVirtualColumn();
}
protected function getAfterListeners(): array
{
return [
'retrieved' => [
function () {
// Always decode after model retrieval
$this->dataEncoded = true;
$this->decodeVirtualColumn();
},
],
'saving' => [
[$this, 'encodeAttributes'],
],
'creating' => [
[$this, 'encodeAttributes'],
],
'updating' => [
[$this, 'encodeAttributes'],
],
];
}
protected function decodeIfEncoded()
{
if ($this->dataEncoded) {
$this->decodeVirtualColumn();
}
}
protected function fireModelEvent($event, $halt = true)
{
$this->decodeIfEncoded();
$result = parent::fireModelEvent($event, $halt);
$this->runAfterListeners($event, $halt);
return $result;
}
public function runAfterListeners($event, $halt = true)
{
$listeners = $this->getAfterListeners()[$event] ?? [];
if (! $event) {
return;
}
foreach ($listeners as $listener) {
if (is_string($listener)) {
$listener = app($listener);
$handle = [$listener, 'handle'];
} else {
$handle = $listener;
}
$handle($this);
}
}
public function getCasts()
{
return array_merge(parent::getCasts(), [
static::getDataColumn() => 'array',
]);
}
/**
* Get the name of the column that stores additional data.
*/
public static function getDataColumn(): string
{
return 'data';
}
public static function getCustomColumns(): array
{
return [
'id',
static::CREATED_AT,
static::UPDATED_AT,
];
}
/**
* Get a column name for an attribute that can be used in SQL queries.
*
* (`foo` or `data->foo` depending on whether `foo` is in custom columns)
*/
public function getColumnForQuery(string $column): string
{
if (in_array($column, static::getCustomColumns(), true)) {
return $column;
}
return static::getDataColumn() . '->' . $column;
}
}