UpdateMutationGenerator::generate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
c 1
b 0
f 0
dl 0
loc 22
rs 9.8333
cc 3
nc 3
nop 2
1
<?php
2
3
namespace DeInternetJongens\LighthouseUtils\Generators\Mutations;
4
5
use DeInternetJongens\LighthouseUtils\Generators\Arguments\IdArgumentGenerator;
6
use DeInternetJongens\LighthouseUtils\Generators\Arguments\InputFieldsArgumentGenerator;
7
use DeInternetJongens\LighthouseUtils\Generators\Arguments\RelationArgumentGenerator;
8
use DeInternetJongens\LighthouseUtils\Models\GraphQLSchema;
9
use GraphQL\Type\Definition\Type;
10
11
class UpdateMutationGenerator
12
{
13
    /**
14
     * Generates a GraphQL Mutation to update a record
15
     *
16
     * @param string $typeName
17
     * @param Type[] $typeFields
18
     * @return string
19
     */
20
    public static function generate(string $typeName, array $typeFields): string
21
    {
22
        $mutationName = 'update' . $typeName;
23
        $arguments = IdArgumentGenerator::generate($typeFields);
24
        $arguments = array_merge($arguments, RelationArgumentGenerator::generate($typeFields));
25
        $arguments = array_merge($arguments, InputFieldsArgumentGenerator::generate($typeFields));
26
27
        if (count($arguments) < 1) {
28
            return '';
29
        }
30
31
        $mutation = sprintf('    %s(%s)', $mutationName, implode(', ', $arguments));
32
        $mutation .= sprintf(': %1$s @update(model: "%1$s")', $typeName);
33
34
        if (config('lighthouse-utils.authorization')) {
35
            $permission = sprintf('update%1$s', $typeName);
36
            $mutation .= sprintf(' @can(if: "%1$s", model: "User")', $permission);
37
        }
38
39
        GraphQLSchema::register($mutationName, $typeName, 'mutation', $permission ?? null);
40
41
        return $mutation;
42
    }
43
}
44