| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class SettingsContainerAbstract |
| 4 |
* |
| 5 |
* @created 28.08.2018 |
| 6 |
* @author Smiley <[email protected]> |
| 7 |
* @copyright 2018 Smiley |
| 8 |
* @license MIT |
| 9 |
*/ |
| 10 |
declare(strict_types=1); |
| 11 |
|
| 12 |
namespace chillerlan\Settings; |
| 13 |
|
| 14 |
use chillerlan\Settings\Attributes\ThrowOnInvalidProperty; |
| 15 |
use InvalidArgumentException, JsonException, ReflectionException, ReflectionObject, |
| 16 |
ReflectionProperty, ReflectionAttribute, RuntimeException; |
| 17 |
use function is_object, json_decode, json_encode, json_last_error_msg, |
| 18 |
method_exists, property_exists, serialize, sprintf, unserialize; |
| 19 |
use const JSON_THROW_ON_ERROR, PHP_VERSION_ID; |
| 20 |
|
| 21 |
abstract class SettingsContainerAbstract implements SettingsContainerInterface{ |
| 22 |
|
| 23 |
protected const SET_PREFIX = 'set_'; |
| 24 |
protected const GET_PREFIX = 'get_'; |
| 25 |
|
| 26 |
/** |
| 27 |
* SettingsContainerAbstract constructor. |
| 28 |
* |
| 29 |
* @phpstan-param array<string, mixed> $properties |
| 30 |
*/ |
| 31 |
public function __construct(iterable|null $properties = null){ |
| 32 |
|
| 33 |
if(!empty($properties)){ |
| 34 |
$this->fromIterable($properties); |
| 35 |
} |
| 36 |
|
| 37 |
$this->construct(); |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* calls a method with trait name as replacement constructor for each used trait |
| 42 |
* (remember pre-php5 classname constructors? yeah, basically this.) |
| 43 |
*/ |
| 44 |
protected function construct():void{ |
| 45 |
$traits = (new ReflectionObject($this))->getTraits(); |
| 46 |
|
| 47 |
foreach($traits as $trait){ |
| 48 |
$method = $trait->getShortName(); |
| 49 |
|
| 50 |
if(method_exists($this, $method)){ |
| 51 |
$this->{$method}(); |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
} |
| 56 |
|
| 57 |
public function __get(string $property):mixed{ |
| 58 |
// back out if the property is inaccessible |
| 59 |
if(!property_exists($this, $property) || $this->isPrivate($property)){ |
| 60 |
|
| 61 |
if($this->throwOnInvalidProperty()){ |
| 62 |
throw new RuntimeException(sprintf('attempt to read invalid property: "$%s"', $property)); |
| 63 |
} |
| 64 |
|
| 65 |
return null; |
| 66 |
} |
| 67 |
// call an existing custom method, skip if the property has a hook |
| 68 |
if(method_exists($this, static::GET_PREFIX.$property) && !$this->hasGetHook($property)){ |
| 69 |
return $this->{static::GET_PREFIX.$property}(); |
| 70 |
} |
| 71 |
// retrieve the value (triggers an existing property hook) |
| 72 |
return $this->{$property}; |
| 73 |
} |
| 74 |
|
| 75 |
public function __set(string $property, mixed $value):void{ |
| 76 |
|
| 77 |
if(!property_exists($this, $property) || $this->isPrivate($property)){ |
| 78 |
|
| 79 |
if($this->throwOnInvalidProperty()){ |
| 80 |
throw new RuntimeException(sprintf('attempt to write invalid property: "$%s"', $property)); |
| 81 |
} |
| 82 |
|
| 83 |
return; |
| 84 |
} |
| 85 |
|
| 86 |
if(method_exists($this, static::SET_PREFIX.$property) && !$this->hasSetHook($property)){ |
| 87 |
$this->{static::SET_PREFIX.$property}($value); |
| 88 |
|
| 89 |
return; |
| 90 |
} |
| 91 |
|
| 92 |
$this->{$property} = $value; |
| 93 |
} |
| 94 |
|
| 95 |
public function __isset(string $property):bool{ |
| 96 |
return isset($this->{$property}) && !$this->isPrivate($property); |
| 97 |
} |
| 98 |
|
| 99 |
public function __unset(string $property):void{ |
| 100 |
|
| 101 |
if($this->__isset($property)){ |
| 102 |
unset($this->{$property}); |
| 103 |
} |
| 104 |
|
| 105 |
} |
| 106 |
|
| 107 |
public function __toString():string{ |
| 108 |
return $this->toJSON(); |
| 109 |
} |
| 110 |
|
| 111 |
/** |
| 112 |
* @internal Checks if a property is private |
| 113 |
*/ |
| 114 |
final protected function isPrivate(string $property):bool{ |
| 115 |
return (new ReflectionProperty($this, $property))->isPrivate(); |
| 116 |
} |
| 117 |
|
| 118 |
/** |
| 119 |
* @internal Checks if a property has a "set" hook |
| 120 |
*/ |
| 121 |
final protected function hasSetHook(string $property):bool{ |
| 122 |
|
| 123 |
if(PHP_VERSION_ID < 80400){ |
| 124 |
return false; |
| 125 |
} |
| 126 |
/** @phan-suppress-next-line PhanUndeclaredMethod, PhanUndeclaredClassConstant */ |
| 127 |
return (new ReflectionProperty($this, $property))->hasHook(\PropertyHookType::Set); |
| 128 |
} |
| 129 |
|
| 130 |
/** |
| 131 |
* @internal Checks if a property has a "get" hook |
| 132 |
*/ |
| 133 |
final protected function hasGetHook(string $property):bool{ |
| 134 |
|
| 135 |
if(PHP_VERSION_ID < 80400){ |
| 136 |
return false; |
| 137 |
} |
| 138 |
/** @phan-suppress-next-line PhanUndeclaredMethod, PhanUndeclaredClassConstant */ |
| 139 |
return (new ReflectionProperty($this, $property))->hasHook(\PropertyHookType::Get); |
| 140 |
} |
| 141 |
|
| 142 |
/** |
| 143 |
* @internal Checks for the attribute "ThrowOnInvalidProperty", used in the magic get/set |
| 144 |
* |
| 145 |
* @see \chillerlan\Settings\Attributes\ThrowOnInvalidProperty |
| 146 |
*/ |
| 147 |
final protected function throwOnInvalidProperty():bool{ |
| 148 |
|
| 149 |
$attributes = (new ReflectionObject($this)) |
| 150 |
->getAttributes(ThrowOnInvalidProperty::class, ReflectionAttribute::IS_INSTANCEOF) |
| 151 |
; |
| 152 |
|
| 153 |
if($attributes === []){ |
| 154 |
return false; |
| 155 |
} |
| 156 |
/** @var \chillerlan\Settings\Attributes\ThrowOnInvalidProperty $attr */ |
| 157 |
$attr = $attributes[0]->newInstance(); |
| 158 |
|
| 159 |
return $attr->throwOnInvalid; |
| 160 |
} |
| 161 |
|
| 162 |
public function toArray():array{ |
| 163 |
|
| 164 |
$properties = (new ReflectionObject($this)) |
| 165 |
->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY | ReflectionProperty::IS_PRIVATE)) |
| 166 |
; |
| 167 |
|
| 168 |
$data = []; |
| 169 |
|
| 170 |
foreach($properties as $reflectionProperty){ |
| 171 |
// the magic getter is called intentionally here, so that any existing hook methods are called on export |
| 172 |
$data[$reflectionProperty->name] = $this->__get($reflectionProperty->name); |
| 173 |
} |
| 174 |
|
| 175 |
return $data; |
| 176 |
} |
| 177 |
|
| 178 |
/** |
| 179 |
* @param iterable<string, mixed> $properties |
| 180 |
*/ |
| 181 |
public function fromIterable(iterable $properties):static{ |
| 182 |
|
| 183 |
foreach($properties as $key => $value){ |
| 184 |
$this->__set($key, $value); |
| 185 |
} |
| 186 |
|
| 187 |
return $this; |
| 188 |
} |
| 189 |
|
| 190 |
public function toJSON(int|null $jsonOptions = null):string{ |
| 191 |
$json = json_encode($this, ($jsonOptions ?? 0)); |
| 192 |
|
| 193 |
if($json === false){ |
| 194 |
throw new JsonException(json_last_error_msg()); // @codeCoverageIgnore |
| 195 |
} |
| 196 |
|
| 197 |
return $json; |
| 198 |
} |
| 199 |
|
| 200 |
public function fromJSON(string $json):static{ |
| 201 |
/** @phpstan-var array<string, mixed> $data */ |
| 202 |
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR); |
| 203 |
|
| 204 |
return $this->fromIterable($data); |
| 205 |
} |
| 206 |
|
| 207 |
/** |
| 208 |
* @return array<string, mixed> |
| 209 |
*/ |
| 210 |
public function jsonSerialize():array{ |
| 211 |
return $this->toArray(); |
| 212 |
} |
| 213 |
|
| 214 |
/** |
| 215 |
* Returns a serialized string representation of the object in its current state (except static/readonly properties) |
| 216 |
*/ |
| 217 |
public function serialize():string{ |
| 218 |
return serialize($this); |
| 219 |
} |
| 220 |
|
| 221 |
/** |
| 222 |
* Restores the data (except static/readonly properties) from the given serialized object to the current instance |
| 223 |
* |
| 224 |
* @throws \InvalidArgumentException |
| 225 |
*/ |
| 226 |
public function unserialize(string $data):void{ |
| 227 |
$obj = unserialize($data); |
| 228 |
|
| 229 |
if(!is_object($obj)){ |
| 230 |
throw new InvalidArgumentException('The given serialized string is invalid'); |
| 231 |
} |
| 232 |
|
| 233 |
$reflection = new ReflectionObject($obj); |
| 234 |
|
| 235 |
if(!$reflection->isInstance($this)){ |
| 236 |
throw new InvalidArgumentException('The unserialized object does not match the class of this container'); |
| 237 |
} |
| 238 |
|
| 239 |
$properties = $reflection->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY)); |
| 240 |
$data = []; |
| 241 |
|
| 242 |
foreach($properties as $reflectionProperty){ |
| 243 |
$data[$reflectionProperty->name] = (PHP_VERSION_ID < 80400) |
| 244 |
? $reflectionProperty->getValue($obj) |
| 245 |
/** @phan-suppress-next-line PhanUndeclaredMethod */ |
| 246 |
: $reflectionProperty->getRawValue($obj); |
| 247 |
} |
| 248 |
|
| 249 |
$this->__unserialize($data); |
| 250 |
} |
| 251 |
|
| 252 |
/** |
| 253 |
* Returns a serialized array representation of the object in its current state (except static/readonly properties), |
| 254 |
* bypassing custom getters and property hooks |
| 255 |
* |
| 256 |
* @return array<string, mixed> |
| 257 |
*/ |
| 258 |
public function __serialize():array{ |
| 259 |
|
| 260 |
$properties = (new ReflectionObject($this)) |
| 261 |
->getProperties(~(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_READONLY)) |
| 262 |
; |
| 263 |
|
| 264 |
$data = []; |
| 265 |
|
| 266 |
foreach($properties as $reflectionProperty){ |
| 267 |
// bypass existing property hooks for PHP >= 8.4 |
| 268 |
$data[$reflectionProperty->name] = (PHP_VERSION_ID < 80400) |
| 269 |
? $reflectionProperty->getValue($this) |
| 270 |
/** @phan-suppress-next-line PhanUndeclaredMethod */ |
| 271 |
: $reflectionProperty->getRawValue($this); |
| 272 |
} |
| 273 |
|
| 274 |
return $data; |
| 275 |
} |
| 276 |
|
| 277 |
/** |
| 278 |
* Restores the data from the given array to the current instance, |
| 279 |
* bypassing custom setters and property hooks |
| 280 |
* |
| 281 |
* @param array<string, mixed> $data |
| 282 |
*/ |
| 283 |
public function __unserialize(array $data):void{ |
| 284 |
$reflection = new ReflectionObject($this); |
| 285 |
|
| 286 |
foreach($data as $key => $value){ |
| 287 |
try{ |
| 288 |
$reflectionProperty = $reflection->getProperty($key); |
| 289 |
|
| 290 |
if($reflectionProperty->isStatic() || $reflectionProperty->isReadOnly()){ |
| 291 |
continue; // @codeCoverageIgnore |
| 292 |
} |
| 293 |
|
| 294 |
(PHP_VERSION_ID < 80400) |
| 295 |
? $reflectionProperty->setValue($this, $value) |
| 296 |
/** @phan-suppress-next-line PhanUndeclaredMethod */ |
| 297 |
: $reflectionProperty->setRawValue($this, $value); |
| 298 |
|
| 299 |
} |
| 300 |
// @codeCoverageIgnoreStart |
| 301 |
catch(ReflectionException){ |
| 302 |
// attempt to assign a non-existent property, skip |
| 303 |
continue; |
| 304 |
} |
| 305 |
// @codeCoverageIgnoreEnd |
| 306 |
} |
| 307 |
|
| 308 |
} |
| 309 |
|
| 310 |
} |