Passed
Push — master ( 4147d7...c7bef9 )
by Iman
06:57
created

AdminApiGeneratorController::getScreetKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
nc 1
nop 0
dl 0
loc 7
c 0
b 0
f 0
cc 1
rs 9.4285
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
        $new_result = [];
139
        foreach ($result as $ro) {
140
141
            if (in_array($ro, $except)) {
142
                continue;
143
            }
144
            $type_field = \Schema::getColumnType($table, $ro);
145
            $new_result[] = ['name' => $ro, 'type' => $this->getFieldType($ro, $type_field)];
146
147
            if (!in_array($type, ['list', 'detail']) || !starts_with($ro, 'id_') ) {
148
                continue;
149
            }
150
            $table2 = substr($ro, 3);
151
            foreach (DB::getSchemaBuilder()->getColumnListing($table2) as $col) {
152
                if (FieldDetector::isExceptional($col) || starts_with($ro, 'id_')) {
153
                    continue;
154
                }
155
                $col = str_replace("_$table2", "", $col);
156
                $new_result[] = ['name' => $table2.'_'.$col, 'type' => \Schema::getColumnType($table2, $col)];
157
            }
158
        }
159
160
        return response()->json($new_result);
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

160
        return response()->/** @scrutinizer ignore-call */ json($new_result);
Loading history...
161
    }
162
163
    public function postSaveApiCustom()
164
    {
165
        $this->cbLoader();
166
        $posts = request()->all();
167
168
        $_data = [];
169
170
        $_data['nama'] = g('nama');
171
        $_data['tabel'] = $posts['tabel'];
172
        $_data['aksi'] = $posts['aksi'];
173
        $_data['permalink'] = g('permalink');
174
        $_data['method_type'] = g('method_type');
175
176
        $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

176
        /** @scrutinizer ignore-call */ 
177
        $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...
177
178
        $_data['parameters'] = serialize(array_filter($json));
179
180
        $_data['sql_where'] = g('sql_where');
181
182
        $json = $this->json2(g('responses_name'), g('responses_type'), g('responses_subquery'), g('responses_used'));
183
        $json = array_filter($json);
184
        $_data['responses'] = serialize($json);
185
        $_data['keterangan'] = g('keterangan');
186
187
        $this->saveToDB($_data);
188
189
        return redirect(CRUDBooster::mainpath())->with(['message' => 'Yeay, your api has been saved successfully !', 'message_type' => 'success']);
190
    }
191
192
    public function getDeleteApi($id)
193
    {
194
        $this->cbLoader();
195
        $row = $this->findRow($id)->first();
196
        $this->findRow($id)->delete();
197
198
        $controllername = ucwords(str_replace('_', ' ', $row->permalink));
199
        $controllername = str_replace(' ', '', $controllername);
200
        @unlink(base_path(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

200
        /** @scrutinizer ignore-unhandled */ @unlink(base_path(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...
201
202
        return response()->json(['status' => 1]);
203
    }
204
205
    /**
206
     * @param $params_name
207
     * @param $params_type
208
     * @param $params_config
209
     * @param $params_required
210
     * @param $params_used
211
     * @param $json
212
     * @return array
213
     */
214
    private function json($params_name, $params_type, $params_config, $params_required, $params_used, $json)
215
    {
216
        $json = [];
217
        for ($i = 0, $_count = count($params_name); $i <= $_count; $i++) {
218
            if (! $params_name[$i]) {
219
                continue;
220
            }
221
            $json[] = [
222
                'name' => $params_name[$i],
223
                'type' => $params_type[$i],
224
                'config' => $params_config[$i],
225
                'required' => $params_required[$i],
226
                'used' => $params_used[$i],
227
            ];
228
        }
229
230
        return $json;
231
    }
232
233
    /**
234
     * @param $responses_name
235
     * @param $responses_type
236
     * @param $responses_subquery
237
     * @param $responses_used
238
     * @return array
239
     */
240
    private function json2($responses_name, $responses_type, $responses_subquery, $responses_used)
241
    {
242
        $json = [];
243
        for ($i = 0, $_count = count($responses_name); $i <= $_count; $i++) {
244
            if (! $responses_name[$i]) {
245
                continue;
246
            }
247
            $json[] = [
248
                'name' => $responses_name[$i],
249
                'type' => $responses_type[$i],
250
                'subquery' => $responses_subquery[$i],
251
                'used' => $responses_used[$i],
252
            ];
253
        }
254
255
        return $json;
256
    }
257
258
    /**
259
     * @param $a
260
     */
261
    private function saveToDB($a)
262
    {
263
        if (request('id')) {
264
            return $this->findRow(g('id'))->update($a);
265
        }
266
267
        $controllerName = ucwords(str_replace('_', ' ', $a['permalink']));
268
        $controllerName = str_replace(' ', '', $controllerName);
269
        $this->generateAPI($controllerName, $a['tabel'], $a['permalink'], $a['method_type']);
270
271
        return $this->table()->insert($a);
272
    }
273
274
    private function generateAPI($controller_name, $table_name, $permalink, $method_type = 'post')
275
    {
276
        $php = '<?php '.view('CbApiGen::api_stub', compact('controller_name', 'table_name', 'permalink', 'method_type'))->render();
277
        $path = base_path(controllers_dir());
278
        file_put_contents($path.'Api'.$controller_name.'Controller.php', $php);
279
    }
280
281
    /**
282
     * @param $ro string
283
     * @param $default string
284
     * @return string
285
     */
286
    private function getFieldType($ro, $default)
287
    {
288
        $MAP = [
289
            'isEmail' => "email",
290
            'isImage' => "image",
291
            'isPassword' => "password",
292
            'isForeignKey' => "integer",
293
        ];
294
295
        foreach ($MAP as $methodName => $type) {
296
            if (FieldDetector::$methodName($ro)) {
297
                return $type;
298
            }
299
        }
300
301
        return $default;
302
    }
303
}
304