-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphqlQuery.php
More file actions
100 lines (82 loc) · 2.5 KB
/
GraphqlQuery.php
File metadata and controls
100 lines (82 loc) · 2.5 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
99
100
<?php
declare(strict_types=1);
namespace GraphqlOrm\Query;
use GraphqlOrm\Exception\InvalidGraphqlResponseException;
use GraphqlOrm\GraphqlManager;
use GraphqlOrm\Query\Ast\QueryNode;
/**
* @template T of object
*/
final readonly class GraphqlQuery
{
/**
* @param class-string<T> $entityClass
* @param GraphqlManager<T> $manager
*/
public function __construct(
private QueryNode|string $graphql,
private string $entityClass,
private GraphqlManager $manager,
) {
}
public function getGraphQL(): string
{
if ($this->graphql instanceof QueryNode) {
return $this->manager->getQueryCompiler()->compile($this->graphql);
}
return $this->graphql;
}
/**
* @return T[]
*/
public function getResult(): array
{
$metadata = $this
->manager
->metadataFactory
->getMetadata($this->entityClass);
return $this
->manager
->execute($this->graphql, hydration: function ($result, $context) use ($metadata) {
$dialect = $this->manager->getDialect();
$data = $result['data'] ?? [];
if (!\array_key_exists($metadata->name, $data)) {
return [];
}
$root = $data[$metadata->name];
if ($root === null) {
return [];
}
if (!\is_array($root)) {
throw InvalidGraphqlResponseException::expectedArray($root);
}
$collection = $dialect->extractCollection($root);
$rows = !empty($collection) ? $collection : null;
if ($rows === null) {
return [];
}
if (!\is_array($rows)) {
throw InvalidGraphqlResponseException::expectedArray($rows);
}
if (array_is_list($rows) === false) {
$rows = [$rows];
}
return array_map(fn ($row) => $this->manager
->hydrator
->hydrate(
$metadata,
$row,
$context
),
$rows
);
});
}
/**
* @return T|null
*/
public function getOneOrNullResult(): ?object
{
return $this->getResult()[0] ?? null;
}
}