Skip to content

Commit

Permalink
fix: add both serialization implementations
Browse files Browse the repository at this point in the history
As the minimum supported PHP version lowered, magic methods for serialization stopped working, added both implementations so it would work in any version
  • Loading branch information
PAXANDDOS committed Mar 24, 2023
1 parent f9d5f68 commit 7f8b56c
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions src/Helpers/SerializableClosure.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* @package Resque
* @author Michael Haynes
*/
final class SerializableClosure
final class SerializableClosure implements \Serializable
{
/**
* The Closure instance.
Expand Down Expand Up @@ -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.
*
Expand Down Expand Up @@ -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);
}

/**
Expand Down

0 comments on commit 7f8b56c

Please sign in to comment.