Skip to content

Commit

Permalink
Fixed unserialization cache (#150)
Browse files Browse the repository at this point in the history
  • Loading branch information
sorinsarca authored Jan 4, 2025
1 parent 72e4f84 commit 79cca5d
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/ClosureInfo.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions tests/PHP80/UnserializeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Opis\Closure\Test\PHP80;

use Opis\Closure\Security\{
SecurityException,
DefaultSecurityProvider,
SecurityProviderInterface
};
use Opis\Closure\Serializer;
use PHPUnit\Framework\TestCase;

class UnserializeTest extends TestCase
{
public function testSum()
{
$f = $this->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);
}
}
1 change: 1 addition & 0 deletions tests/PHP80/v4/sum.bin
Original file line number Diff line number Diff line change
@@ -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;}}}
2 changes: 2 additions & 0 deletions tests/PHP80/v4/sum.security.bin
Original file line number Diff line number Diff line change
@@ -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;}}}

0 comments on commit 79cca5d

Please sign in to comment.