forked from php-soap/encoding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScopedCache.php
More file actions
44 lines (38 loc) · 984 Bytes
/
ScopedCache.php
File metadata and controls
44 lines (38 loc) · 984 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
declare(strict_types=1);
namespace Soap\Encoding\Cache;
use Closure;
use WeakMap;
/**
* GC-safe cache scoped to an object's lifetime.
* When the scope object is garbage collected, all its cached entries are released.
*
* @template TScope of object
* @template TValue
*
* @internal
*/
final class ScopedCache
{
/** @var WeakMap<TScope, array<string, TValue>> */
private WeakMap $cache;
public function __construct()
{
/** @var WeakMap<TScope, array<string, TValue>> */
$this->cache = new WeakMap();
}
/**
* @param TScope $scope
* @param Closure(): TValue $factory
* @return TValue
*/
public function lookup(object $scope, string $key, Closure $factory): mixed
{
$scopeCache = $this->cache[$scope] ?? [];
if (!isset($scopeCache[$key])) {
$scopeCache[$key] = $factory();
$this->cache[$scope] = $scopeCache;
}
return $scopeCache[$key];
}
}