forked from thecodingmachine/graphqlite
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrefetchBuffer.php
More file actions
98 lines (82 loc) · 2.64 KB
/
PrefetchBuffer.php
File metadata and controls
98 lines (82 loc) · 2.64 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
declare(strict_types=1);
namespace TheCodingMachine\GraphQLite;
use GraphQL\Type\Definition\ResolveInfo;
use SplObjectStorage;
use function md5;
use function serialize;
/**
* A class in charge of holding the fields for a deferred computation.
*/
class PrefetchBuffer
{
/** @var array<string, array<int, object>> An array of buffered, indexed by hash of arguments. */
private array $objects = [];
/** @var SplObjectStorage A Storage of prefetch method results, holds source to resolved values. */
private SplObjectStorage $results;
public function __construct()
{
$this->results = new SplObjectStorage();
}
/** @param array<array-key, mixed> $arguments The input arguments passed from GraphQL to the field. */
public function register(
object $object,
array $arguments,
ResolveInfo|null $info = null,
): void {
$this->objects[$this->computeHash($arguments, $info)][] = $object;
}
/** @param array<array-key, mixed> $arguments The input arguments passed from GraphQL to the field. */
private function computeHash(
array $arguments,
ResolveInfo|null $info,
): string {
if (
$info instanceof ResolveInfo
&& isset($info->operation)
&& $info->operation->loc?->source?->body !== null
) {
return md5(serialize($arguments) . $info->operation->loc->source->body);
}
return md5(serialize($arguments));
}
/**
* @param array<array-key, mixed> $arguments The input arguments passed from GraphQL to the field.
*
* @return array<int, object>
*/
public function getObjectsByArguments(
array $arguments,
ResolveInfo|null $info = null,
): array {
return $this->objects[$this->computeHash($arguments, $info)] ?? [];
}
/** @param array<array-key, mixed> $arguments The input arguments passed from GraphQL to the field. */
public function purge(
array $arguments,
ResolveInfo|null $info = null,
): void {
unset($this->objects[$this->computeHash($arguments, $info)]);
}
public function storeResult(
object $source,
mixed $result,
): void {
$this->results->offsetSet($source, $result);
}
public function hasResult(
object $source,
): bool {
return $this->results->offsetExists($source);
}
public function getResult(
object $source,
): mixed {
return $this->results->offsetGet($source);
}
public function purgeResult(
object $source,
): void {
$this->results->offsetUnset($source);
}
}