GeneratorService   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 198
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
eloc 59
c 6
b 0
f 1
dl 0
loc 198
rs 10
wmc 18

10 Methods

Rating   Name   Duplication   Size   Complexity  
A buildResource() 0 6 1
A initialRequest() 0 12 3
A buildRequests() 0 8 1
A runBuildBaseController() 0 5 2
A buildModelAndMigrations() 0 9 2
A generateApi() 0 16 3
A registerCredential() 0 11 1
A setBaseControllerExists() 0 4 1
A buildController() 0 9 3
A runMigration() 0 3 1
1
<?php
2
3
namespace KMLaravel\ApiGenerator\Services;
4
5
6
use Illuminate\Support\Facades\Artisan;
7
use Illuminate\Support\Facades\File;
8
use KMLaravel\ApiGenerator\BuildClasses\KMControllerBuilder;
9
use KMLaravel\ApiGenerator\BuildClasses\KMModelAndMigrationBuilder;
10
use KMLaravel\ApiGenerator\BuildClasses\KMRequestBuilder;
11
use KMLaravel\ApiGenerator\BuildClasses\KMResourcesBuilder;
12
use KMLaravel\ApiGenerator\Facade\KMFileFacade;
13
use KMLaravel\ApiGenerator\Helpers\KMFile;
14
15
class GeneratorService
16
{
17
18
    /**
19
     * @var object
20
     */
21
    private $request;
22
    /**
23
     * @var bool
24
     */
25
    private $baseControllerExists;
26
    /**
27
     * @var array
28
     */
29
    private $basicBuildOption = [];
30
    /**
31
     * @var array
32
     */
33
    private $advancedBuildOption = [];
34
    /**
35
     * @var string
36
     */
37
    private $apiTitle;
38
    /**
39
     * @var array
40
     */
41
    private $column;
42
    /**
43
     * @var array
44
     */
45
    private $paths;
46
47
    /**
48
     * @param $request
49
     * @return GeneratorService
50
     * @desc this function initialize request object which has been validated from controller and assigned all data.
51
     *
52
     */
53
    public function initialRequest($request): GeneratorService
54
    {
55
        [$this->request , $this->column , $this->apiTitle ] = [$request , $request->column , str_replace('\\' , '/' ,$request->title)];
56
        // append all basic options that actor want to run migration  to new array
57
        foreach ($this->request->basic_options as $item => $status) {
58
            $this->basicBuildOption [] = $item;
59
        }
60
        // append all advanced options that actor want to run migration  to new array
61
        foreach ($this->request->advanced_options as $item => $status) {
62
            $this->advancedBuildOption[] = $item;
63
        }
64
        return $this;
65
    }
66
67
    /**
68
     * @return GeneratorService
69
     * this setter function for baseControllerExists property to determine
70
     * if actor choose to run migration  to install base controller before.
71
     */
72
    public function setBaseControllerExists(): GeneratorService
73
    {
74
        $this->baseControllerExists = KMFileFacade::baseControllerExists();
0 ignored issues
show
Documentation Bug introduced by
It seems like KMLaravel\ApiGenerator\F...:baseControllerExists() of type KMLaravel\ApiGenerator\Helpers\KMFile is incompatible with the declared type boolean of property $baseControllerExists.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
75
        return $this;
76
    }
77
78
    /**
79
     * this main function which process is distributed throughout functions available in this current class
80
     * the function is check if this function is exists and this function ame came from actor options to run
81
     * migration which is loaded from api_generator config file.
82
     */
83
    public function generateApi()
84
    {
85
        $this->setBaseControllerExists();
86
        // merge basic options and advanced options.
87
        //we here want to be advanced options last options to run inside foreach.
88
        $options = array_merge($this->basicBuildOption , $this->advancedBuildOption);
89
        foreach ($options as $option) {
90
            if (method_exists(__CLASS__, $option)) {
91
                $this->$option();
92
            }
93
        }
94
        // of course we will build controller as a last step
95
        // because now we have all paths we need
96
        $this->buildController();
97
        // at the end we will register some data to credential file in assets
98
        $this->registerCredential();
99
    }
100
101
    /**
102
     * @return KMFile
103
     * this function is use separate class its work like a services to auto build model and check from
104
     * migration options and finally push the path for model to paths property to use it when we create
105
     * controller as final step.
106
     */
107
    protected function buildModelAndMigrations()
108
    {
109
        $builder = new KMModelAndMigrationBuilder();
110
        $modelClass = "$this->apiTitle";
111
        $migrationRequired = in_array("buildMigration" , $this->basicBuildOption) ? "-m" : "";
112
        $builder->initialResource($modelClass, "modelAndMigrationReplacer")
113
            ->callArtisan($migrationRequired)
114
            ->build($this->column, ["migrationRequired" => $migrationRequired]);
115
        return $this->paths["{{ model_path }}"] = KMFileFacade::getClassNameSpace("model", $modelClass);
116
    }
117
118
    /**
119
     *
120
     */
121
    protected function runBuildBaseController()
122
    {
123
        if (!$this->baseControllerExists) {
124
            file_put_contents(KMFileFacade::baseControllerPath(),
0 ignored issues
show
Bug introduced by
KMLaravel\ApiGenerator\F...e::baseControllerPath() of type KMLaravel\ApiGenerator\Helpers\KMFile is incompatible with the type string expected by parameter $filename of file_put_contents(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

124
            file_put_contents(/** @scrutinizer ignore-type */ KMFileFacade::baseControllerPath(),
Loading history...
125
                File::get(KMFileFacade::getFilesFromStubs("BaseController"))
0 ignored issues
show
Unused Code introduced by
The call to KMLaravel\ApiGenerator\F...de::getFilesFromStubs() has too many arguments starting with 'BaseController'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
                File::get(KMFileFacade::/** @scrutinizer ignore-call */ getFilesFromStubs("BaseController"))

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
126
            );
127
        }
128
    }
129
130
    /**
131
     * if actor choose to run migration.
132
     * **************************************
133
     * we will update options in next release
134
     * **************************************
135
     * @param string $options
136
     * @return int
137
     */
138
    protected function runMigration($options = "")
139
    {
140
        return Artisan::call("migrate $options");
141
    }
142
143
    /**
144
     * @return KMFile
145
     * this function is used KMRequestBuilder separate class its work like a services to auto build request and
146
     * put the rule which actor is selected and finally push the path for model to paths property to use it when
147
     * we create controller as final step.
148
     */
149
    protected function buildRequests()
150
    {
151
        $builder = new KMRequestBuilder();
152
        $requestClass = "$this->apiTitle" . "Request";
153
        $builder->initialResource($requestClass, "requestReplacer")
154
            ->callArtisan()
155
            ->build($this->column);
156
        return $this->paths["{{ request_path }}"] = KMFileFacade::getClassNameSpace("Requests", $requestClass);
157
    }
158
159
    /**
160
     * @return mixed
161
     * here we build controller ads final step in building process
162
     * the idea is take all paths that resulted from the previous process ( request ,  model , migrations ..)
163
     * and its addition to controller path , and then choose  controllerReplacer function to replaces the
164
     * resource in controller.stub file and append it to controllers folder.
165
     * *******************************************************
166
     * we will update option to make actor use if he will used
167
     * our controller or choose to build custom controller
168
     * *******************************************************
169
     */
170
    protected function buildController()
171
    {
172
        $builder = new KMControllerBuilder();
173
        $controllerClass = "$this->apiTitle" . "Controller";
174
        $controllerBuildType = !$this->baseControllerExists || $this->paths == null ? "basicBuild" : "build";
175
        return $builder->initialResource($controllerClass, "controllerReplacer")
176
            ->callArtisan()
177
            ->$controllerBuildType($this->column, array_merge($this->paths ?? [], [
178
                "{{ controller_path }}" => KMFileFacade::getClassNameSpace("Controller", $controllerClass),
179
            ]));
180
    }
181
182
    /**
183
     * this auto generate resources file which is use standard laravel resources file
184
     * and get the path do this resource and push them to paths array
185
     */
186
    protected function buildResource()
187
    {
188
        $builder = new KMResourcesBuilder();
189
        $resourceClass = "$this->apiTitle" . "Resource";
190
        $builder->callArtisan($resourceClass);
191
        return $this->paths["{{ resource_path }}"] = KMFileFacade::getClassNameSpace("Resources", "$this->apiTitle" . "Resource");
192
    }
193
194
    /**
195
     * @return KMFile
196
     * in this function we can register some information about our process result
197
     * like controller name , url ( will be api title as default ) , and title for this api.
198
     * *******************************
199
     * we will add more flexibility to routing process
200
     * *******************************
201
     */
202
    protected function registerCredential()
203
    {
204
        $data = [
205
            "title" => $this->apiTitle,
206
            "controller" => "$this->apiTitle" . "Controller",
207
            "url" => "$this->apiTitle",
208
            "name" => "$this->apiTitle",
209
            "type" => "resource",
210
            "date" => date('l jS \of F Y h:i:s A'),
211
        ];
212
        return KMFileFacade::setDataToCredentialJsonFile($data);
213
    }
214
}
215