Completed
Push — sf/composer-json ( f5fb05...58ca75 )
by Kiyotaka
05:48
created

PluginController::handler()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Store;
15
16
use Eccube\Common\Constant;
17
use Eccube\Controller\AbstractController;
18
use Eccube\Entity\BaseInfo;
19
use Eccube\Entity\Plugin;
20
use Eccube\Entity\PluginEventHandler;
21
use Eccube\Exception\PluginException;
22
use Eccube\Form\Type\Admin\AuthenticationType;
23
use Eccube\Form\Type\Admin\CaptchaType;
24
use Eccube\Form\Type\Admin\PluginLocalInstallType;
25
use Eccube\Form\Type\Admin\PluginManagementType;
26
use Eccube\Repository\BaseInfoRepository;
27
use Eccube\Repository\PluginRepository;
28
use Eccube\Service\PluginApiService;
29
use Eccube\Service\PluginService;
30
use Eccube\Util\CacheUtil;
31
use Eccube\Util\StringUtil;
32
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
33
use Symfony\Component\DependencyInjection\Container;
34
use Symfony\Component\Filesystem\Filesystem;
35
use Symfony\Component\Finder\Finder;
36
use Symfony\Component\HttpFoundation\File\UploadedFile;
37
use Symfony\Component\HttpFoundation\RedirectResponse;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\Routing\Annotation\Route;
40
use Symfony\Component\Routing\Exception\RouteNotFoundException;
41
42
class PluginController extends AbstractController
43
{
44
    /**
45
     * @var PluginService
46
     */
47
    protected $pluginService;
48
49
    /**
50
     * @var BaseInfo
51
     */
52
    protected $BaseInfo;
53
54
    /**
55
     * @var PluginRepository
56
     */
57
    protected $pluginRepository;
58
59
    /**
60
     * @var PluginApiService
61
     */
62
    protected $pluginApiService;
63
64
    /**
65
     * PluginController constructor.
66
     *
67
     * @param PluginRepository $pluginRepository
68
     * @param PluginService $pluginService
69
     * @param BaseInfoRepository $baseInfoRepository
70
     * @param PluginApiService $pluginApiService
71
     *
72
     * @throws \Doctrine\ORM\NoResultException
73
     * @throws \Doctrine\ORM\NonUniqueResultException
74
     */
75
    public function __construct(PluginRepository $pluginRepository, PluginService $pluginService, BaseInfoRepository $baseInfoRepository, PluginApiService $pluginApiService)
76
    {
77
        $this->pluginRepository = $pluginRepository;
78
        $this->pluginService = $pluginService;
79
        $this->BaseInfo = $baseInfoRepository->get();
80
        $this->pluginApiService = $pluginApiService;
81
    }
82
83
    /**
84
     * インストール済プラグイン画面
85
     *
86
     * @Route("/%eccube_admin_route%/store/plugin", name="admin_store_plugin")
87
     * @Template("@admin/Store/plugin.twig")
88
     */
89
    public function index(Request $request)
90
    {
91
        $pluginForms = [];
92
        $configPages = [];
93
        $Plugins = $this->pluginRepository->findBy([], ['code' => 'ASC']);
94
95
        // ファイル設置プラグインの取得.
96
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins);
97
        $unregisterdPluginsConfigPages = [];
98
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
99
            try {
100
                $code = $unregisterdPlugin['code'];
101
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
102
                $unregisterdPluginsConfigPages[$code] = $this->generateUrl('plugin_'.$code.'_config');
103
            } catch (RouteNotFoundException $e) {
104
                // プラグインで設定画面のルートが定義されていない場合は無視
105
            }
106
        }
107
108
        $officialPlugins = [];
109
        $unofficialPlugins = [];
110
111
        foreach ($Plugins as $Plugin) {
112
            $form = $this->formFactory
113
                ->createNamedBuilder(
114
                    'form'.$Plugin->getId(),
115
                    PluginManagementType::class,
116
                    null,
117
                    [
118
                        'plugin_id' => $Plugin->getId(),
119
                    ]
120
                )
121
                ->getForm();
122
            $pluginForms[$Plugin->getId()] = $form->createView();
123
124
            try {
125
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
126
                $configPages[$Plugin->getCode()] = $this->generateUrl(Container::underscore($Plugin->getCode()).'_admin_config');
127
            } catch (\Exception $e) {
128
                // プラグインで設定画面のルートが定義されていない場合は無視
129
            }
130
            if ($Plugin->getSource() == 0) {
131
                // 商品IDが設定されていない場合、非公式プラグイン
132
                $unofficialPlugins[] = $Plugin;
133
            } else {
134
                $officialPlugins[$Plugin->getSource()] = $Plugin;
135
            }
136
        }
137
138
        // Todo: Need new authentication mechanism
139
        // オーナーズストアからダウンロード可能プラグイン情報を取得
140
        $authKey = $this->BaseInfo->getAuthenticationKey();
141
        // オーナーズストア通信
142
        // TODO: get url from api service instead of direct from controller
143
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/plugins/purchased';
144
        list($json, $info) = $this->getRequestApi($request, $authKey, $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...
Deprecated Code introduced by
The method Eccube\Controller\Admin\...roller::getRequestApi() has been deprecated with message: since release, please refer PluginApiService

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
145
        $officialPluginsDetail = [];
146
        if ($json) {
147
            // 接続成功時
148
            $data = json_decode($json, true);
149
            foreach ($data as $item) {
150
                if (isset($officialPlugins[$item['id']])) {
151
                    $Plugin = $officialPlugins[$item['id']];
152
                    $officialPluginsDetail[$item['id']] = $item;
153
                    $officialPluginsDetail[$item['id']]['update_status'] = 0;
154 View Code Duplication
                    if ($this->pluginService->isUpdate($Plugin->getVersion(), $item['version'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
155
                        $officialPluginsDetail[$item['id']]['update_status'] = 1;
156
                    }
157
                } else {
158
                    $Plugin = new Plugin();
159
                    $Plugin->setName($item['name']);
160
                    $Plugin->setCode($item['code']);
161
                    $Plugin->setVersion($item['version']);
162
                    $Plugin->setSource($item['id']);
163
                    $Plugin->setEnabled(false);
164
                    $officialPlugins[$item['id']] = $Plugin;
165
                    $officialPluginsDetail[$item['id']] = $item;
166
                    $officialPluginsDetail[$item['id']]['update_status'] = 0;
167 View Code Duplication
                    if ($this->pluginService->isUpdate($Plugin->getVersion(), $item['version'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
168
                        $officialPluginsDetail[$item['id']]['update_status'] = 1;
169
                    }
170
                }
171
            }
172
        }
173
174
        return [
175
            'plugin_forms' => $pluginForms,
176
            'officialPlugins' => $officialPlugins,
177
            'unofficialPlugins' => $unofficialPlugins,
178
            'configPages' => $configPages,
179
            'unregisterdPlugins' => $unregisterdPlugins,
180
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
181
            'officialPluginsDetail' => $officialPluginsDetail,
182
        ];
183
    }
184
185
    /**
186
     * インストール済プラグインからのアップデート
187
     *
188
     * @Route("/%eccube_admin_route%/store/plugin/{id}/update", requirements={"id" = "\d+"}, name="admin_store_plugin_update", methods={"POST"})
189
     *
190
     * @param Request $request
191
     * @param Plugin $Plugin
192
     *
193
     * @return RedirectResponse
194
     */
195
    public function update(Request $request, Plugin $Plugin)
196
    {
197
        $form = $this->formFactory
198
            ->createNamedBuilder(
199
                'form'.$Plugin->getId(),
200
                PluginManagementType::class,
201
                null,
202
                [
203
                    'plugin_id' => null, // placeHolder
204
                ]
205
            )
206
            ->getForm();
207
208
        $message = '';
209
        $form->handleRequest($request);
210
        if ($form->isSubmitted() && $form->isValid()) {
211
            $tmpDir = null;
212
            try {
213
                $formFile = $form['plugin_archive']->getData();
214
                $tmpDir = $this->pluginService->createTempDir();
215
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
216
                $formFile->move($tmpDir, $tmpFile);
217
                $this->pluginService->update($Plugin, $tmpDir.'/'.$tmpFile);
218
                $fs = new Filesystem();
219
                $fs->remove($tmpDir);
220
                $this->addSuccess('admin.plugin.update.complete', 'admin');
221
222
                return $this->redirectToRoute('admin_store_plugin');
223
            } catch (PluginException $e) {
224
                if (!empty($tmpDir) && file_exists($tmpDir)) {
225
                    $fs = new Filesystem();
226
                    $fs->remove($tmpDir);
227
                }
228
                $message = $e->getMessage();
229
            } catch (\Exception $er) {
230
                // Catch composer install error | Other error
231
                if (!empty($tmpDir) && file_exists($tmpDir)) {
232
                    $fs = new Filesystem();
233
                    $fs->remove($tmpDir);
234
                }
235
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
236
                $message = 'admin.plugin.install.fail';
237
            }
238
        } else {
239
            $errors = $form->getErrors(true);
240
            foreach ($errors as $error) {
241
                $message = $error->getMessage();
0 ignored issues
show
Bug introduced by
The method getMessage does only exist in Symfony\Component\Form\FormError, but not in Symfony\Component\Form\FormErrorIterator.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
242
            }
243
        }
244
245
        $this->addError($message, 'admin');
246
247
        return $this->redirectToRoute('admin_store_plugin');
248
    }
249
250
    /**
251
     * 対象のプラグインを有効にします。
252
     *
253
     * @Route("/%eccube_admin_route%/store/plugin/{id}/enable", requirements={"id" = "\d+"}, name="admin_store_plugin_enable", methods={"PUT"})
254
     *
255
     * @param Plugin $Plugin
256
     *
257
     * @return RedirectResponse
258
     */
259 View Code Duplication
    public function enable(Plugin $Plugin, CacheUtil $cacheUtil)
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...
260
    {
261
        $this->isTokenValid();
262
263
        if ($Plugin->isEnabled()) {
264
            $this->addError('admin.plugin.already.enable', 'admin');
265
        } else {
266
            $requires = $this->pluginService->findRequirePluginNeedEnable($Plugin->getCode());
267
            if (!empty($requires)) {
268
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $requires[0]]);
269
                $dependName = $requires[0];
270
                if ($DependPlugin) {
271
                    $dependName = $DependPlugin->getName();
272
                }
273
                $message = trans('admin.plugin.enable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
274
                $this->addError($message, 'admin');
275
276
                return $this->redirectToRoute('admin_store_plugin');
277
            }
278
            $this->pluginService->enable($Plugin);
279
            $this->addSuccess('admin.plugin.enable.complete', 'admin');
280
        }
281
282
        // キャッシュを削除してリダイレクト
283
        // リダイレクトにredirectToRoute関数を使用していないのは、削除したキャッシュが再生成されてしまうため。
284
        $url = $this->generateUrl('admin_store_plugin');
285
        $cacheUtil->clearCache();
286
287
        return $this->redirect($url);
288
    }
289
290
    /**
291
     * 対象のプラグインを無効にします。
292
     *
293
     * @Route("/%eccube_admin_route%/store/plugin/{id}/disable", requirements={"id" = "\d+"}, name="admin_store_plugin_disable", methods={"PUT"})
294
     *
295
     * @param Plugin $Plugin
296
     *
297
     * @return RedirectResponse
298
     */
299 View Code Duplication
    public function disable(Plugin $Plugin, CacheUtil $cacheUtil)
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...
300
    {
301
        $this->isTokenValid();
302
303
        if ($Plugin->isEnabled()) {
304
            $dependents = $this->pluginService->findDependentPluginNeedDisable($Plugin->getCode());
305
            if (!empty($dependents)) {
306
                $dependName = $dependents[0];
307
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $dependents[0]]);
308
                if ($DependPlugin) {
309
                    $dependName = $DependPlugin->getName();
310
                }
311
                $message = trans('admin.plugin.disable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
312
                $this->addError($message, 'admin');
313
314
                return $this->redirectToRoute('admin_store_plugin');
315
            }
316
317
            $this->pluginService->disable($Plugin);
318
            $this->addSuccess('admin.plugin.disable.complete', 'admin');
319
        } else {
320
            $this->addError('admin.plugin.already.disable', 'admin');
321
322
            return $this->redirectToRoute('admin_store_plugin');
323
        }
324
325
        // キャッシュを削除してリダイレクト
326
        // リダイレクトにredirectToRoute関数を使用していないのは、削除したキャッシュが再生成されてしまうため。
327
        $url = $this->generateUrl('admin_store_plugin');
328
        $cacheUtil->clearCache();
329
330
        return $this->redirect($url);
331
    }
332
333
    /**
334
     * 対象のプラグインを削除します。
335
     *
336
     * @Route("/%eccube_admin_route%/store/plugin/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_uninstall", methods={"DELETE"})
337
     *
338
     * @param Plugin $Plugin
339
     *
340
     * @return RedirectResponse
341
     */
342 View Code Duplication
    public function uninstall(Plugin $Plugin)
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...
343
    {
344
        $this->isTokenValid();
345
346
        if ($Plugin->isEnabled()) {
347
            $this->addError('admin.plugin.uninstall.error.not_disable', 'admin');
348
349
            return $this->redirectToRoute('admin_store_plugin');
350
        }
351
352
        // Check other plugin depend on it
353
        $pluginCode = $Plugin->getCode();
354
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
355
        if (!empty($otherDepend)) {
356
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
357
            $dependName = $otherDepend[0];
358
            if ($DependPlugin) {
359
                $dependName = $DependPlugin->getName();
360
            }
361
            $message = trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
362
            $this->addError($message, 'admin');
363
364
            return $this->redirectToRoute('admin_store_plugin');
365
        }
366
367
        $this->pluginService->uninstall($Plugin);
368
        $this->addSuccess('admin.plugin.uninstall.complete', 'admin');
369
370
        return $this->redirectToRoute('admin_store_plugin');
371
    }
372
373
    /**
374
     * プラグインファイルアップロード画面
375
     *
376
     * @Route("/%eccube_admin_route%/store/plugin/install", name="admin_store_plugin_install")
377
     * @Template("@admin/Store/plugin_install.twig")
378
     *
379
     * @param Request $request
380
     *
381
     * @return array|RedirectResponse
382
     */
383
    public function install(Request $request)
384
    {
385
        $form = $this->formFactory
386
            ->createBuilder(PluginLocalInstallType::class)
387
            ->getForm();
388
        $errors = [];
389
        $form->handleRequest($request);
390
        if ($form->isSubmitted() && $form->isValid()) {
391
            $tmpDir = null;
392
            try {
393
                $service = $this->pluginService;
394
                /** @var UploadedFile $formFile */
395
                $formFile = $form['plugin_archive']->getData();
396
                $tmpDir = $service->createTempDir();
397
                // 拡張子を付けないとpharが動かないので付ける
398
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
399
                $formFile->move($tmpDir, $tmpFile);
400
                $tmpPath = $tmpDir.'/'.$tmpFile;
401
                $service->install($tmpPath);
402
                // Remove tmp file
403
                $fs = new Filesystem();
404
                $fs->remove($tmpDir);
405
                $this->addSuccess('admin.plugin.install.complete', 'admin');
406
407
                return $this->redirectToRoute('admin_store_plugin');
408
            } catch (PluginException $e) {
409
                if (!empty($tmpDir) && file_exists($tmpDir)) {
410
                    $fs = new Filesystem();
411
                    $fs->remove($tmpDir);
412
                }
413
                log_error('plugin install failed.', ['original-message' => $e->getMessage()]);
414
                $errors[] = $e;
415
            } catch (\Exception $er) {
416
                // Catch composer install error | Other error
417
                if (!empty($tmpDir) && file_exists($tmpDir)) {
418
                    $fs = new Filesystem();
419
                    $fs->remove($tmpDir);
420
                }
421
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
422
                $this->addError('admin.plugin.install.fail', 'admin');
423
            }
424
        } else {
425
            foreach ($form->getErrors(true) as $error) {
426
                $errors[] = $error;
427
            }
428
        }
429
430
        return [
431
            'form' => $form->createView(),
432
            'errors' => $errors,
433
        ];
434
    }
435
436
    /**
437
     * 認証キー設定画面
438
     *
439
     * @Route("/%eccube_admin_route%/store/plugin/authentication_setting", name="admin_store_authentication_setting")
440
     * @Template("@admin/Store/authentication_setting.twig")
441
     */
442
    public function authenticationSetting(Request $request)
443
    {
444
        $builder = $this->formFactory
445
            ->createBuilder(AuthenticationType::class, $this->BaseInfo);
446
447
        $form = $builder->getForm();
448
        $form->handleRequest($request);
449
450
        if ($form->isSubmitted() && $form->isValid()) {
451
            // 認証キーの登録 and PHP path
452
            $this->BaseInfo = $form->getData();
453
            $this->entityManager->persist($this->BaseInfo);
454
            $this->entityManager->flush();
455
456
            $this->addSuccess('admin.flash.register_completed', 'admin');
457
        }
458
459
        $builderCaptcha = $this->formFactory->createBuilder(CaptchaType::class);
460
461
        // get captcha image, save it to temp folder
462
        list($captcha, $info) = $this->pluginApiService->getCaptcha();
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...
463
        $tmpFolder = $this->eccubeConfig->get('eccube_temp_image_dir');
464
        file_put_contents($tmpFolder.'/captcha.png', $captcha);
465
466
        return [
467
            'form' => $form->createView(),
468
            'captchaForm' => $builderCaptcha->getForm()->createView(),
469
        ];
470
    }
471
472
    /**
473
     * Captcha
474
     * Todo: check fail (implement after the api defined)
475
     *
476
     * @param Request $request
477
     *
478
     * @return RedirectResponse
479
     *
480
     * @Route("/%eccube_admin_route%/store/plugin/auth/captcha", name="admin_store_auth_captcha")
481
     */
482
    public function authenticationCaptcha(Request $request)
483
    {
484
        $builder = $this->formFactory->createBuilder(CaptchaType::class);
485
        $form = $builder->getForm();
486
        $form->handleRequest($request);
487
        if ($form->isSubmitted() && $form->isValid()) {
488
            $param['captcha'] = $form['captcha']->getData();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$param was never initialized. Although not strictly required by PHP, it is generally a good practice to add $param = 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...
489
            list($ret, $info) = $this->pluginApiService->postApiKey($param);
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...
490
            if ($ret && $data = json_decode($ret, true)) {
491
                if (isset($data['api_key']) && !empty($data['api_key'])) {
492
                    $this->BaseInfo->setAuthenticationKey($data['api_key']);
493
                    $this->entityManager->persist($this->BaseInfo);
494
                    $this->entityManager->flush($this->BaseInfo);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $this->BaseInfo.

This check compares calls to functions or methods with their respective definitions. If the call has more 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.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
495
                    $this->addSuccess('admin.flash.register_completed', 'admin');
496
497
                    return $this->redirectToRoute('admin_store_authentication_setting');
498
                }
499
            }
500
        }
501
        $this->addError('admin.flash.register_failed', 'admin');
502
503
        return $this->redirectToRoute('admin_store_authentication_setting');
504
    }
505
506
    /**
507
     * APIリクエスト処理
508
     *
509
     * @param Request $request
510
     * @param string|null $authKey
511
     * @param string $url
512
     *
513
     * @deprecated since release, please refer PluginApiService
514
     *
515
     * @return array
516
     */
517
    private function getRequestApi(Request $request, $authKey, $url)
518
    {
519
        $curl = curl_init($url);
520
521
        $options = [// オプション配列
522
            //HEADER
523
            CURLOPT_HTTPHEADER => [
524
                'Authorization: '.base64_encode($authKey),
525
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
526
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
527
            ],
528
            CURLOPT_HTTPGET => true,
529
            CURLOPT_SSL_VERIFYPEER => true,
530
            CURLOPT_RETURNTRANSFER => true,
531
            CURLOPT_FAILONERROR => true,
532
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
533
        ];
534
535
        curl_setopt_array($curl, $options); /// オプション値を設定
536
        $result = curl_exec($curl);
537
        $info = curl_getinfo($curl);
538
539
        $message = curl_error($curl);
540
        $info['message'] = $message;
541
        curl_close($curl);
542
543
        log_info('http get_info', $info);
544
545
        return [$result, $info];
546
    }
547
548
    /**
549
     * レスポンスのチェック
550
     *
551
     * @param $info
552
     *
553
     * @return string
554
     *
555
     * @deprecated since release, please refer PluginApiService
556
     */
557 View Code Duplication
    private function getResponseErrorMessage($info)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
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...
558
    {
559
        if (!empty($info)) {
560
            $statusCode = $info['http_code'];
561
            $message = $info['message'];
562
563
            $message = $statusCode.' : '.$message;
564
        } else {
565
            $message = trans('plugin.text.error.timeout_or_invalid_url');
566
        }
567
568
        return $message;
569
    }
570
571
    /**
572
     * フォルダ設置のみのプラグインを取得する.
573
     *
574
     * @param array $plugins
575
     *
576
     * @return array
577
     */
578
    protected function getUnregisteredPlugins(array $plugins)
579
    {
580
        $finder = new Finder();
581
        $pluginCodes = [];
582
583
        // DB登録済みプラグインコードのみ取得
584
        foreach ($plugins as $key => $plugin) {
585
            $pluginCodes[] = $plugin->getCode();
586
        }
587
        // DB登録済みプラグインコードPluginディレクトリから排他
588
        $dirs = $finder->in($this->eccubeConfig['plugin_realdir'])->depth(0)->directories();
589
590
        // プラグイン基本チェック
591
        $unregisteredPlugins = [];
592
        foreach ($dirs as $dir) {
593
            $pluginCode = $dir->getBasename();
594
            if (in_array($pluginCode, $pluginCodes, true)) {
595
                continue;
596
            }
597
            try {
598
                $this->pluginService->checkPluginArchiveContent($dir->getRealPath());
599
            } catch (\Eccube\Exception\PluginException $e) {
600
                //config.yamlに不備があった際は全てスキップ
601
                log_warning($e->getMessage());
602
                continue;
603
            }
604
            $config = $this->pluginService->readYml($dir->getRealPath().'/config.yml');
605
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
606
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
607
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
608
            $unregisteredPlugins[$pluginCode]['enabled'] = Constant::DISABLED;
609
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
610
        }
611
612
        return $unregisteredPlugins;
613
    }
614
}
615