Skip to content

Instantly share code, notes, and snippets.

@SamMousa
Created August 8, 2023 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamMousa/4df8735a58a0f5daf60cfa3716b9add6 to your computer and use it in GitHub Desktop.
Save SamMousa/4df8735a58a0f5daf60cfa3716b9add6 to your computer and use it in GitHub Desktop.
Unserialize without worrying about uninitialized properties
<?php
declare(strict_types=1);
trait SafeUnserialize
{
public function __wakeup(): void
{
$rc = new \ReflectionClass(self::class);
/** @var array<string, \ReflectionParameter> $constructorParameters */
$constructorParameters = [];
foreach($rc->getConstructor()->getParameters() as $parameter) {
$constructorParameters[$parameter->getName()] = $parameter;
}
foreach($rc->getProperties() as $property) {
if (!$property->isInitialized($this)) {
if ($property->hasDefaultValue()) {
$property->setValue($this, $property->getDefaultValue());
} elseif ($property->isPromoted() && $constructorParameters[$property->getName()]->isDefaultValueAvailable()) {
$property->setValue($this, $constructorParameters[$property->getName()]->getDefaultValue());
} elseif ($property->isPromoted() && $constructorParameters[$property->getName()]->allowsNull()) {
$property->setValue($this, null);
} else {
throw new \RuntimeException('Unserialized object has uninitialized properties: ' . $property->getName());
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment