Passed
Push — master ( 71b23e...5dcda6 )
by Iman
05:33
created

AdminApiGeneratorController::generateAPI()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
nc 1
nop 4
dl 0
loc 5
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 Illuminate\Support\Facades\Request;
7
use Illuminate\Support\Facades\DB;
8
use Illuminate\Support\Facades\Route;
9
use crocodicstudio\crudbooster\helpers\CRUDBooster;
10
11
class AdminApiGeneratorController extends CBController
12
{
13
    public function cbInit()
14
    {
15
        $this->table = 'cms_apicustom';
16
        $this->primaryKey = "id";
17
        $this->title_field = "nama";
18
        $this->buttonShow = false;
19
        $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...
20
        $this->deleteBtn = false;
21
        $this->buttonAdd = false;
22
        $this->button_import = false;
23
        $this->buttonExport = false;
24
    }
25
26
    public function getIndex()
27
    {
28
        $this->cbLoader();
29
30
        $data = [];
31
32
        $data['page_title'] = 'API Generator';
33
        $data['apis'] = $this->table()->orderby('nama', 'asc')->get();
34
35
        return view('CbApiGen::api_documentation', $data);
36
    }
37
38
    public function apiDocumentation()
39
    {
40
        $this->cbLoader();
41
        $data = [];
42
43
        $data['apis'] = $this->table()->orderby('nama', 'asc')->get();
44
45
        return view('CbApiGen::api_documentation_public', $data);
46
    }
47
48
    public function getDownloadPostman()
49
    {
50
        $this->cbLoader();
51
        $data = [];
52
        $data['variables'] = [];
53
        $data['info'] = [
54
            'name' => cbGetsetting('appname').' - API',
55
            '_postman_id' => "1765dd11-73d1-2978-ae11-36921dc6263d",
56
            'description' => '',
57
            'schema' => 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json',
58
        ];
59
        $items = [];
60
        foreach ($this->table()->orderby('nama', 'asc')->get() as $api) {
61
            $parameters = unserialize($api->parameters);
62
            $formdata = [];
63
            $httpbuilder = [];
64
            if ($parameters) {
65
                foreach ($parameters as $p) {
66
                    $enabled = ($p['used'] == 0) ? false : true;
67
                    $name = $p['name'];
68
                    $httpbuilder[$name] = '';
69
                    if ($enabled) {
70
                        $formdata[] = ['key' => $name, 'value' => '', 'type' => 'text', 'enabled' => $enabled];
71
                    }
72
                }
73
            }
74
75
            if (strtolower($api->method_type) == 'get' && $httpbuilder) {
76
                $httpbuilder = "?".http_build_query($httpbuilder);
77
            } else {
78
                $httpbuilder = '';
79
            }
80
81
            $items[] = [
82
                'name' => $api->nama,
83
                'request' => [
84
                    'url' => url('api/'.$api->permalink).$httpbuilder,
85
                    'method' => $api->method_type ?: 'GET',
86
                    'header' => [],
87
                    'body' => [
88
                        'mode' => 'formdata',
89
                        'formdata' => $formdata,
90
                    ],
91
                    'description' => $api->keterangan,
92
                ],
93
            ];
94
        }
95
        $data['item'] = $items;
96
97
        $json = json_encode($data);
98
99
        return \Response::make($json, 200, [
100
            'Content-Type' => 'application/json',
101
            'Content-Disposition' => 'attachment; filename='.cbGetsetting('appname').' - API For POSTMAN.json',
102
        ]);
103
    }
104
105
    public function getGenerator()
106
    {
107
        $this->cbLoader();
108
109
        $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...
110
        $data['tables'] = CRUDBooster::listCbTables();
111
112
        return view('CbApiGen::api_generator', $data);
113
    }
114
115
    public function getEditApi($id)
116
    {
117
        $this->cbLoader();
118
119
        $row = $this->findRow($id)->first();
120
121
        $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...
122
        $data['parameters'] = json_encode(unserialize($row->parameters));
123
        $data['responses'] = json_encode(unserialize($row->responses));
124
        $data['page_title'] = 'API Generator';
125
126
        $data['tables'] = CRUDBooster::listCbTables();
127
128
        return view('CbApiGen::api_generator', $data);
129
    }
130
131
    public function postSaveApiCustom()
132
    {
133
        $this->cbLoader();
134
        $posts = request()->all();
135
136
        $_data = [];
137
138
        $_data['nama'] = g('nama');
139
        $_data['tabel'] = $posts['tabel'];
140
        $_data['aksi'] = $posts['aksi'];
141
        $_data['permalink'] = g('permalink');
142
        $_data['method_type'] = g('method_type');
143
144
        $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

144
        /** @scrutinizer ignore-call */ 
145
        $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...
145
146
        $_data['parameters'] = serialize(array_filter($json));
147
148
        $_data['sql_where'] = g('sql_where');
149
150
        $json = $this->json2(g('responses_name'), g('responses_type'), g('responses_subquery'), g('responses_used'));
151
        $json = array_filter($json);
152
        $_data['responses'] = serialize($json);
153
        $_data['keterangan'] = g('keterangan');
154
155
        $this->saveToDB($_data);
156
157
        return redirect(CRUDBooster::mainpath())->with(['message' => 'Yeay, your api has been saved successfully !', 'message_type' => 'success']);
158
    }
159
160
    public function getDeleteApi($id)
161
    {
162
        $this->cbLoader();
163
        $row = $this->findRow($id)->first();
164
        $this->findRow($id)->delete();
165
166
        $controllername = ucwords(str_replace('_', ' ', $row->permalink));
167
        $controllername = str_replace(' ', '', $controllername);
168
        @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

168
        /** @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...
169
170
        return response()->json(['status' => 1]);
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

170
        return response()->/** @scrutinizer ignore-call */ json(['status' => 1]);
Loading history...
171
    }
172
173
    /**
174
     * @param $params_name
175
     * @param $params_type
176
     * @param $params_config
177
     * @param $params_required
178
     * @param $params_used
179
     * @param $json
180
     * @return array
181
     */
182
    private function json($params_name, $params_type, $params_config, $params_required, $params_used, $json)
0 ignored issues
show
Unused Code introduced by
The parameter $json is not used and could be removed. ( Ignorable by Annotation )

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

182
    private function json($params_name, $params_type, $params_config, $params_required, $params_used, /** @scrutinizer ignore-unused */ $json)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
183
    {
184
        $json = [];
185
        for ($i = 0, $_count = count($params_name); $i <= $_count; $i++) {
186
            if (! $params_name[$i]) {
187
                continue;
188
            }
189
            $json[] = [
190
                'name' => $params_name[$i],
191
                'type' => $params_type[$i],
192
                'config' => $params_config[$i],
193
                'required' => $params_required[$i],
194
                'used' => $params_used[$i],
195
            ];
196
        }
197
198
        return $json;
199
    }
200
201
    /**
202
     * @param $responses_name
203
     * @param $responses_type
204
     * @param $responses_subquery
205
     * @param $responses_used
206
     * @return array
207
     */
208
    private function json2($responses_name, $responses_type, $responses_subquery, $responses_used)
209
    {
210
        $json = [];
211
        for ($i = 0, $_count = count($responses_name); $i <= $_count; $i++) {
212
            if (! $responses_name[$i]) {
213
                continue;
214
            }
215
            $json[] = [
216
                'name' => $responses_name[$i],
217
                'type' => $responses_type[$i],
218
                'subquery' => $responses_subquery[$i],
219
                'used' => $responses_used[$i],
220
            ];
221
        }
222
223
        return $json;
224
    }
225
226
    /**
227
     * @param $a
228
     */
229
    private function saveToDB($a)
230
    {
231
        if (request('id')) {
232
            return $this->findRow(g('id'))->update($a);
233
        }
234
235
        $controllerName = ucwords(str_replace('_', ' ', $a['permalink']));
236
        $controllerName = str_replace(' ', '', $controllerName);
237
        $this->generateAPI($controllerName, $a['tabel'], $a['permalink'], $a['method_type']);
238
239
        return $this->table()->insert($a);
240
    }
241
242
    private function generateAPI($controller_name, $table_name, $permalink, $method_type = 'post')
243
    {
244
        $php = '<?php '.view('CbApiGen::api_stub', compact('controller_name', 'table_name', 'permalink', 'method_type'))->render();
245
        $path = controllers_dir();
246
        file_put_contents($path.'Api'.$controller_name.'Controller.php', $php);
247
    }
248
}
249