-
Notifications
You must be signed in to change notification settings - Fork 61
/
SortTrait.php
58 lines (48 loc) · 1.74 KB
/
SortTrait.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
<?php
namespace SilverStripe\GraphQL\Schema\Traits;
use GraphQL\Type\Definition\ResolveInfo;
trait SortTrait
{
private static function getSortArgs(ResolveInfo $info, array $args, string $fieldName): array
{
$sortArgs = [];
$sortOrder = self::getSortOrder($info, $fieldName);
foreach ($sortOrder as $orderName) {
if (!isset($args[$fieldName][$orderName])) {
continue;
}
$sortArgs[$orderName] = $args[$fieldName][$orderName];
unset($args[$fieldName][$orderName]);
}
return array_merge($sortArgs, $args[$fieldName]);
}
/**
* Gets the original order of fields to be sorted based on the query args order.
*
* This is necessary because the underlying GraphQL implementation we're using ignores the
* order of query args, and uses the order that fields are defined in the schema instead.
*/
private static function getSortOrder(ResolveInfo $info, string $fieldName)
{
$relevantNode = $info->fieldDefinition->getName();
// Find the query field node that matches the schema
foreach ($info->fieldNodes as $node) {
if ($node->name->value !== $relevantNode) {
continue;
}
// Find the sort arg
foreach ($node->arguments as $arg) {
if ($arg->name->value !== $fieldName) {
continue;
}
// Get the sort order from the query
$sortOrder = [];
foreach ($arg->value->fields as $field) {
$sortOrder[] = $field->name->value;
}
return $sortOrder;
}
}
return [];
}
}