CreateMutationGenerator::generate()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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