Passed
Push — master ( 561d20...1650db )
by Richard
03:56 queued 11s
created

GraphQLMutationGenerator::generateSchema()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 18
rs 9.6111
cc 5
nc 5
nop 0
1
<?php
2
3
namespace PWWEB\Artomator\Generators\GraphQL;
4
5
use Illuminate\Support\Str;
6
use InfyOm\Generator\Generators\BaseGenerator;
7
use PWWEB\Artomator\Common\CommandData;
8
9
class GraphQLMutationGenerator extends BaseGenerator
10
{
11
    /**
12
     * @var CommandData
13
     */
14
    private $commandData;
15
16
    /**
17
     * @var string
18
     */
19
    private $fileName;
20
21
    /**
22
     * @var string
23
     */
24
    private $fileContents;
25
26
    /**
27
     * @var string
28
     */
29
    private $templateData;
30
31
    public function __construct(CommandData $commandData)
32
    {
33
        $this->commandData = $commandData;
34
        $this->fileName = $commandData->config->pathGraphQL;
35
        $this->fileContents = file_get_contents($this->fileName);
36
        $this->templateData = get_artomator_template('graphql.mutations');
37
        $this->templateData = fill_template($this->commandData->dynamicVars, $this->templateData);
38
    }
39
40
    public function generate()
41
    {
42
        if (true === Str::contains($this->fileContents, $this->templateData)) {
43
            $this->commandData->commandObj->info('GraphQL Mutations '.$this->commandData->config->mHumanPlural.' already exist; Skipping');
44
45
            return;
46
        }
47
48
        if (false === str::contains($this->fileContents, 'type Mutation {')) {
49
            $this->fileContents = preg_replace('/(type Query {)(.+?[^}])(})/is', '$1$2$3'."\n\ntype Mutation {  }", $this->fileContents);
50
        }
51
52
        $this->fileContents = preg_replace('/(type Mutation {)(.+?[^}])(})/is', '$1$2'.str_replace('\\', '\\\\', $this->templateData).'$3', $this->fileContents);
53
54
        file_put_contents($this->fileName, $this->fileContents);
55
56
        $this->commandData->commandComment("\nGraphQL Mutations created");
57
    }
58
59
    public function rollback()
60
    {
61
        $strings = [
62
            'create',
63
            'update',
64
            'delete',
65
        ];
66
        $model = $this->commandData->config->gHuman;
67
68
        foreach ($strings as $string) {
69
            if (Str::contains($this->fileContents, $string.$model)) {
70
                $this->fileContents = preg_replace('/(\s)+('.$string.$model.'\()(.+?)(\):.+?)(\))/is', '', $this->fileContents);
71
72
                file_put_contents($this->fileName, $this->fileContents);
73
                $this->commandData->commandComment('GraphQL '.ucfirst($string).' Mutation deleted');
74
            }
75
        }
76
    }
77
}
78