-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphqlDataProvider.php
98 lines (81 loc) · 2.53 KB
/
GraphqlDataProvider.php
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
namespace amin3mej\graphql;
use Yii;
use yii\base\InvalidConfigException;
use yii\data\BaseDataProvider;
use yii\di\Instance;
use yii\helpers\ArrayHelper;
class GraphqlDataProvider extends BaseDataProvider
{
/**
* @var string the GraphQL query that is used to fetch data models
*/
public $query;
/**
* @var string the address for access data in GraphQL response
*/
public $queryCallback;
/**
* @var string the GraphQL query that is used to fetch [[totalCount]]
*/
public $totalCountQuery;
/**
* @var string|null the key for defaultTarget array or if its null, defaultTarget will be used.
*/
public $target;
/**
* @var GraphqlQuery
*/
public $graphqlQuery;
public function init()
{
if ($this->graphqlQuery !== NULL) {
$this->graphqlQuery = Instance::ensure($this->graphqlQuery, GraphqlQuery::className());
} elseif (isset(Yii::$app->graphql)) {
$this->graphqlQuery = Yii::$app->graphql;
} else {
throw new InvalidConfigException('GraphqlDataProvider::graphqlQuery or Config::graphql must be set.');
}
}
/**
* {@inheritdoc}
*/
protected function prepareModels()
{
if (!$this->query) {
throw new InvalidConfigException('The "query" property must be set.');
}
$variables = [];
if (($pagination = $this->getPagination()) !== false) {
$pagination->totalCount = $this->getTotalCount();
if ($pagination->totalCount === 0) {
return [];
}
$variables['limit'] = $pagination->getLimit();
$variables['offset'] = $pagination->getOffset();
}
//@TODO: sort must be implemented.
$response = $this->graphqlQuery->execute($this->query, $variables, $this->target);
return ArrayHelper::getValue($response, $this->queryCallback);
}
/**
* {@inheritdoc}
*/
protected function prepareKeys($models)
{
return array_keys($models);
}
/**
* {@inheritdoc}
*/
protected function prepareTotalCount()
{
if (!$this->totalCountQuery) {
throw new InvalidConfigException('The "totalCountQuery" property must be set.');
}
$response = $this->graphqlQuery->execute($this->totalCountQuery, [], $this->target);
$return = [];
array_walk_recursive($response, function($a) use (&$return) { $return[] = $a; });
return $return[0];
}
}