-
-
Notifications
You must be signed in to change notification settings - Fork 469
Expand file tree
/
Copy pathOrderByDirective.php
More file actions
280 lines (232 loc) · 10.1 KB
/
Copy pathOrderByDirective.php
File metadata and controls
280 lines (232 loc) · 10.1 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
<?php declare(strict_types=1);
namespace Nuwave\Lighthouse\OrderBy;
use GraphQL\Language\AST\FieldDefinitionNode;
use GraphQL\Language\AST\InputValueDefinitionNode;
use GraphQL\Language\AST\InterfaceTypeDefinitionNode;
use GraphQL\Language\AST\ObjectTypeDefinitionNode;
use GraphQL\Language\Parser;
use Illuminate\Contracts\Database\Query\Builder;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Nuwave\Lighthouse\Exceptions\DefinitionException;
use Nuwave\Lighthouse\Execution\ResolveInfo;
use Nuwave\Lighthouse\Schema\AST\ASTHelper;
use Nuwave\Lighthouse\Schema\AST\DocumentAST;
use Nuwave\Lighthouse\Schema\Directives\BaseDirective;
use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective;
use Nuwave\Lighthouse\Support\Contracts\ArgDirectiveForArray;
use Nuwave\Lighthouse\Support\Contracts\ArgManipulator;
use Nuwave\Lighthouse\Support\Contracts\FieldBuilderDirective;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
use Nuwave\Lighthouse\Support\Traits\GeneratesColumnsEnum;
class OrderByDirective extends BaseDirective implements ArgBuilderDirective, ArgDirectiveForArray, ArgManipulator, FieldBuilderDirective
{
use GeneratesColumnsEnum;
public static function definition(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
Sort a result list by one or more given columns.
"""
directive @orderBy(
"""
Restrict the allowed column names to a well-defined list.
This improves introspection capabilities and security.
Mutually exclusive with `columnsEnum`.
Only used when the directive is added on an argument.
"""
columns: [String!]
"""
Use an existing enumeration type to restrict the allowed columns to a predefined list.
This allows you to re-use the same enum for multiple fields.
Mutually exclusive with `columns`.
Only used when the directive is added on an argument.
"""
columnsEnum: String
"""
Allow clients to sort by aggregates on relations.
Only used when the directive is added on an argument.
"""
relations: [OrderByRelation!]
"""
The database column for which the order by clause will be applied on.
Only used when the directive is added on a field.
"""
column: String
"""
The direction of the order by clause.
Only used when the directive is added on a field.
"""
direction: OrderByDirection = ASC
) on ARGUMENT_DEFINITION | FIELD_DEFINITION
"""
Options for the `direction` argument of `@orderBy`.
"""
enum OrderByDirection {
"""
Sort in ascending order.
"""
ASC
"""
Sort in descending order.
"""
DESC
}
"""
Options for the `relations` argument of `@orderBy`.
"""
input OrderByRelation {
"""
Name of the relation.
"""
relation: String!
"""
Restrict the allowed column names to a well-defined list.
This improves introspection capabilities and security.
Mutually exclusive with `columnsEnum`.
"""
columns: [String!]
"""
Use an existing enumeration type to restrict the allowed columns to a predefined list.
This allows you to re-use the same enum for multiple fields.
Mutually exclusive with `columns`.
"""
columnsEnum: String
}
GRAPHQL;
}
/** @param array<array<string, mixed>> $value */
public function handleBuilder(Builder $builder, $value): Builder
{
foreach ($value as $orderByClause) {
$order = Arr::pull($orderByClause, 'order');
$column = Arr::pull($orderByClause, 'column');
if ($column === null) {
if (! $builder instanceof EloquentBuilder) {
$notEloquentBuilder = $builder::class;
throw new DefinitionException("Can not order by relations on non-Eloquent builders, got: {$notEloquentBuilder}.");
}
$relation = array_key_first($orderByClause);
assert(is_string($relation));
$relationSnake = Str::snake($relation);
$relationValues = Arr::first($orderByClause);
$aggregate = $relationValues['aggregate'];
if ($aggregate === 'count') {
$builder->withCount($relation);
$column = "{$relationSnake}_count";
} else {
$upperAggregate = ucfirst($aggregate);
$operator = "with{$upperAggregate}";
$relationColumn = $relationValues['column'];
$builder->{$operator}($relation, $relationColumn);
$column = "{$relationSnake}_{$aggregate}_{$relationColumn}";
}
}
$builder->orderBy($column, $order);
}
return $builder;
}
public function manipulateArgDefinition(
DocumentAST &$documentAST,
InputValueDefinitionNode &$argDefinition,
FieldDefinitionNode &$parentField,
ObjectTypeDefinitionNode|InterfaceTypeDefinitionNode &$parentType,
): void {
$this->validateMutuallyExclusiveArguments(['columns', 'columnsEnum']);
if (! $this->hasAllowedColumns() && ! $this->directiveHasArgument('relations')) {
$argDefinition->type = Parser::typeReference('[' . OrderByServiceProvider::DEFAULT_ORDER_BY_CLAUSE . '!]');
return;
}
$qualifiedOrderByPrefix = ASTHelper::qualifiedArgType($argDefinition, $parentField, $parentType);
$allowedColumnsTypeName = $this->hasAllowedColumns()
? $this->generateColumnsEnum($documentAST, $argDefinition, $parentField, $parentType)
: 'String';
if ($this->directiveHasArgument('relations')) {
/** @var array<string, string> $relationsInputs */
$relationsInputs = [];
foreach ($this->directiveArgValue('relations') as $relation) {
$relationName = $relation['relation'];
$relationUpper = ucfirst($relationName);
$inputName = $qualifiedOrderByPrefix . $relationUpper;
$relationsInputs[$relationName] = $inputName;
$columns = $relation['columns'] ?? null;
if ($columns !== null) {
$allowedRelationColumnsEnumName = "{$qualifiedOrderByPrefix}{$relationUpper}Column";
$documentAST->setTypeDefinition(
$this->createAllowedColumnsEnum(
$argDefinition,
$parentField,
$parentType,
$columns,
$allowedRelationColumnsEnumName,
),
);
$documentAST->setTypeDefinition(
OrderByServiceProvider::createRelationAggregateFunctionForColumnInput(
$inputName,
"Aggregate specification for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.{$relationName}.",
$allowedRelationColumnsEnumName,
),
);
} else {
$documentAST->setTypeDefinition(
OrderByServiceProvider::createRelationAggregateFunctionInput(
$inputName,
"Aggregate specification for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.{$relationName}.",
),
);
}
}
$qualifiedRelationOrderByName = "{$qualifiedOrderByPrefix}RelationOrderByClause";
/** @var array<int, string> $relationNames */
$relationNames = array_keys($relationsInputs);
$inputMerged = <<<GRAPHQL
"Order by clause for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}."
input {$qualifiedRelationOrderByName} {
"The column that is used for ordering."
column: {$allowedColumnsTypeName} {$this->mutuallyExclusiveRule($relationNames)}
"The direction that is used for ordering."
order: SortOrder!
GRAPHQL;
foreach ($relationsInputs as $relation => $input) {
/** @var array<int, string> $otherOptions */
$otherOptions = ['column'];
foreach ($relationNames as $relationName) {
if ($relationName !== $relation) {
$otherOptions[] = $relationName;
}
}
$inputMerged .= <<<GRAPHQL
"Aggregate specification."
{$relation}: {$input} {$this->mutuallyExclusiveRule($otherOptions)}
GRAPHQL;
}
$argDefinition->type = Parser::typeReference("[{$qualifiedRelationOrderByName}!]");
$documentAST->setTypeDefinition(Parser::inputObjectTypeDefinition("{$inputMerged}}"));
} else {
$restrictedOrderByName = "{$qualifiedOrderByPrefix}OrderByClause";
$argDefinition->type = Parser::typeReference("[{$restrictedOrderByName}!]");
$documentAST->setTypeDefinition(
OrderByServiceProvider::createOrderByClauseInput(
$restrictedOrderByName,
"Order by clause for {$parentType->name->value}.{$parentField->name->value}.{$argDefinition->name->value}.",
$allowedColumnsTypeName,
),
);
}
}
public function handleFieldBuilder(Builder $builder, mixed $root, array $args, GraphQLContext $context, ResolveInfo $resolveInfo): Builder
{
return $builder->orderBy(
$this->directiveArgValue('column'),
$this->directiveArgValue('direction', 'ASC'),
);
}
/** @param array<string> $otherOptions */
protected function mutuallyExclusiveRule(array $otherOptions): string
{
$optionsString = implode(',', $otherOptions);
return "@rules(apply: [\"prohibits:{$optionsString}\"])";
}
}