|
1
|
<?php |
|
2
|
|
|
3
|
declare(strict_types=1); |
|
4
|
|
|
5
|
namespace Serializor; |
|
6
|
|
|
7
|
use Closure; |
|
8
|
use ReflectionFunction; |
|
9
|
|
|
10
|
/** |
|
11
|
* Stasis for named functions and static methods. |
|
12
|
* Very compact - just stores the callable reference. |
|
13
|
*/ |
|
14
|
final class CallableStasis extends Stasis |
|
15
|
{ |
|
16
|
/** |
|
17
|
* The callable: "funcName" or ["ClassName", "methodName"] |
|
18
|
*/ |
|
19
|
private string|array $callable; |
|
20
|
|
|
21
|
public function __construct(string|array $callable) |
|
22
|
{ |
|
23
|
$this->callable = $callable; |
|
24
|
} |
|
25
|
|
|
26
|
public function __serialize(): array |
|
27
|
{ |
|
28
|
return [$this->callable]; |
|
29
|
} |
|
30
|
|
|
31
|
public function __unserialize(array $data): void |
|
32
|
{ |
|
33
|
$this->callable = $data[0]; |
|
34
|
} |
|
35
|
|
|
36
|
public function getClassName(): string |
|
37
|
{ |
|
38
|
return Closure::class; |
|
39
|
} |
|
40
|
|
|
41
|
public static function fromClosure(Closure $value, ReflectionFunction $rf): CallableStasis |
|
42
|
{ |
|
43
|
$name = $rf->getName(); |
|
44
|
$closureCalledClass = $rf->getClosureCalledClass(); |
|
45
|
|
|
46
|
if ($closureCalledClass !== null) { |
|
47
|
// Static method |
|
48
|
return new CallableStasis([$closureCalledClass->getName(), $name]); |
|
49
|
} |
|
50
|
|
|
51
|
// Named function |
|
52
|
return new CallableStasis($name); |
|
53
|
} |
|
54
|
|
|
55
|
public function &getInstance(): mixed |
|
56
|
{ |
|
57
|
if ($this->hasInstance()) { |
|
58
|
return $this->getCachedInstance(); |
|
59
|
} |
|
60
|
|
|
61
|
$result = Closure::fromCallable($this->callable); |
|
62
|
$this->setInstance($result); |
|
63
|
return $result; |
|
64
|
} |
|
65
|
} |
|
66
|
|