-
-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathInjectDirective.php
More file actions
74 lines (63 loc) · 2.48 KB
/
InjectDirective.php
File metadata and controls
74 lines (63 loc) · 2.48 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
<?php
namespace Nuwave\Lighthouse\Schema\Directives;
use Nuwave\Lighthouse\Exceptions\DefinitionException;
use Nuwave\Lighthouse\Execution\ResolveInfo;
use Nuwave\Lighthouse\Schema\Values\FieldValue;
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
class InjectDirective extends BaseDirective implements FieldMiddleware
{
public static function definition(): string
{
return /** @lang GraphQL */ <<<'GRAPHQL'
"""
Inject a value from the context object into the arguments.
"""
directive @inject(
"""
A path to the property of the context that will be injected.
If the value is nested within the context, you may use dot notation
to get it, e.g. "user.id".
"""
context: String!
"""
The target name of the argument into which the value is injected.
You can use dot notation to set the value at arbitrary depth
within the incoming argument.
Use an asterisk `*` as a path segment where the value of the argument is a list to be traversed.
"""
name: String!
) repeatable on FIELD_DEFINITION
GRAPHQL;
}
/**
* @throws \Nuwave\Lighthouse\Exceptions\DefinitionException
*/
public function handleField(FieldValue $fieldValue, \Closure $next): FieldValue
{
$contextAttributeName = $this->directiveArgValue('context');
if (! $contextAttributeName) {
throw new DefinitionException(
"The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `context` argument"
);
}
$argumentName = $this->directiveArgValue('name');
if (! $argumentName) {
throw new DefinitionException(
"The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `name` argument"
);
}
$previousResolver = $fieldValue->getResolver();
$fieldValue->setResolver(function ($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($contextAttributeName, $argumentName, $previousResolver) {
$valueFromContext = data_get($context, $contextAttributeName);
$resolveInfo->argumentSet->addValue($argumentName, $valueFromContext);
return $previousResolver(
$rootValue,
$resolveInfo->argumentSet->toArray(),
$context,
$resolveInfo
);
});
return $next($fieldValue);
}
}