1
<?php
2

3
namespace Nuwave\Lighthouse\Schema\Directives;
4

5
use Nuwave\Lighthouse\Schema\Values\FieldValue;
6
use Nuwave\Lighthouse\Support\Contracts\FieldResolver;
7

8
class MethodDirective extends BaseDirective implements FieldResolver
9
{
10
    /** @var \GraphQL\Language\AST\FieldDefinitionNode */
11
    protected $definitionNode;
12

13 1
    public static function definition(): string
14
    {
15
        return /** @lang GraphQL */ <<<'GRAPHQL'
16 1
"""
17
Resolve a field by calling a method on the parent object.
18

19
Use this if the data is not accessible through simple property access or if you
20
want to pass argument to the method.
21
"""
22
directive @method(
23
  """
24
  Specify the method of which to fetch the data from.
25
  Defaults to the name of the field if not given.
26
  """
27
  name: String
28
) on FIELD_DEFINITION
29
GRAPHQL;
30
    }
31

32 1
    public function resolveField(FieldValue $fieldValue): FieldValue
33
    {
34 1
        return $fieldValue->setResolver(
35
            /**
36
             * @param  array<string, mixed>  $args
37
             * @return mixed Really anything
38
             */
39
            function ($root, array $args) {
40
                /** @var string $method */
41 1
                $method = $this->directiveArgValue(
42 1
                    'name',
43 1
                    $this->nodeName()
44
                );
45

46 1
                $orderedArgs = [];
47 1
                foreach ($this->definitionNode->arguments as $argDefinition) {
48 1
                    $orderedArgs [] = $args[$argDefinition->name->value] ?? null;
49
                }
50

51 1
                return $root->{$method}(...$orderedArgs);
52
            }
53
        );
54
    }
55
}

Read our documentation on viewing source code .

Loading