src/UnsignedSerializableClosure.php source

1 <?php
2
3 declare(strict_types=1);
4
5 namespace Serializor;
6
7 use Closure;
8
9 /**
10 * Implementation of UnsignedSerializableClosure to be compatible with
11 * Opis/Closure and Laravel/SerializableClosure.
12 *
13 * @package Serializor
14 */
15 class UnsignedSerializableClosure
16 {
17
18 /**
19 * Singleton of the default Serializor instance which
20 * does not validate or apply signatures.
21 *
22 * @var null|Codec
23 */
24 private static ?Codec $serializor = null;
25
26 /**
27 * The closure's serializable.
28 */
29 protected $closure;
30
31 /**
32 * Creates a new serializable closure instance.
33 *
34 * @param Closure $closure
35 * @return void
36 */
37 public function __construct(Closure $closure)
38 {
39 $this->closure = $closure;
40 }
41
42 /**
43 * Resolve the closure with the given arguments.
44 *
45 * @return mixed
46 */
47 public function __invoke()
48 {
49 return call_user_func_array($this->closure, func_get_args());
50 }
51
52 /**
53 * Gets the closure.
54 *
55 * @return \Closure
56 */
57 public function getClosure()
58 {
59 return $this->closure;
60 }
61
62 /**
63 * Get the serializable representation of the closure.
64 *
65 * @return array
66 */
67 public function __serialize()
68 {
69 return [
70 '_' => self::getSerializor()->_serialize($this->closure),
71 ];
72 }
73
74 /**
75 * Restore the closure after serialization.
76 *
77 * @param array $data
78 * @return void
79 */
80 public function __unserialize($data)
81 {
82 $this->closure = self::getSerializor()->_unserialize($data['_']);
83 }
84
85 /**
86 * Returns a default instance of Serializor which does not check
87 * or add signatures to the serialized strings.
88 *
89 * @return Codec
90 */
91 public static function getSerializor(): Codec
92 {
93 if (self::$serializor === null) {
94 self::$serializor = new Codec('');
95 }
96 return self::$serializor;
97 }
98 }
99