1
<?php
2

3
namespace Nuwave\Lighthouse\Schema\AST;
4

5
use GraphQL\Language\AST\NodeKind;
6
use GraphQL\Language\AST\TypeNode;
7
use Illuminate\Support\Collection;
8

9
abstract class TypeNodeConverter
10
{
11
    /**
12
     * Convert an AST type to an executable type.
13
     *
14
     * @param  \GraphQL\Language\AST\TypeNode&\GraphQL\Language\AST\Node  $node
15
     * @return mixed The executable type.
16
     */
17 1
    public function convert(TypeNode $node)
18
    {
19 1
        return $this->convertWrappedTypeNode($node);
20
    }
21

22
    /**
23
     * Convert an AST type and apply wrapping types.
24
     *
25
     * @param  \GraphQL\Language\AST\TypeNode&\GraphQL\Language\AST\Node  $node
26
     * @param  array<string>  $wrappers
27
     * @return mixed The wrapped type.
28
     */
29 1
    protected function convertWrappedTypeNode(TypeNode $node, array $wrappers = [])
30
    {
31
        // Recursively unwrap the type and save the wrappers
32 1
        $nodeKind = $node->kind;
33 1
        if (in_array($nodeKind, [NodeKind::NON_NULL_TYPE, NodeKind::LIST_TYPE])) {
34
            /** @var \GraphQL\Language\AST\NonNullTypeNode|\GraphQL\Language\AST\ListTypeNode $node */
35 1
            $wrappers[] = $nodeKind;
36

37 1
            return $this->convertWrappedTypeNode(
38 1
                $node->type,
39
                $wrappers
40
            );
41
        }
42
        /** @var \GraphQL\Language\AST\NamedTypeNode $node */
43

44
        // Re-wrap the type by applying the wrappers in the reversed order
45 1
        return (new Collection($wrappers))
46 1
            ->reverse()
47 1
            ->reduce(
48
                function ($type, string $kind) {
49 1
                    if ($kind === NodeKind::NON_NULL_TYPE) {
50 1
                        return $this->nonNull($type);
51
                    }
52

53 1
                    if ($kind === NodeKind::LIST_TYPE) {
54 1
                        return $this->listOf($type);
55
                    }
56

57 0
                    return $type;
58 1
                },
59 1
                $this->namedType($node->name->value)
60
            );
61
    }
62

63
    /**
64
     * Wrap or mark the type as non-null.
65
     *
66
     * @param  mixed  $type The type to wrap.
67
     * @return mixed The type wrapped with non-null.
68
     */
69
    abstract protected function nonNull($type);
70

71
    /**
72
     * Wrap or mark the type as a list.
73
     *
74
     * @param  mixed  $type The type to wrap.
75
     * @return mixed The type wrapped as a list.
76
     */
77
    abstract protected function listOf($type);
78

79
    /**
80
     * Get the named type for the given node name.
81
     *
82
     * @return mixed Representation of the type with the given name.
83
     */
84
    abstract protected function namedType(string $nodeName);
85
}

Read our documentation on viewing source code .

Loading