Created
August 8, 2023 08:54
-
-
Save SamMousa/4df8735a58a0f5daf60cfa3716b9add6 to your computer and use it in GitHub Desktop.
Unserialize without worrying about uninitialized properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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