From 79cca5defa6b58f393958f97f5f6922e9327a00e Mon Sep 17 00:00:00 2001 From: Sorin Sarca Date: Sat, 4 Jan 2025 16:09:39 +0200 Subject: [PATCH] Fixed unserialization cache (#150) --- src/ClosureInfo.php | 4 +++ tests/PHP80/UnserializeTest.php | 47 +++++++++++++++++++++++++++++++++ tests/PHP80/v4/sum.bin | 1 + tests/PHP80/v4/sum.security.bin | 2 ++ 4 files changed, 54 insertions(+) create mode 100644 tests/PHP80/UnserializeTest.php create mode 100644 tests/PHP80/v4/sum.bin create mode 100644 tests/PHP80/v4/sum.security.bin diff --git a/src/ClosureInfo.php b/src/ClosureInfo.php index a741b17..03ead18 100644 --- a/src/ClosureInfo.php +++ b/src/ClosureInfo.php @@ -166,6 +166,10 @@ public function __unserialize(array $data): void $this->body = $data['body']; $this->use = $data['use'] ?? null; $this->flags = $data['flags'] ?? 0; + if ($this->key && !isset(self::$cache[$this->key])) { + // save it to cache + self::$cache[$this->key] = $this; + } } public static function createKey(string $body, ?string $header = null): string diff --git a/tests/PHP80/UnserializeTest.php b/tests/PHP80/UnserializeTest.php new file mode 100644 index 0000000..7ffa52d --- /dev/null +++ b/tests/PHP80/UnserializeTest.php @@ -0,0 +1,47 @@ +u("sum"); + $this->assertEquals(5, $f(2, 3)); + } + + public function testSumSecurity() + { + $f = $this->u("sum.security", "opis-secret"); + $this->assertEquals(15, $f(10, 5)); + } + + public function testSumSecurityNoSecret() + { + $this->expectException(SecurityException::class); + $f = $this->u("sum.security"); + } + + public function testSumSecurityWrongSecret() + { + $this->expectException(SecurityException::class); + $f = $this->u("sum.security", "other-secret"); + } + + private function u(string $name, SecurityProviderInterface|string|null $security = null): mixed + { + $data = file_get_contents(__DIR__ . "/v4/{$name}.bin"); + if (is_string($security)) { + $security = new DefaultSecurityProvider($security); + } + return Serializer::unserialize($data, $security); + } +} \ No newline at end of file diff --git a/tests/PHP80/v4/sum.bin b/tests/PHP80/v4/sum.bin new file mode 100644 index 0000000..b5b900a --- /dev/null +++ b/tests/PHP80/v4/sum.bin @@ -0,0 +1 @@ +O:16:"Opis\Closure\Box":2:{i:0;i:1;i:1;a:1:{s:4:"info";O:24:"Opis\Closure\ClosureInfo":4:{s:3:"key";s:32:"093e81f0bc16d309b87c6468c295a871";s:7:"imports";s:14:"namespace Abc;";s:4:"body";s:34:"fn(int $a, int $b): int => $a + $b";s:5:"flags";i:1;}}} \ No newline at end of file diff --git a/tests/PHP80/v4/sum.security.bin b/tests/PHP80/v4/sum.security.bin new file mode 100644 index 0000000..00bf785 --- /dev/null +++ b/tests/PHP80/v4/sum.security.bin @@ -0,0 +1,2 @@ +@3dYblAsRY6xP6slSCshCy0luKsYh05GmQKapFqTJ8jM= +O:16:"Opis\Closure\Box":2:{i:0;i:1;i:1;a:1:{s:4:"info";O:24:"Opis\Closure\ClosureInfo":4:{s:3:"key";s:32:"093e81f0bc16d309b87c6468c295a871";s:7:"imports";s:14:"namespace Abc;";s:4:"body";s:34:"fn(int $a, int $b): int => $a + $b";s:5:"flags";i:1;}}} \ No newline at end of file