From 7f8b56c7388aa2e10f3a82862b6149ad23c958c2 Mon Sep 17 00:00:00 2001 From: Paul <40315177+PAXANDDOS@users.noreply.github.com> Date: Fri, 24 Mar 2023 23:33:55 +0200 Subject: [PATCH] fix: add both serialization implementations As the minimum supported PHP version lowered, magic methods for serialization stopped working, added both implementations so it would work in any version --- src/Helpers/SerializableClosure.php | 42 +++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/src/Helpers/SerializableClosure.php b/src/Helpers/SerializableClosure.php index dc28e0b..460bf65 100644 --- a/src/Helpers/SerializableClosure.php +++ b/src/Helpers/SerializableClosure.php @@ -17,7 +17,7 @@ * @package Resque * @author Michael Haynes */ -final class SerializableClosure +final class SerializableClosure implements \Serializable { /** * The Closure instance. @@ -52,6 +52,16 @@ public function __construct(\Closure $closure) $this->reflection = new \ReflectionFunction($closure); } + /** + * Get the unserialized Closure instance. + * + * @return \Closure + */ + public function getClosure(): \Closure + { + return $this->closure; + } + /** * Get the code for the Closure. * @@ -181,13 +191,35 @@ public function __unserialize(array $payload): void } /** - * Get the unserialized Closure instance. + * Serialize the Closure instance. (PHP <=7.3) * - * @return \Closure + * @return string|null */ - public function getClosure(): \Closure + public function serialize(): ?string { - return $this->closure; + return serialize([ + 'code' => $this->getCode(), 'variables' => $this->getVariables() + ]); + } + + /** + * Unserialize the Closure instance. (PHP >=7.4) + * + * @param string $payload + * @return void + */ + public function unserialize($payload): void + { + $payload = unserialize($payload); + + // We will extract the variables into the current scope so that as the Closure + // is built it will inherit the scope it had before it was serialized which + // will emulate the Closures existing in that scope instead of right now. + extract($payload['variables']); + + eval('$this->closure = '.$payload['code'].';'); + + $this->reflection = new \ReflectionFunction($this->closure); } /**