Failed Conditions
Pull Request — experimental/3.1 (#2670)
by
unknown
24:05 queued 02:41
created

OwnerStoreController   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 409
Duplicated Lines 4.89 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 0%

Importance

Changes 9
Bugs 1 Features 1
Metric Value
c 9
b 1
f 1
dl 20
loc 409
ccs 0
cts 96
cp 0
rs 8.3999
wmc 38
lcom 1
cbo 10

8 Methods

Rating   Name   Duplication   Size   Complexity  
C search() 7 71 14
B doConfirm() 0 29 2
C apiInstall() 0 78 11
B deleteConfirm() 0 41 4
A apiUninstall() 0 19 3
B getRequestApi() 0 26 1
A postRequestApi() 0 16 1
A getResponseErrorMessage() 13 13 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
namespace Eccube\Controller\Admin\Store;
24
25
use Doctrine\ORM\EntityManager;
26
use Eccube\Annotation\Inject;
27
use Eccube\Application;
28
use Eccube\Common\Constant;
29
use Eccube\Controller\AbstractController;
30
use Eccube\Entity\Plugin;
31
use Eccube\Repository\PluginRepository;
32
use Eccube\Service\Composer\ComposerServiceInterface;
33
use Eccube\Service\PluginService;
34
use Eccube\Service\SystemService;
35
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
36
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
37
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
38
use Symfony\Component\HttpFoundation\RedirectResponse;
39
use Symfony\Component\HttpFoundation\Request;
40
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
41
42
/**
43
 * @Route(service=OwnerStoreController::class)
44
 */
45
class OwnerStoreController extends AbstractController
46
{
47
    /**
48
     * @Inject("config")
49
     * @var array
50
     */
51
    protected $appConfig;
52
53
    /**
54
     * @Inject(PluginRepository::class)
55
     * @var PluginRepository
56
     */
57
    protected $pluginRepository;
58
59
    /**
60
     * @Inject(PluginService::class)
61
     * @var PluginService
62
     */
63
    protected $pluginService;
64
65
    /**
66
     * @Inject("eccube.service.composer")
67
     * @var ComposerServiceInterface
68
     */
69
    protected $composerService;
70
71
    /**
72
     * @var EntityManager
73
     * @Inject("orm.em")
74
     */
75
    protected $em;
76
77
    /**
78
     * @Inject(SystemService::class)
79
     * @var SystemService
80
     */
81
    protected $systemService;
82
83
    private static $vendorName = 'ec-cube';
84
85
    /**
86
     * Owner's Store Plugin Installation Screen - Search function
87
     *
88
     * @Route("/{_admin}/store/plugin/search", name="admin_store_plugin_owners_search")
89
     * @Template("Store/plugin_search.twig")
90
     * @param Application $app
91
     * @param Request     $request
92
     * @return array
93
     */
94
    public function search(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
95
    {
96
        // Acquire downloadable plug-in information from owners store
97
        $items = array();
98
        $promotionItems = array();
99
        $message = '';
100
        // Owner's store communication
101
        $url = $this->appConfig['package_repo_url'].'/search/packages.json';
102
        list($json, $info) = $this->getRequestApi($url);
103
        if ($json === false) {
104
            $message = $this->getResponseErrorMessage($info);
105
        } else {
106
            $data = json_decode($json, true);
107
            if (isset($data['success']) && $data['success']) {
108
                // Check plugin installed
109
                $pluginInstalled = $this->pluginRepository->findAll();
110
                // Update_status 1 : not install/purchased 、2 : Installed、 3 : Update、4 : paid purchase
111
                foreach ($data['item'] as $item) {
112
                    // Not install/purchased
113
                    $item['update_status'] = 1;
114
                    /** @var Plugin $plugin */
115
                    foreach ($pluginInstalled as $plugin) {
116
                        if ($plugin->getSource() == $item['product_id']) {
117
                            // Installed
118
                            $item['update_status'] = 2;
119
                            if ($this->pluginService->isUpdate($plugin->getVersion(), $item['version'])) {
120
                                // Need update
121
                                $item['update_status'] = 3;
122
                            }
123
                        }
124
                    }
125
                    $items[] = $item;
126
                }
127
128
                // EC-CUBE version check
129
                foreach ($items as &$item) {
130
                    // Not applicable version
131
                    $item['version_check'] = 0;
132
                    if (in_array(Constant::VERSION, $item['eccube_version'])) {
133
                        // Match version
134
                        $item['version_check'] = 1;
135
                    }
136
                    if ($item['price'] != '0' && $item['purchased'] == '0') {
137
                        // Not purchased with paid items
138
                        $item['update_status'] = 4;
139
                    }
140
                    // Add plugin dependency
141
                    $item['depend'] = $this->pluginService->getRequirePluginName($items, $item);
142
                }
143
                unset($item);
144
145
                // Promotion item
146
                $i = 0;
147 View Code Duplication
                foreach ($items as $item) {
148
                    if ($item['promotion'] == 1) {
149
                        $promotionItems[] = $item;
150
                        unset($items[$i]);
151
                    }
152
                    $i++;
153
                }
154
            } else {
155
                $message = $app->trans('admin.plugin.authentication.fail');
156
            }
157
        }
158
159
        return [
160
            'items' => $items,
161
            'promotionItems' => $promotionItems,
162
            'message' => $message,
163
        ];
164
    }
165
166
    /**
167
     * Do confirm page
168
     *
169
     * @Route("/{_admin}/store/plugin/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_install_confirm")
170
     * @Template("Store/plugin_confirm.twig")
171
     * @param Application $app
172
     * @param Request     $request
173
     * @param string      $id
174
     * @return array
175
     */
176
    public function doConfirm(Application $app, Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $app is not used and could be removed.

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

Loading history...
177
    {
178
        // Owner's store communication
179
        $url = $this->appConfig['package_repo_url'].'/search/packages.json';
180
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
181
        $data = json_decode($json, true);
182
        $items = $data['item'];
183
184
        // Find plugin in api
185
        $index = array_search($id, array_column($items, 'product_id'));
186
        if ($index === false) {
187
            throw new NotFoundHttpException();
188
        }
189
190
        $pluginCode = $items[$index]['product_code'];
191
192
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
193
194
        // Prevent infinity loop: A -> B -> A.
195
        $dependents[] = $plugin;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dependents was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dependents = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
196
        $dependents = $this->pluginService->getDependency($items, $plugin, $dependents);
0 ignored issues
show
Bug introduced by
It seems like $plugin defined by $this->pluginService->bu...fo($items, $pluginCode) on line 192 can also be of type null; however, Eccube\Service\PluginService::getDependency() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
197
        // Unset first param
198
        unset($dependents[0]);
199
200
        return [
201
            'item' => $plugin,
202
            'dependents' => $dependents,
203
        ];
204
    }
205
206
    /**
207
     * Api Install plugin by composer connect with package repo
208
     *
209
     * @Route("/{_admin}/store/plugin/api/{pluginCode}/{eccubeVersion}/{version}" , name="admin_store_plugin_api_install")
210
     *
211
     * @param Application $app
212
     * @param Request     $request
213
     * @param string      $pluginCode
214
     * @param string      $eccubeVersion
215
     * @param string      $version
216
     * @return RedirectResponse
217
     */
218
    public function apiInstall(Application $app, Request $request, $pluginCode, $eccubeVersion, $version)
219
    {
220
        // Check plugin code
221
        $url = $this->appConfig['package_repo_url'].'/search/packages.json'.'?eccube_version='.$eccubeVersion.'&plugin_code='.$pluginCode.'&version='.$version;
222
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
223
        $existFlg = false;
224
        $data = json_decode($json, true);
225
        if ($data && isset($data['success'])) {
226
            $success = $data['success'];
227
            if ($success == '1' && isset($data['item'])) {
228
                foreach ($data['item'] as $item) {
229
                    if ($item['product_code'] == $pluginCode) {
230
                        $existFlg = true;
231
                        break;
232
                    }
233
                }
234
            }
235
        }
236
        if ($existFlg === false) {
237
            log_info(sprintf('%s plugin not found!', $pluginCode));
238
            $app->addError('admin.plugin.not.found', 'admin');
239
240
            return $app->redirect($app->url('admin_store_plugin_owners_search'));
241
        }
242
        $dependents = array();
243
        $items = $data['item'];
244
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
245
        $dependents[] = $plugin;
246
        $dependents = $this->pluginService->getDependency($items, $plugin, $dependents);
0 ignored issues
show
Bug introduced by
It seems like $plugin defined by $this->pluginService->bu...fo($items, $pluginCode) on line 244 can also be of type null; however, Eccube\Service\PluginService::getDependency() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
247
248
        // Unset first param
249
        unset($dependents[0]);
250
        $dependentModifier = [];
251
        $packageNames = '';
252
        if (!empty($dependents)) {
253
            foreach ($dependents as $item) {
254
                $packageNames .= self::$vendorName . '/' . $item['product_code'] . ' ';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
255
                $pluginItem = [
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
256
                    "product_code" => $item['product_code'],
257
                    "version" => $item['version']
258
                ];
259
                array_push($dependentModifier, $pluginItem);
260
            }
261
        }
262
        $packageNames .= self::$vendorName . '/' . $pluginCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
263
        $data = array(
0 ignored issues
show
introduced by
Add a comma after each item in a multi-line array
Loading history...
264
            'code' => $pluginCode,
265
            'version' => $version,
266
            'core_version' => $eccubeVersion,
267
            'php_version' => phpversion(),
268
            'db_version' => $this->systemService->getDbversion(),
269
            'os' => php_uname('s') . ' ' . php_uname('r') . ' ' . php_uname('v'),
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
270
            'host' => $request->getHost(),
271
            'web_server' => $request->server->get("SERVER_SOFTWARE"),
272
            'composer_version' => $this->composerService->composerVersion(),
273
            'composer_execute_mode' => $this->composerService->getMode(),
274
            'dependents' => json_encode($dependentModifier)
275
        );
276
277
        try {
278
            $this->composerService->execRequire($packageNames);
279
            // Do report to package repo
280
            $url = $this->appConfig['package_repo_url'] . '/report';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
281
            $this->postRequestApi($url, $data);
282
            $app->addSuccess('admin.plugin.install.complete', 'admin');
283
284
            return $app->redirect($app->url('admin_store_plugin'));
285
        } catch (\Exception $exception) {
286
            log_info($exception);
287
        }
288
289
        // Do report to package repo
290
        $url = $this->appConfig['package_repo_url'] . '/report/fail';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
291
        $this->postRequestApi($url, $data);
292
        $app->addError('admin.plugin.install.fail', 'admin');
293
294
        return $app->redirect($app->url('admin_store_plugin_owners_search'));
295
    }
296
297
    /**
298
     * Do confirm page
299
     *
300
     * @Route("/{_admin}/store/plugin/delete/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_delete_confirm")
301
     * @Template("Store/plugin_confirm_uninstall.twig")
302
     * @param Application $app
303
     * @param Plugin      $Plugin
304
     * @return array|RedirectResponse
305
     */
306
    public function deleteConfirm(Application $app, Plugin $Plugin)
307
    {
308
        // Owner's store communication
309
        $url = $this->appConfig['package_repo_url'].'/search/packages.json';
310
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
311
        $data = json_decode($json, true);
312
        $items = $data['item'];
313
314
        // The plugin depends on it
315
        $pluginCode = $Plugin->getCode();
316
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
317
318
        if (!empty($otherDepend)) {
319
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
320
            $dependName = $otherDepend[0];
321
            if ($DependPlugin) {
322
                $dependName = $DependPlugin->getName();
323
            }
324
325
            $message = $app->trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
326
            $app->addError($message, 'admin');
327
328
            return $app->redirect($app->url('admin_store_plugin'));
329
        }
330
331
        // Check plugin in api
332
        $pluginSource = $Plugin->getSource();
333
        $index = array_search($pluginSource, array_column($items, 'product_id'));
334
        if ($index === false) {
335
            throw new NotFoundHttpException();
336
        }
337
338
        // Build info
339
        $pluginCode = $Plugin->getCode();
340
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
341
        $plugin['id'] = $Plugin->getId();
342
343
        return [
344
            'item' => $plugin,
345
        ];
346
    }
347
348
    /**
349
     * New ways to remove plugin: using composer command
350
     *
351
     * @Method("DELETE")
352
     * @Route("/{_admin}/store/plugin/api/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_api_uninstall")
353
     * @param Application $app
354
     * @param Plugin      $Plugin
355
     * @return RedirectResponse
356
     */
357
    public function apiUninstall(Application $app, Plugin $Plugin)
358
    {
359
        $this->isTokenValid($app);
360
361
        if ($Plugin->isEnabled()) {
362
            $this->pluginService->disable($Plugin);
363
        }
364
        $pluginCode = $Plugin->getCode();
365
        $packageName = self::$vendorName.'/'.$pluginCode;
366
        try {
367
            $this->composerService->execRemove($packageName);
368
            $app->addSuccess('admin.plugin.uninstall.complete', 'admin');
369
        } catch (\Exception $exception) {
370
            log_info($exception);
371
            $app->addError('admin.plugin.uninstall.error', 'admin');
372
        }
373
374
        return $app->redirect($app->url('admin_store_plugin'));
375
    }
376
377
    /**
378
     * API request processing
379
     *
380
     * @param string  $url
381
     * @return array
382
     */
383
    private function getRequestApi($url)
384
    {
385
        $curl = curl_init($url);
386
387
        // Option array
388
        $options = array(
389
            // HEADER
390
            CURLOPT_HTTPGET => true,
391
            CURLOPT_SSL_VERIFYPEER => false,
392
            CURLOPT_RETURNTRANSFER => true,
393
            CURLOPT_FAILONERROR => true,
394
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
395
        );
396
397
        // Set option value
398
        curl_setopt_array($curl, $options);
399
        $result = curl_exec($curl);
400
        $info = curl_getinfo($curl);
401
        $message = curl_error($curl);
402
        $info['message'] = $message;
403
        curl_close($curl);
404
405
        log_info('http get_info', $info);
406
407
        return array($result, $info);
408
    }
409
410
    /**
411
     * API post request processing
412
     *
413
     * @param string  $url
414
     * @param array $data
415
     * @return array
416
     */
417
    private function postRequestApi($url, $data)
418
    {
419
        $curl = curl_init($url);
420
        curl_setopt($curl, CURLOPT_URL, $url);
421
        curl_setopt($curl, CURLOPT_POST, 1);
422
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
423
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
424
        $result = curl_exec($curl);
425
        $info = curl_getinfo($curl);
426
        $message = curl_error($curl);
427
        $info['message'] = $message;
428
        curl_close($curl);
429
430
        log_info('http post_info', $info);
431
        return array($result, $info);
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
432
    }
433
434
    /**
435
     * Get message
436
     *
437
     * @param $info
438
     * @return string
439
     */
440 View Code Duplication
    private function getResponseErrorMessage($info)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
441
    {
442
        if (!empty($info)) {
443
            $statusCode = $info['http_code'];
444
            $message = $info['message'];
445
446
            $message = $statusCode.' : '.$message;
447
        } else {
448
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
449
        }
450
451
        return $message;
452
    }
453
}
454