1
<?php
2

3
namespace Nuwave\Lighthouse\Schema\Directives;
4

5
use Closure;
6
use GraphQL\Type\Definition\ResolveInfo;
7
use Illuminate\Support\Arr;
8
use Nuwave\Lighthouse\Exceptions\DefinitionException;
9
use Nuwave\Lighthouse\Schema\Values\FieldValue;
10
use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware;
11
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
12

13
class InjectDirective extends BaseDirective implements FieldMiddleware
14
{
15 1
    public static function definition(): string
16
    {
17
        return /** @lang GraphQL */ <<<'GRAPHQL'
18 1
"""
19
Inject a value from the context object into the arguments.
20
"""
21
directive @inject(
22
  """
23
  A path to the property of the context that will be injected.
24
  If the value is nested within the context, you may use dot notation
25
  to get it, e.g. "user.id".
26
  """
27
  context: String!
28

29
  """
30
  The target name of the argument into which the value is injected.
31
  You can use dot notation to set the value at arbitrary depth
32
  within the incoming argument.
33
  """
34
  name: String!
35
) repeatable on FIELD_DEFINITION
36
GRAPHQL;
37
    }
38

39
    /**
40
     * @throws \Nuwave\Lighthouse\Exceptions\DefinitionException
41
     */
42 1
    public function handleField(FieldValue $fieldValue, Closure $next): FieldValue
43
    {
44 1
        $contextAttributeName = $this->directiveArgValue('context');
45 1
        if (! $contextAttributeName) {
46 0
            throw new DefinitionException(
47 0
                "The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `context` argument"
48
            );
49
        }
50

51 1
        $argumentName = $this->directiveArgValue('name');
52 1
        if (! $argumentName) {
53 0
            throw new DefinitionException(
54 0
                "The `inject` directive on {$fieldValue->getParentName()} [{$fieldValue->getFieldName()}] must have a `name` argument"
55
            );
56
        }
57

58 1
        $previousResolver = $fieldValue->getResolver();
59

60 1
        return $next(
61 1
            $fieldValue->setResolver(
62
                function ($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo) use ($contextAttributeName, $argumentName, $previousResolver) {
63 1
                    $valueFromContext = data_get($context, $contextAttributeName);
64 1
                    $args = Arr::add($args, $argumentName, $valueFromContext);
65

66 1
                    $resolveInfo->argumentSet->addValue($argumentName, $valueFromContext);
67

68 1
                    return $previousResolver($rootValue, $args, $context, $resolveInfo);
69
                }
70
            )
71
        );
72
    }
73
}

Read our documentation on viewing source code .

Loading