Completed
Pull Request — experimental/sf (#3340)
by Ryo
231:52 queued 224:05
created

PluginController::clearCache()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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