Failed Conditions
Branch experimental/sf (68db07)
by Kentaro
42:17 queued 33:39
created

PluginController::handler_down()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
ccs 0
cts 4
cp 0
crap 2
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\PluginLocalInstallType;
23
use Eccube\Form\Type\Admin\PluginManagementType;
24
use Eccube\Repository\PluginEventHandlerRepository;
25
use Eccube\Repository\PluginRepository;
26
use Eccube\Service\PluginService;
27
use Eccube\Util\CacheUtil;
28
use Eccube\Util\StringUtil;
29
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
32
use Symfony\Component\Filesystem\Filesystem;
33
use Symfony\Component\Finder\Finder;
34
use Symfony\Component\Form\Extension\Core\Type\FormType;
35
use Symfony\Component\Form\Extension\Core\Type\TextType;
36
use Symfony\Component\HttpFoundation\File\UploadedFile;
37
use Symfony\Component\HttpFoundation\RedirectResponse;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\Routing\Exception\RouteNotFoundException;
40
use Symfony\Component\Validator\Constraints as Assert;
41
42
class PluginController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
43
{
44
    /**
45
     * @var PluginEventHandlerRepository
46
     */
47
    protected $pluginEventHandlerRepository;
48
49
    /**
50
     * @var PluginService
51
     */
52
    protected $pluginService;
53
54
    /**
55
     * @var BaseInfo
56
     */
57
    protected $BaseInfo;
58
59
    /**
60
     * @var PluginRepository
61
     */
62
    protected $pluginRepository;
63
64
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$eventHandlerRepository" missing
Loading history...
65
     * PluginController constructor.
66
     *
67
     * @param PluginRepository $pluginRepository
68
     * @param PluginService $pluginService
0 ignored issues
show
introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
69
     * @param BaseInfo $baseInfo
0 ignored issues
show
introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
introduced by
Doc comment for parameter $baseInfo does not match actual variable name $eventHandlerRepository
Loading history...
70
     */
71
    public function __construct(PluginRepository $pluginRepository, PluginService $pluginService, PluginEventHandlerRepository $eventHandlerRepository, BaseInfo $baseInfo)
72
    {
73
        $this->pluginRepository = $pluginRepository;
74
        $this->pluginService = $pluginService;
75
        $this->pluginEventHandlerRepository = $eventHandlerRepository;
76
        $this->BaseInfo = $baseInfo;
77
    }
78
79
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
80
     * インストール済プラグイン画面
81
     *
82
     * @Route("/%eccube_admin_route%/store/plugin", name="admin_store_plugin")
83
     * @Template("@admin/Store/plugin.twig")
84
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
85
    public function index(Request $request)
86
    {
87
        $pluginForms = [];
88
        $configPages = [];
89
        $Plugins = $this->pluginRepository->findBy([], ['code' => 'ASC']);
90
91
        // ファイル設置プラグインの取得.
92
        $unregisterdPlugins = $this->getUnregisteredPlugins($Plugins);
93
        $unregisterdPluginsConfigPages = [];
94
        foreach ($unregisterdPlugins as $unregisterdPlugin) {
95
            try {
96
                $code = $unregisterdPlugin['code'];
97
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
98
                $unregisterdPluginsConfigPages[$code] = $this->generateUrl('plugin_'.$code.'_config');
99
            } catch (RouteNotFoundException $e) {
100
                // プラグインで設定画面のルートが定義されていない場合は無視
101
            }
102
        }
103
104
        $officialPlugins = [];
105
        $unofficialPlugins = [];
106
107
        foreach ($Plugins as $Plugin) {
108
            $form = $this->formFactory
109
                ->createNamedBuilder(
110
                    'form'.$Plugin->getId(),
111
                    PluginManagementType::class,
112
                    null,
113
                    [
114
                        'plugin_id' => $Plugin->getId(),
115
                    ]
116
                )
117
                ->getForm();
118
            $pluginForms[$Plugin->getId()] = $form->createView();
119
120
            try {
121
                // プラグイン用設定画面があれば表示(プラグイン用のサービスプロバイダーに定義されているか)
122
                $configPages[$Plugin->getCode()] = $this->generateUrl('plugin_'.$Plugin->getCode().'_config');
123
            } catch (\Exception $e) {
124
                // プラグインで設定画面のルートが定義されていない場合は無視
125
            }
126
            if ($Plugin->getSource() == 0) {
127
                // 商品IDが設定されていない場合、非公式プラグイン
128
                $unofficialPlugins[] = $Plugin;
129
            } else {
130
                $officialPlugins[] = $Plugin;
131
            }
132
        }
133
134
        // Todo: Need new authentication mechanism
135
        // オーナーズストアからダウンロード可能プラグイン情報を取得
136
        $authKey = $this->BaseInfo->getAuthenticationKey();
137
        // オーナーズストア通信
138
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json';
139
        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...
140
141
        $officialPluginsDetail = [];
142
        if ($json) {
143
            // 接続成功時
144
            $data = json_decode($json, true);
145
            if (isset($data['success']) && $data['success']) {
146
                foreach ($data['item'] as $item) {
147
                    foreach ($officialPlugins as $key => $plugin) {
148
                        if ($plugin->getSource() == $item['product_id']) {
149
                            $officialPluginsDetail[$key] = $item;
150
                            $officialPluginsDetail[$key]['update_status'] = 0;
151
                            if ($this->pluginService->isUpdate($plugin->getVersion(), $item['version'])) {
152
                                $officialPluginsDetail[$key]['update_status'] = 1;
153
                            }
154
                        }
155
                    }
156
                }
157
            }
158
        }
159
160
        return [
161
            'plugin_forms' => $pluginForms,
162
            'officialPlugins' => $officialPlugins,
163
            'unofficialPlugins' => $unofficialPlugins,
164
            'configPages' => $configPages,
165
            'unregisterdPlugins' => $unregisterdPlugins,
166
            'unregisterdPluginsConfigPages' => $unregisterdPluginsConfigPages,
167
            'officialPluginsDetail' => $officialPluginsDetail,
168
        ];
169
    }
170
171
    /**
172
     * インストール済プラグインからのアップデート
173
     *
174
     * @Method("POST")
175
     * @Route("/%eccube_admin_route%/store/plugin/{id}/update", requirements={"id" = "\d+"}, name="admin_store_plugin_update")
176
     *
177
     * @param Request     $request
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 5 found
Loading history...
178
     * @param Plugin      $Plugin
0 ignored issues
show
introduced by
Expected 2 spaces after parameter type; 6 found
Loading history...
179
     *
180
     * @return RedirectResponse
181
     */
182
    public function update(Request $request, Plugin $Plugin)
183
    {
184
        $form = $this->formFactory
185
            ->createNamedBuilder(
186
                'form'.$Plugin->getId(),
187
                PluginManagementType::class,
188
                null,
189
                [
190
                    'plugin_id' => null, // placeHolder
191
                ]
192
            )
193
            ->getForm();
194
195
        $message = '';
196
        $form->handleRequest($request);
197
        if ($form->isSubmitted() && $form->isValid()) {
198
            $tmpDir = null;
199
            try {
200
                $formFile = $form['plugin_archive']->getData();
201
                $tmpDir = $this->pluginService->createTempDir();
202
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
203
                $formFile->move($tmpDir, $tmpFile);
204
                $this->pluginService->update($Plugin, $tmpDir.'/'.$tmpFile);
205
                $fs = new Filesystem();
206
                $fs->remove($tmpDir);
207
                $this->addSuccess('admin.plugin.update.complete', 'admin');
208
209
                return $this->redirectToRoute('admin_store_plugin');
210
            } catch (PluginException $e) {
211
                if (!empty($tmpDir) && file_exists($tmpDir)) {
212
                    $fs = new Filesystem();
213
                    $fs->remove($tmpDir);
214
                }
215
                $message = $e->getMessage();
216
            } catch (\Exception $er) {
217
                // Catch composer install error | Other error
218
                if (!empty($tmpDir) && file_exists($tmpDir)) {
219
                    $fs = new Filesystem();
220
                    $fs->remove($tmpDir);
221
                }
222
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
223
                $message = 'admin.plugin.install.fail';
224
            }
225
        } else {
226
            $errors = $form->getErrors(true);
227
            foreach ($errors as $error) {
228
                $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...
229
            }
230
        }
231
232
        $this->addError($message, 'admin');
233
234
        return $this->redirectToRoute('admin_store_plugin');
235
    }
236
237
    /**
238
     * 対象のプラグインを有効にします。
239
     *
240
     * @Method("PUT")
241
     * @Route("/%eccube_admin_route%/store/plugin/{id}/enable", requirements={"id" = "\d+"}, name="admin_store_plugin_enable")
242
     *
243
     * @param Plugin      $Plugin
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 6 found
Loading history...
244
     *
245
     * @return RedirectResponse
246
     */
247 View Code Duplication
    public function enable(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...
248
    {
249
        $this->isTokenValid();
250
251
        if ($Plugin->isEnabled()) {
252
            $this->addError('admin.plugin.already.enable', 'admin');
253
        } else {
254
            $requires = $this->pluginService->findRequirePluginNeedEnable($Plugin->getCode());
255
            if (!empty($requires)) {
256
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $requires[0]]);
257
                $dependName = $requires[0];
258
                if ($DependPlugin) {
259
                    $dependName = $DependPlugin->getName();
260
                }
261
                $message = trans('admin.plugin.enable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
262
                $this->addError($message, 'admin');
263
264
                return $this->redirectToRoute('admin_store_plugin');
265
            }
266
            $this->pluginService->enable($Plugin);
267
            $this->addSuccess('admin.plugin.enable.complete', 'admin');
268
        }
269
270
        // 有効化できた場合はキャッシュを再生成する
271
        return $this->redirectToRoute('admin_store_clear_cache');
272
    }
273
274
    /**
275
     * 対象のプラグインを無効にします。
276
     *
277
     * @Method("PUT")
278
     * @Route("/%eccube_admin_route%/store/plugin/{id}/disable", requirements={"id" = "\d+"}, name="admin_store_plugin_disable")
279
     *
280
     * @param Plugin      $Plugin
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 6 found
Loading history...
281
     *
282
     * @return RedirectResponse
283
     */
284 View Code Duplication
    public function disable(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...
285
    {
286
        $this->isTokenValid();
287
288
        if ($Plugin->isEnabled()) {
289
            $dependents = $this->pluginService->findDependentPluginNeedDisable($Plugin->getCode());
290
            if (!empty($dependents)) {
291
                $dependName = $dependents[0];
292
                $DependPlugin = $this->pluginRepository->findOneBy(['code' => $dependents[0]]);
293
                if ($DependPlugin) {
294
                    $dependName = $DependPlugin->getName();
295
                }
296
                $message = trans('admin.plugin.disable.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
297
                $this->addError($message, 'admin');
298
299
                return $this->redirectToRoute('admin_store_plugin');
300
            }
301
302
            $this->pluginService->disable($Plugin);
303
            $this->addSuccess('admin.plugin.disable.complete', 'admin');
304
        } else {
305
            $this->addError('admin.plugin.already.disable', 'admin');
306
307
            return $this->redirectToRoute('admin_store_plugin');
308
        }
309
310
        // 無効化できた場合はキャッシュを再生成する
311
        return $this->redirectToRoute('admin_store_clear_cache');
312
    }
313
314
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$cacheUtil" missing
Loading history...
315
     * プラグイン有効状態切り替え後にキャッシュを削除するためのルーティング
316
     *
317
     * このルーティングが必要な理由:
318
     * プラグイン有効化のリクエスト内でキャッシュを削除しても、有効になる前の情報でキャッシュが再生成されてしまう。
319
     * それを回避するために、このルーティングにリダイレクトして、プラグイン有効状態であらためてキャッシュ再生成する。
320
     *
321
     * @Route("/%eccube_admin_route%/store/plugin/clearcache", name="admin_store_clear_cache")
322
     *
323
     * @param Request     $request
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 5 found
Loading history...
324
     *
325
     * @return RedirectResponse
326
     */
327
    public function clearCache(Request $request, CacheUtil $cacheUtil)
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...
328
    {
329
        $cacheUtil->clearCache();
330
331
        return $this->redirectToRoute('admin_store_plugin');
332
    }
333
334
    /**
335
     * 対象のプラグインを削除します。
336
     *
337
     * @Method("DELETE")
338
     * @Route("/%eccube_admin_route%/store/plugin/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_uninstall")
339
     *
340
     * @param Plugin      $Plugin
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 6 found
Loading history...
341
     *
342
     * @return RedirectResponse
343
     */
344
    public function uninstall(Plugin $Plugin)
345
    {
346
        $this->isTokenValid();
347
348
        if ($Plugin->isEnabled()) {
349
            $this->addError('admin.plugin.uninstall.error.not_disable', 'admin');
350
351
            return $this->redirectToRoute('admin_store_plugin');
352
        }
353
354
        // Check other plugin depend on it
355
        $pluginCode = $Plugin->getCode();
356
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
357
        if (!empty($otherDepend)) {
358
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
359
            $dependName = $otherDepend[0];
360
            if ($DependPlugin) {
361
                $dependName = $DependPlugin->getName();
362
            }
363
            $message = trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
364
            $this->addError($message, 'admin');
365
366
            return $this->redirectToRoute('admin_store_plugin');
367
        }
368
369
        $this->pluginService->uninstall($Plugin);
370
        $this->addSuccess('admin.plugin.uninstall.complete', 'admin');
371
372
        return $this->redirectToRoute('admin_store_plugin');
373
    }
374
375
    /**
376
     * @Route("/%eccube_admin_route%/store/plugin/handler", name="admin_store_plugin_handler")
377
     * @Template("@admin/Store/plugin_handler.twig")
378
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
379
    public function handler()
380
    {
381
        $handlers = $this->pluginEventHandlerRepository->getHandlers();
382
383
        // 一次元配列からイベント毎の二次元配列に変換する
384
        $HandlersPerEvent = [];
385
        foreach ($handlers as $handler) {
386
            $HandlersPerEvent[$handler->getEvent()][$handler->getHandlerType()][] = $handler;
387
        }
388
389
        return [
390
            'handlersPerEvent' => $HandlersPerEvent,
391
        ];
392
    }
393
394
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$Handler" missing
Loading history...
395
     * @Route("/%eccube_admin_route%/store/plugin/handler_up/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_up")
396
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
397
    public function handler_up(PluginEventHandler $Handler)
0 ignored issues
show
Coding Style introduced by
Method name "PluginController::handler_up" is not in camel caps format
Loading history...
398
    {
399
        $repo = $this->pluginEventHandlerRepository;
400
        $repo->upPriority($repo->find($Handler->getId()));
401
402
        return $this->redirectToRoute('admin_store_plugin_handler');
403
    }
404
405
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$Handler" missing
Loading history...
406
     * @Route("/%eccube_admin_route%/store/plugin/handler_down/{id}", requirements={"id" = "\d+"}, name="admin_store_plugin_handler_down")
407
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
408
    public function handler_down(PluginEventHandler $Handler)
0 ignored issues
show
Coding Style introduced by
Method name "PluginController::handler_down" is not in camel caps format
Loading history...
409
    {
410
        $repo = $this->pluginEventHandlerRepository;
411
        $repo->upPriority($Handler, false);
412
413
        return $this->redirectToRoute('admin_store_plugin_handler');
414
    }
415
416
    /**
417
     * プラグインファイルアップロード画面
418
     *
419
     * @Route("/%eccube_admin_route%/store/plugin/install", name="admin_store_plugin_install")
420
     * @Template("@admin/Store/plugin_install.twig")
421
     *
422
     * @param Request     $request
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 5 found
Loading history...
423
     *
424
     * @return array|RedirectResponse
425
     */
426
    public function install(Request $request)
427
    {
428
        $form = $this->formFactory
429
            ->createBuilder(PluginLocalInstallType::class)
430
            ->getForm();
431
        $errors = [];
432
        $form->handleRequest($request);
433
        if ($form->isSubmitted() && $form->isValid()) {
434
            $tmpDir = null;
435
            try {
436
                $service = $this->pluginService;
437
                /** @var UploadedFile $formFile */
438
                $formFile = $form['plugin_archive']->getData();
439
                $tmpDir = $service->createTempDir();
440
                // 拡張子を付けないとpharが動かないので付ける
441
                $tmpFile = sha1(StringUtil::random(32)).'.'.$formFile->getClientOriginalExtension();
442
                $formFile->move($tmpDir, $tmpFile);
443
                $tmpPath = $tmpDir.'/'.$tmpFile;
444
                $service->install($tmpPath);
445
                // Remove tmp file
446
                $fs = new Filesystem();
447
                $fs->remove($tmpDir);
448
                $this->addSuccess('admin.plugin.install.complete', 'admin');
449
450
                return $this->redirectToRoute('admin_store_plugin');
451
            } catch (PluginException $e) {
452
                if (!empty($tmpDir) && file_exists($tmpDir)) {
453
                    $fs = new Filesystem();
454
                    $fs->remove($tmpDir);
455
                }
456
                log_error('plugin install failed.', ['original-message' => $e->getMessage()]);
457
                $errors[] = $e;
458
            } catch (\Exception $er) {
459
                // Catch composer install error | Other error
460
                if (!empty($tmpDir) && file_exists($tmpDir)) {
461
                    $fs = new Filesystem();
462
                    $fs->remove($tmpDir);
463
                }
464
                log_error('plugin install failed.', ['original-message' => $er->getMessage()]);
465
                $this->addError('admin.plugin.install.fail', 'admin');
466
            }
467
        } else {
468
            foreach ($form->getErrors(true) as $error) {
469
                $errors[] = $error;
470
            }
471
        }
472
473
        return [
474
            'form' => $form->createView(),
475
            'errors' => $errors,
476
        ];
477
    }
478
479
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$request" missing
Loading history...
480
     * 認証キー設定画面
481
     *
482
     * @Route("/%eccube_admin_route%/store/plugin/authentication_setting", name="admin_store_authentication_setting")
483
     * @Template("@admin/Store/authentication_setting.twig")
484
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
485
    public function authenticationSetting(Request $request)
486
    {
487
        $builder = $this->formFactory
488
            ->createBuilder(FormType::class, $this->BaseInfo);
489
        $builder->add(
490
            'authentication_key',
491
            TextType::class,
492
            [
493
                'label' => trans('plugin.label.auth_key'),
494
                'constraints' => [
495
                    new Assert\Regex(['pattern' => '/^[0-9a-zA-Z]+$/']),
496
                ],
497
            ]
498
        );
499
500
        $form = $builder->getForm();
501
        $form->handleRequest($request);
502
503
        if ($form->isSubmitted() && $form->isValid()) {
504
            // 認証キーの登録
505
            $this->BaseInfo = $form->getData();
506
            $this->entityManager->persist($this->BaseInfo);
507
            $this->entityManager->flush();
508
509
            $this->addSuccess('admin.plugin.authentication.setting.complete', 'admin');
510
        }
511
512
        return [
513
            'form' => $form->createView(),
514
        ];
515
    }
516
517
    /**
518
     * APIリクエスト処理
519
     *
520
     * @param Request $request
521
     * @param $authKey
522
     * @param string $url
523
     *
524
     * @return array
525
     */
526
    private function getRequestApi(Request $request, $authKey, $url)
527
    {
528
        $curl = curl_init($url);
529
530
        $options = [           // オプション配列
531
            //HEADER
532
            CURLOPT_HTTPHEADER => [
533
                'Authorization: '.base64_encode($authKey),
534
                'x-eccube-store-url: '.base64_encode($request->getSchemeAndHttpHost().$request->getBasePath()),
535
                'x-eccube-store-version: '.base64_encode(Constant::VERSION),
536
            ],
537
            CURLOPT_HTTPGET => true,
538
            CURLOPT_SSL_VERIFYPEER => true,
539
            CURLOPT_RETURNTRANSFER => true,
540
            CURLOPT_FAILONERROR => true,
541
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
542
        ];
543
544
        curl_setopt_array($curl, $options); /// オプション値を設定
545
        $result = curl_exec($curl);
546
        $info = curl_getinfo($curl);
547
548
        $message = curl_error($curl);
549
        $info['message'] = $message;
550
        curl_close($curl);
551
552
        log_info('http get_info', $info);
553
554
        return [$result, $info];
555
    }
556
557
    /**
558
     * レスポンスのチェック
559
     *
560
     * @param $info
561
     *
562
     * @return string
563
     */
564 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...
565
    {
566
        if (!empty($info)) {
567
            $statusCode = $info['http_code'];
568
            $message = $info['message'];
569
570
            $message = $statusCode.' : '.$message;
571
        } else {
572
            $message = trans('plugin.text.error.timeout_or_invalid_url');
573
        }
574
575
        return $message;
576
    }
577
578
    /**
579
     * フォルダ設置のみのプラグインを取得する.
580
     *
581
     * @param array $plugins
582
     *
583
     * @return array
584
     */
585
    protected function getUnregisteredPlugins(array $plugins)
0 ignored issues
show
introduced by
Declare public methods first, then protected ones and finally private ones
Loading history...
586
    {
587
        $finder = new Finder();
588
        $pluginCodes = [];
589
590
        // DB登録済みプラグインコードのみ取得
591
        foreach ($plugins as $key => $plugin) {
592
            $pluginCodes[] = $plugin->getCode();
593
        }
594
        // DB登録済みプラグインコードPluginディレクトリから排他
595
        $dirs = $finder->in($this->eccubeConfig['plugin_realdir'])->depth(0)->directories();
596
597
        // プラグイン基本チェック
598
        $unregisteredPlugins = [];
599
        foreach ($dirs as $dir) {
600
            $pluginCode = $dir->getBasename();
601
            if (in_array($pluginCode, $pluginCodes, true)) {
602
                continue;
603
            }
604
            try {
605
                $this->pluginService->checkPluginArchiveContent($dir->getRealPath());
606
            } catch (\Eccube\Exception\PluginException $e) {
607
                //config.yamlに不備があった際は全てスキップ
608
                log_warning($e->getMessage());
609
                continue;
610
            }
611
            $config = $this->pluginService->readYml($dir->getRealPath().'/config.yml');
612
            $unregisteredPlugins[$pluginCode]['name'] = isset($config['name']) ? $config['name'] : null;
613
            $unregisteredPlugins[$pluginCode]['event'] = isset($config['event']) ? $config['event'] : null;
614
            $unregisteredPlugins[$pluginCode]['version'] = isset($config['version']) ? $config['version'] : null;
615
            $unregisteredPlugins[$pluginCode]['enabled'] = Constant::DISABLED;
616
            $unregisteredPlugins[$pluginCode]['code'] = isset($config['code']) ? $config['code'] : null;
617
        }
618
619
        return $unregisteredPlugins;
620
    }
621
}
622