FindQueryGenerator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 17
dl 0
loc 39
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A generate() 0 30 5
1
<?php
2
3
namespace DeInternetJongens\LighthouseUtils\Generators\Queries;
4
5
use DeInternetJongens\LighthouseUtils\Models\GraphQLSchema;
6
use GraphQL\Type\Definition\IDType;
7
use GraphQL\Type\Definition\Type;
8
9
class FindQueryGenerator
10
{
11
    /**
12
     * Generates a GraphQL query that returns one entity by ID
13
     *
14
     * @param string $typeName
15
     * @param Type[] $typeFields
16
     * @return string
17
     */
18
    public static function generate(string $typeName, array $typeFields): string
19
    {
20
        $arguments = [];
21
22
        //Loop through fields to find the 'ID' field.
23
        foreach ($typeFields as $fieldName => $field) {
24
            if (false === ($field instanceof IDType)) {
25
                continue;
26
            }
27
28
            $arguments[] = sprintf('%s: %s! @eq', $fieldName, $field->name);
29
            break;
30
        }
31
32
        if (count($arguments) < 1) {
33
            return '';
34
        }
35
36
        $queryName = lcfirst($typeName);
37
        $query = sprintf('    %s(%s)', $queryName, implode(', ', $arguments));
38
        $query .= sprintf(': %1$s @find(model: "%1$s")', $typeName);
39
40
        if (config('lighthouse-utils.authorization')) {
41
            $permission = sprintf('find%1$s', $typeName);
42
            $query .= sprintf(' @can(if: "%1$s", model: "User")', $permission);
43
        }
44
45
        GraphQLSchema::register($queryName, $typeName, 'query', $permission ?? null);
46
47
        return $query;
48
    }
49
}
50