Passed
Push — master ( 72fffe...b949dd )
by Ferry
04:19
created

DeveloperPluginStoreController::getInstall()   C

Complexity

Conditions 12
Paths 54

Size

Total Lines 70
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 38
c 1
b 0
f 0
nc 54
nop 1
dl 0
loc 70
rs 6.9666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: User
5
 * Date: 4/25/2019
6
 * Time: 9:28 PM
7
 */
8
9
namespace crocodicstudio\crudbooster\controllers;
10
11
use crocodicstudio\crudbooster\exceptions\CBValidationException;
12
use crocodicstudio\crudbooster\helpers\ComposerHelper;
13
use crocodicstudio\crudbooster\helpers\CurlHelper;
14
use crocodicstudio\crudbooster\helpers\ModuleGenerator;
15
use Illuminate\Support\Facades\Cache;
16
use Illuminate\Support\Facades\DB;
17
use Illuminate\Support\Facades\Hash;
18
use Illuminate\Support\Facades\Log;
19
20
class DeveloperPluginStoreController extends Controller
21
{
22
23
    private $view = "crudbooster::dev_layouts.modules.plugin";
24
25
    public function __construct()
26
    {
27
        view()->share(['page_title'=>'Plugin Store']);
28
    }
29
30
31
    public function getIndex() {
32
33
        if(request("refresh")) {
34
            $this->fetchPluginData(false );
35
            return cb()->redirectBack("Plugin list has been refreshed!","success");
36
        }
37
38
        $data = [];
39
        $data['result'] = $this->fetchPluginData();
40
        return view($this->view.'.index',$data);
41
    }
42
43
    public function postLoginAccount() {
44
        $curl = new CurlHelper("http://crudbooster.com/api/login_member");
45
        $curl->headers([
46
            "Access-Token"=>"bVc/ZnpYNSZrMVZYOHE5U2tqcSU=",
47
            "User-Agent"=>"CRUDBooster-Bot-Client"
48
        ]);
49
        $curl->data([
50
            "email"=>request("email"),
51
            "password"=>request("password")
52
        ]);
53
        $response = $curl->send();
54
55
        if($respArray = json_decode($response, true)) {
56
            if($respArray['status'] && isset($respArray['token'])) {
57
                session(['account_token'=>$respArray['token']]);
58
            }
59
            return response()->make($response,200,["Content-Type"=>"application/json"]);
60
        } else {
61
            return response()->json(['status'=>false,'message'=>'failed']);
62
        }
63
    }
64
65
    public function postRequestBuyPlugin() {
66
        $curl = new CurlHelper("http://crudbooster.com/api/request_buy_plugin");
67
        $curl->headers([
68
            "Access-Token"=>"bVc/ZnpYNSZrMVZYOHE5U2tqcSU=",
69
            "User-Agent"=>"CRUDBooster-Bot-Client"
70
        ]);
71
        $curl->data([
72
            "key"=>base64_encode(request("key")),
0 ignored issues
show
Bug introduced by
It seems like request('key') can also be of type array; however, parameter $data of base64_encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

72
            "key"=>base64_encode(/** @scrutinizer ignore-type */ request("key")),
Loading history...
73
            "token"=>base64_encode(request("token")),
74
            "ref"=>base64_encode(cb()->getDeveloperUrl("plugins"))
75
        ]);
76
        $response = $curl->send();
77
78
        if($respArray = json_decode($response, true)) {
79
            if($respArray['status']) {
80
                $form = base64_decode($respArray['payment']);
81
                return response()->json(['status'=>true,'form'=>$form]);
82
            } else {
83
                return response()->json($respArray);
84
            }
85
        } else {
86
            return response()->json(['status'=>false,'message'=>'failed','raw'=>$response]);
87
        }
88
    }
89
90
    public function getUninstall($key)
91
    {
92
        $pluginData = $this->fetchPluginData();
93
94
        if(isset($pluginData[$key])) {
95
            if(file_exists(app_path("CBPlugins/".$key))) {
96
97
                if(isset($pluginData['source']) && $pluginData['source'] == 'composer') {
98
                    if(isset($pluginData['package'])) {
99
                        ComposerHelper::composerRemove($pluginData['package']);
100
                    }
101
                }
102
103
                rrmdir(app_path("CBPlugins/".$key));
104
105
                return response()->json(['status'=>true, 'message'=>'Plugin has been uninstalled!']);
106
            }else{
107
                return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin is not found']);
108
            }
109
        }else {
110
            return response()->json(['status'=>false,'message'=>'Failed to uninstall, plugin key is not found']);
111
        }
112
    }
113
114
    private function recursiveCopy($src,$dst) {
115
        $dir = opendir($src);
116
        @mkdir($dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). 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

116
        /** @scrutinizer ignore-unhandled */ @mkdir($dst);

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...
117
        while(false !== ( $file = readdir($dir)) ) {
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

117
        while(false !== ( $file = readdir(/** @scrutinizer ignore-type */ $dir)) ) {
Loading history...
118
            if (( $file != '.' ) && ( $file != '..' )) {
119
                if ( is_dir($src . '/' . $file) ) {
120
                    $this->recursiveCopy($src . '/' . $file,$dst . '/' . $file);
121
                }
122
                else {
123
                    copy($src . '/' . $file,$dst . '/' . $file);
124
                }
125
            }
126
        }
127
        closedir($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

127
        closedir(/** @scrutinizer ignore-type */ $dir);
Loading history...
128
    }
129
130
    public function getInstall($key)
131
    {
132
        ini_set("memory_limit","192M");
133
        set_time_limit(500);
134
135
        $pluginData = $this->fetchPluginData();
136
137
        try {
138
            if(isset($pluginData[$key])) {
139
                $plugin = $pluginData[$key];
140
141
                if(isset($plugin['source']) && $plugin['source'] == "composer") {
142
143
                    if(isset($plugin['package']) && isset($plugin['service_provider'])) {
144
                        // Make a composer
145
                        $output = ComposerHelper::composerRequire($plugin['package'], $plugin['service_provider']);
146
147
                        return response()->json(['status'=>true,'message'=>$output]);
148
                    } else {
149
                        return response()->json(['status'=>true,'message'=>'Installation is failed, there is no package and or service provider']);
150
                    }
151
152
                } else {
153
                    // Create temp file of zip plugin
154
                    $temp = tmpfile();
155
                    fwrite($temp, file_get_contents($plugin['url_download']));
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

155
                    fwrite(/** @scrutinizer ignore-type */ $temp, file_get_contents($plugin['url_download']));
Loading history...
156
                    $filename = stream_get_meta_data($temp)['uri'];
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $stream of stream_get_meta_data() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

156
                    $filename = stream_get_meta_data(/** @scrutinizer ignore-type */ $temp)['uri'];
Loading history...
157
158
                    // Extract zip plugin
159
                    $zip = new \ZipArchive;
160
                    $res = $zip->open($filename);
161
                    if ($res === TRUE) {
162
                        $zip->extractTo(app_path('CBPlugins'));
163
                        $dirName = $zip->getNameIndex(0);
164
                        $zip->close();
165
                        fclose($temp);
0 ignored issues
show
Bug introduced by
It seems like $temp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

165
                        fclose(/** @scrutinizer ignore-type */ $temp);
Loading history...
166
167
                        // Rename
168
                        if(file_exists(app_path("CBPlugins/".$key))) rrmdir(app_path("CBPlugins/".$key));
169
                        rename(app_path("CBPlugins/".$dirName), app_path("CBPlugins/".$key));
170
171
                        // Read Plugin JSON
172
                        $pluginJson = json_decode(file_get_contents(app_path("CBPlugins/".$key."/plugin.json")), true);
173
174
                        // Check if has asset
175
                        if($pluginJson && $pluginJson['asset']) {
176
                            // Check destination folder is ready
177
                            if(file_exists(public_path("cb_asset/".$key))) {
178
                                rrmdir(public_path("cb_asset/".$key));
179
                            }
180
181
                            // Create directory empty
182
                            mkdir(public_path("cb_asset/".$key));
183
184
                            // Copy asset
185
                            $this->recursiveCopy(app_path("CBPlugins/".$key."/".$pluginJson['asset']), public_path("cb_asset/".$key));
186
                        }
187
188
                        return response()->json(['status'=>true,'message'=>'Install / update plugin has been succesfull!']);
189
190
                    } else {
191
                        return response()->json(['status'=>false,'message'=>"Failed to install/update, can't open the plugin archive"]);
192
                    }
193
                }
194
195
            }else{
196
                return response()->json(['status'=>false,'message'=>'Failed to install/update, plugin key is not found']);
197
            }
198
        } catch (\Exception $e) {
199
            return response()->json(['status'=>false,'message'=>'Something went wrong!']);
200
        }
201
    }
202
203
    private function fetchPluginData($cache = true)
204
    {
205
        if($cache === true && $data = Cache::get("plugin_store_data")) {
206
            return $data;
207
        }
208
209
        $result = [];
210
211
        try {
212
            $no_cache = ($cache)?0:1;
213
            $opts = [
214
                "http" => [
215
                    "method" => "GET",
216
                    "header" => "Access-Token: bVc/ZnpYNSZrMVZYOHE5U2tqcSU=\r\n".
217
                                "User-Agent: CRUDBooster-Bot-Client\r\n".
218
                                "No-Cache: ".$no_cache
219
                ]
220
            ];
221
            Log::debug("Headers: ".print_r($opts,true));
222
            $context = stream_context_create($opts);
223
            $data = file_get_contents(base64_decode("aHR0cDovL2NydWRib29zdGVyLmNvbS9hcGkvcGx1Z2luP2FjY2Vzc190b2tlbj1iVmMvWm5wWU5TWnJNVlpZT0hFNVUydHFjU1U9"), false, $context);
224
            Log::debug("Plugin API : ".$data);
225
            if($data) {
226
                $data = json_decode($data, true);
227
                if($data['status']==true) {
228
229
                    foreach($data['data'] as $item) {
230
                        $key = $item['key'];
231
                        $result[ $key ] = $item;
232
                    }
233
234
                    $result = collect($result)->sortBy("name")->all();
235
236
                    Cache::put("plugin_store_data", $result, now()->addDays(3));
237
                }
238
            }
239
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
240
241
        }
242
243
        return $result;
244
    }
245
}