src/Serializor.php source

1 <?php
2
3 declare(strict_types=1);
4
5 namespace Serializor;
6
7 use Serializor\Codec;
8
9 /**
10 * Serializor class responsible for serializing and deserializing data,
11 * particularly closures and anonymous classes.
12 */
13 class Serializor
14 {
15 /**
16 * Singleton instance for the default Serializor codec.
17 */
18 private static ?Codec $singleton = null;
19
20 /** @var string|null The default secret key used for serialization security */
21 private static ?string $defaultSecret = null;
22
23 /**
24 * Serializes the given value using the default Serializor instance.
25 * This method acts as a replacement for PHP's native `serialize()` function.
26 *
27 * @param mixed $value The value to be serialized
28 * @return string The serialized string
29 */
30 public static function serialize(mixed $value): string
31 {
32 return self::getInstance()->serialize($value);
33 }
34
35 /**
36 * Unserializes the given string using the default Serializor instance.
37 * This method acts as a replacement for PHP's native `unserialize()` function.
38 *
39 * @param string $value The serialized string to be unserialized
40 * @return mixed The unserialized value
41 */
42 public static function &unserialize(string $value): mixed
43 {
44 return self::getInstance()->unserialize($value);
45 }
46
47 /**
48 * Retrieves the default Codec instance. This is a singleton, meaning
49 * only one instance is created and reused across multiple calls.
50 *
51 * @return Codec The codec instance for serializing and deserializing data
52 */
53 public static function getInstance(): Codec
54 {
55 if (self::$singleton === null) {
56 self::$singleton = new Codec(self::$defaultSecret ?? '');
57 }
58 return self::$singleton;
59 }
60
61 /**
62 * Sets a custom secret key for the default Serializor instance, which can be
63 * used to secure the serialization process.
64 *
65 * @param string $secret The secret key to use for serialization
66 */
67 public static function setDefaultSecret(string $secret): void
68 {
69 self::$defaultSecret = $secret;
70 self::$singleton = null;
71 }
72
73 /**
74 * Register a custom factory for handling user-defined types.
75 *
76 * @param class-string $class The class name to handle
77 * @param callable(object): ?Stasis $factory Factory that returns a Stasis or null to skip
78 */
79 public static function registerFactory(string $class, callable $factory): void
80 {
81 Stasis::registerFactory($class, $factory);
82 }
83 }
84