Passed
Push — master ( c7bef9...d094e5 )
by Iman
04:30
created

AdminApiGeneratorController::prepareResults()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 2
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace crocodicstudio\crudbooster\Modules\ApiGeneratorModule;
4
5
use crocodicstudio\crudbooster\controllers\CBController;
6
use crocodicstudio\crudbooster\Modules\ModuleGenerator\ControllerGenerator\FieldDetector;
7
use Illuminate\Support\Facades\Request;
8
use Illuminate\Support\Facades\DB;
9
use Illuminate\Support\Facades\Route;
10
use crocodicstudio\crudbooster\helpers\CRUDBooster;
11
12
class AdminApiGeneratorController extends CBController
13
{
14
    public function cbInit()
15
    {
16
        $this->table = 'cms_apicustom';
17
        $this->primaryKey = "id";
18
        $this->title_field = "nama";
19
        $this->button_show = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_show does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
20
        $this->button_new = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_new does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
21
        $this->deleteBtn = false;
22
        $this->button_add = false;
0 ignored issues
show
Bug Best Practice introduced by
The property button_add does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
23
        $this->button_import = false;
24
        $this->buttonExport = false;
25
    }
26
27
    public function getIndex()
28
    {
29
        $this->cbLoader();
30
31
        $data = [];
32
33
        $data['page_title'] = 'API Generator';
34
        $data['apis'] = $this->table()->orderby('nama', 'asc')->get();
35
36
        return view('CbApiGen::api_documentation', $data);
37
    }
38
39
    public function apiDocumentation()
40
    {
41
        $this->cbLoader();
42
        $data = [];
43
44
        $data['apis'] = $this->table()->orderby('nama', 'asc')->get();
45
46
        return view('CbApiGen::api_documentation_public', $data);
47
    }
48
49
    public function getDownloadPostman()
50
    {
51
        $this->cbLoader();
52
        $data = [];
53
        $data['variables'] = [];
54
        $data['info'] = [
55
            'name' => cbGetsetting('appname').' - API',
56
            '_postman_id' => "1765dd11-73d1-2978-ae11-36921dc6263d",
57
            'description' => '',
58
            'schema' => 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json',
59
        ];
60
        $items = [];
61
        foreach ($this->table()->orderby('nama', 'asc')->get() as $api) {
62
            $parameters = unserialize($api->parameters);
63
            $formdata = [];
64
            $httpbuilder = [];
65
            if ($parameters) {
66
                foreach ($parameters as $p) {
67
                    $enabled = ($p['used'] == 0) ? false : true;
68
                    $name = $p['name'];
69
                    $httpbuilder[$name] = '';
70
                    if ($enabled) {
71
                        $formdata[] = ['key' => $name, 'value' => '', 'type' => 'text', 'enabled' => $enabled];
72
                    }
73
                }
74
            }
75
76
            if (strtolower($api->method_type) == 'get' && $httpbuilder) {
77
                $httpbuilder = "?".http_build_query($httpbuilder);
78
            } else {
79
                $httpbuilder = '';
80
            }
81
82
            $items[] = [
83
                'name' => $api->nama,
84
                'request' => [
85
                    'url' => url('api/'.$api->permalink).$httpbuilder,
86
                    'method' => $api->method_type ?: 'GET',
87
                    'header' => [],
88
                    'body' => [
89
                        'mode' => 'formdata',
90
                        'formdata' => $formdata,
91
                    ],
92
                    'description' => $api->keterangan,
93
                ],
94
            ];
95
        }
96
        $data['item'] = $items;
97
98
        $json = json_encode($data);
99
100
        return \Response::make($json, 200, [
101
            'Content-Type' => 'application/json',
102
            'Content-Disposition' => 'attachment; filename='.cbGetsetting('appname').' - API For POSTMAN.json',
103
        ]);
104
    }
105
106
    public function getGenerator()
107
    {
108
        $this->cbLoader();
109
110
        $data['page_title'] = 'API Generator';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
111
        $data['tables'] = CRUDBooster::listCbTables();
112
113
        return view('CbApiGen::api_generator', $data);
114
    }
115
116
    public function getEditApi($id)
117
    {
118
        $this->cbLoader();
119
120
        $row = $this->findRow($id)->first();
121
122
        $data['row'] = $row;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
123
        $data['parameters'] = json_encode(unserialize($row->parameters));
124
        $data['responses'] = json_encode(unserialize($row->responses));
125
        $data['page_title'] = 'API Generator';
126
127
        $data['tables'] = CRUDBooster::listCbTables();
128
129
        return view('CbApiGen::api_generator', $data);
130
    }
131
132
    public function getColumnTable($table, $type = 'list')
133
    {
134
        $this->cbLoader();
135
        $except = ['created_at', 'deleted_at', 'updated_at'];
136
137
        $result = \Schema::getColumnListing($table);
138
        $newResult = [];
139
        foreach ($result as $row) {
140
141
            if (in_array($row, $except)) {
142
                continue;
143
            }
144
            $type_field = \Schema::getColumnType($table, $row);
145
            $newResult[] = ['name' => $row, 'type' => $this->getFieldType($row, $type_field)];
146
147
            if (! in_array($type, ['list', 'detail']) || ! starts_with($row, 'id_')) {
148
                continue;
149
            }
150
151
            $newResult = $this->prepareResults($row, $newResult);
152
        }
153
154
        return response()->json($newResult);
0 ignored issues
show
Bug introduced by
The method json() does not exist on Symfony\Component\HttpFoundation\Response. It seems like you code against a sub-type of Symfony\Component\HttpFoundation\Response such as Illuminate\Http\Response or Illuminate\Http\JsonResponse or Illuminate\Http\RedirectResponse. ( Ignorable by Annotation )

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

154
        return response()->/** @scrutinizer ignore-call */ json($newResult);
Loading history...
155
    }
156
157
    public function postSaveApiCustom()
158
    {
159
        $this->cbLoader();
160
        $posts = request()->all();
161
162
        $_data = [];
163
164
        $_data['nama'] = g('nama');
165
        $_data['tabel'] = $posts['tabel'];
166
        $_data['aksi'] = $posts['aksi'];
167
        $_data['permalink'] = g('permalink');
168
        $_data['method_type'] = g('method_type');
169
170
        $json = $this->json(g('params_name'), g('params_type'), g('params_config'), g('params_required'), g('params_used'));
0 ignored issues
show
Bug introduced by
The call to crocodicstudio\crudboost...ratorController::json() has too few arguments starting with json. ( Ignorable by Annotation )

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

170
        /** @scrutinizer ignore-call */ 
171
        $json = $this->json(g('params_name'), g('params_type'), g('params_config'), g('params_required'), g('params_used'));

This check compares calls to functions or methods with their respective definitions. If the call has less 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...
171
172
        $_data['parameters'] = serialize(array_filter($json));
173
174
        $_data['sql_where'] = g('sql_where');
175
176
        $json = $this->json2(g('responses_name'), g('responses_type'), g('responses_subquery'), g('responses_used'));
177
        $json = array_filter($json);
178
        $_data['responses'] = serialize($json);
179
        $_data['keterangan'] = g('keterangan');
180
181
        $this->saveToDB($_data);
182
183
        return redirect(CRUDBooster::mainpath())->with(['message' => 'Yeay, your api has been saved successfully !', 'message_type' => 'success']);
184
    }
185
186
    public function getDeleteApi($id)
187
    {
188
        $this->cbLoader();
189
        $row = $this->findRow($id)->first();
190
        $this->findRow($id)->delete();
191
192
        $controllername = ucwords(str_replace('_', ' ', $row->permalink));
193
        $controllername = str_replace(' ', '', $controllername);
194
        @unlink((controllers_dir()."Api".$controllername."Controller.php"));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

194
        /** @scrutinizer ignore-unhandled */ @unlink((controllers_dir()."Api".$controllername."Controller.php"));

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
195
196
        return response()->json(['status' => 1]);
197
    }
198
199
    /**
200
     * @param $params_name
201
     * @param $params_type
202
     * @param $params_config
203
     * @param $params_required
204
     * @param $params_used
205
     * @param $json
206
     * @return array
207
     */
208
    private function json($params_name, $params_type, $params_config, $params_required, $params_used, $json)
209
    {
210
        $json = [];
211
        for ($i = 0, $_count = count($params_name); $i <= $_count; $i++) {
212
            if (! $params_name[$i]) {
213
                continue;
214
            }
215
            $json[] = [
216
                'name' => $params_name[$i],
217
                'type' => $params_type[$i],
218
                'config' => $params_config[$i],
219
                'required' => $params_required[$i],
220
                'used' => $params_used[$i],
221
            ];
222
        }
223
224
        return $json;
225
    }
226
227
    /**
228
     * @param $responses_name
229
     * @param $responses_type
230
     * @param $responses_subquery
231
     * @param $responses_used
232
     * @return array
233
     */
234
    private function json2($responses_name, $responses_type, $responses_subquery, $responses_used)
235
    {
236
        $json = [];
237
        for ($i = 0, $_count = count($responses_name); $i <= $_count; $i++) {
238
            if (! $responses_name[$i]) {
239
                continue;
240
            }
241
            $json[] = [
242
                'name' => $responses_name[$i],
243
                'type' => $responses_type[$i],
244
                'subquery' => $responses_subquery[$i],
245
                'used' => $responses_used[$i],
246
            ];
247
        }
248
249
        return $json;
250
    }
251
252
    /**
253
     * @param $a
254
     */
255
    private function saveToDB($a)
256
    {
257
        if (request('id')) {
258
            return $this->findRow(g('id'))->update($a);
259
        }
260
261
        $controllerName = ucwords(str_replace('_', ' ', $a['permalink']));
262
        $controllerName = str_replace(' ', '', $controllerName);
263
        $this->generateAPI($controllerName, $a['tabel'], $a['permalink'], $a['method_type']);
264
265
        return $this->table()->insert($a);
266
    }
267
268
    private function generateAPI($controller_name, $table_name, $permalink, $method_type = 'post')
269
    {
270
        $php = '<?php '.view('CbApiGen::api_stub', compact('controller_name', 'table_name', 'permalink', 'method_type'))->render();
271
        $path = controllers_dir();
272
        file_put_contents($path.'Api'.$controller_name.'Controller.php', $php);
273
    }
274
275
    /**
276
     * @param $ro string
277
     * @param $default string
278
     * @return string
279
     */
280
    private function getFieldType($ro, $default)
281
    {
282
        $MAP = [
283
            'isEmail' => "email",
284
            'isImage' => "image",
285
            'isPassword' => "password",
286
            'isForeignKey' => "integer",
287
        ];
288
289
        foreach ($MAP as $methodName => $type) {
290
            if (FieldDetector::$methodName($ro)) {
291
                return $type;
292
            }
293
        }
294
295
        return $default;
296
    }
297
298
    /**
299
     * @param $table2
300
     * @param $ro
301
     * @param $new_result
302
     * @return array
303
     */
304
    private function prepareResults($ro, $new_result)
305
    {
306
        if (starts_with($ro, 'id_')) {
307
            return $new_result;
308
        }
309
        $table2 = substr($ro, 3);
310
        $columns = DB::getSchemaBuilder()->getColumnListing($table2);
311
        $columns = array_filter($columns, function ($col) {
312
            return ! FieldDetector::isExceptional($col);
313
        });
314
315
        foreach ($columns as $col) {
316
            $col = str_replace("_$table2", "", $col);
317
            $new_result[] = ['name' => $table2.'_'.$col, 'type' => \Schema::getColumnType($table2, $col)];
318
        }
319
320
        return $new_result;
321
    }
322
}
323