Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSettingsContainerAbstract.php
More file actions
Latest commit
292 lines (226 loc) · 7.53 KB
/
Copy pathSettingsContainerAbstract.php
File metadata and controls
292 lines (226 loc) · 7.53 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
<?php
/**
* Class SettingsContainerAbstract
*
* @created 28.08.2018
* @author Smiley <smiley@chillerlan.net>
* @copyright 2018 Smiley
* @license MIT
*/
declare(strict_types=1);
namespacechillerlan\Settings;
usechillerlan\Settings\Attributes\ThrowOnInvalidProperty;
useInvalidArgumentException, JsonException, PropertyHookType, ReflectionException, ReflectionObject,
ReflectionProperty, ReflectionAttribute, RuntimeException;
usefunctionis_object, json_decode, json_encode, json_last_error_msg,
method_exists, property_exists, serialize, sprintf, unserialize;
useconstJSON_THROW_ON_ERROR;
abstractclass SettingsContainerAbstract implements SettingsContainerInterface{
protectedconststringSET_PREFIX = 'set_';
protectedconststringGET_PREFIX = 'get_';
/**
* SettingsContainerAbstract constructor.
*
* @phpstan-param array<string, mixed> $properties
*/
publicfunction__construct(iterable|null$properties = null){
if(!empty($properties)){
$this->fromIterable($properties);
}
$this->construct();
}
/**
* calls a method with trait name as replacement constructor for each used trait
* (remember pre-php5 classname constructors? yeah, basically this.)
*/
protectedfunctionconstruct():void{
$traits = newReflectionObject($this)->getTraits();
foreach($traitsas$trait){
$method = $trait->getShortName();
if(method_exists($this, $method)){
$this->{$method}();
}
}
}
publicfunction__get(string$property):mixed{
// back out if the property is inaccessible
if(!property_exists($this, $property) || $this->isPrivate($property)){
if($this->throwOnInvalidProperty()){
thrownewRuntimeException(sprintf('attempt to read invalid property: "$%s"', $property));
}
returnnull;
}
// call an existing custom method, skip if the property has a hook
if(method_exists($this, static::GET_PREFIX.$property) && !$this->hasGetHook($property)){
return$this->{static::GET_PREFIX.$property}();
}
// retrieve the value (triggers an existing property hook)
return$this->{$property};
}
publicfunction__set(string$property, mixed$value):void{
if(!property_exists($this, $property) || $this->isPrivate($property)){
if($this->throwOnInvalidProperty()){
thrownewRuntimeException(sprintf('attempt to write invalid property: "$%s"', $property));
}
return;
}
if(method_exists($this, static::SET_PREFIX.$property) && !$this->hasSetHook($property)){
$this->{static::SET_PREFIX.$property}($value);
return;
}
$this->{$property} = $value;
}
publicfunction__isset(string$property):bool{
returnisset($this->{$property}) && !$this->isPrivate($property);
}
publicfunction__unset(string$property):void{
if($this->__isset($property)){
unset($this->{$property});
}
}
publicfunction__toString():string{
return$this->toJSON();
}
/**
* Checks if a property is private
*/
finalprotectedfunctionisPrivate(string$property):bool{
returnnewReflectionProperty($this, $property)->isPrivate();
}
/**
* Checks if a property has a "set" hook
*/
finalprotectedfunctionhasSetHook(string$property):bool{
returnnewReflectionProperty($this, $property)->hasHook(PropertyHookType::Set);
}
/**
* Checks if a property has a "get" hook
*/
finalprotectedfunctionhasGetHook(string$property):bool{
returnnewReflectionProperty($this, $property)->hasHook(PropertyHookType::Get);
}
/**
* Checks for the attribute "ThrowOnInvalidProperty", used in the magic get/set
*
* @see \chillerlan\Settings\Attributes\ThrowOnInvalidProperty
*/
finalprotectedfunctionthrowOnInvalidProperty():bool{
$attributes = newReflectionObject($this)
->getAttributes(ThrowOnInvalidProperty::class, ReflectionAttribute::IS_INSTANCEOF)
;
if($attributes === []){
returnfalse;
}
/** @var \chillerlan\Settings\Attributes\ThrowOnInvalidProperty $attr */
$attr = $attributes[0]->newInstance();
return$attr->throwOnInvalid;
}
publicfunctiontoArray():array{
$properties = newReflectionObject($this)
->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY | ReflectionProperty::IS_PRIVATE))
;
$data = [];
foreach($propertiesas$reflectionProperty){
// the magic getter is called intentionally here, so that any existing hook methods are called on export
$data[$reflectionProperty->name] = $this->__get($reflectionProperty->name);
}
return$data;
}
/**
* @param iterable<string, mixed> $properties
*/
publicfunctionfromIterable(iterable$properties):static{
foreach($propertiesas$key => $value){
$this->__set($key, $value);
}
return$this;
}
publicfunctiontoJSON(int|null$jsonOptions = null):string{
$json = json_encode($this, ($jsonOptions ?? 0));
if($json === false){
thrownewJsonException(json_last_error_msg()); // @codeCoverageIgnore
}
return$json;
}
publicfunctionfromJSON(string$json):static{
/** @phpstan-var array<string, mixed> $data */
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
return$this->fromIterable($data);
}
/**
* @return array<string, mixed>
*/
publicfunctionjsonSerialize():array{
return$this->toArray();
}
/**
* Returns a serialized string representation of the object in its current state (except static/readonly properties)
*/
publicfunctionserialize():string{
returnserialize($this);
}
/**
* Restores the data (except static/readonly properties) from the given serialized object to the current instance
*
* @throws \InvalidArgumentException
*/
publicfunctionunserialize(string$data):void{
$obj = unserialize($data);
if(!is_object($obj)){
thrownewInvalidArgumentException('The given serialized string is invalid');
}
$reflection = newReflectionObject($obj);
if(!$reflection->isInstance($this)){
thrownewInvalidArgumentException('The unserialized object does not match the class of this container');
}
$properties = $reflection->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY));
$data = [];
foreach($propertiesas$reflectionProperty){
// bypass existing property hooks
$data[$reflectionProperty->name] = $reflectionProperty->getRawValue($obj);
}
$this->__unserialize($data);
}
/**
* Returns a serialized array representation of the object in its current state (except static/readonly properties),
* bypassing custom getters and property hooks
*
* @return array<string, mixed>
*/
publicfunction__serialize():array{
$properties = newReflectionObject($this)
->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY))
;
$data = [];
foreach($propertiesas$reflectionProperty){
// bypass existing property hooks
$data[$reflectionProperty->name] = $reflectionProperty->getRawValue($this);
}
return$data;
}
/**
* Restores the data from the given array to the current instance,
* bypassing custom setters and property hooks
*
* @param array<string, mixed> $data
*/
publicfunction__unserialize(array$data):void{
$reflection = newReflectionObject($this);
foreach($dataas$key => $value){
try{
$reflectionProperty = $reflection->getProperty($key);
if($reflectionProperty->isStatic() || $reflectionProperty->isReadOnly()){
continue; // @codeCoverageIgnore
}
// bypass existing property hooks
$reflectionProperty->setRawValue($this, $value);
}
// @codeCoverageIgnoreStart
catch(ReflectionException){
// attempt to assign a non-existent property, skip
continue;
}
// @codeCoverageIgnoreEnd
}
}
}