Failed Conditions
Push — pr/3408 ( 278c84 )
by Kiyotaka
06:25
created

OwnerStoreController::search()   F

Complexity

Conditions 22
Paths 96

Size

Total Lines 138

Duplication

Lines 16
Ratio 11.59 %

Importance

Changes 0
Metric Value
cc 22
nc 96
nop 3
dl 16
loc 138
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
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\Master\PageMax;
19
use Eccube\Entity\Plugin;
20
use Eccube\Form\Type\Admin\SearchPluginApiType;
21
use Eccube\Repository\PluginRepository;
22
use Eccube\Service\Composer\ComposerApiService;
23
use Eccube\Service\Composer\ComposerProcessService;
24
use Eccube\Service\Composer\ComposerServiceInterface;
25
use Eccube\Service\PluginApiService;
26
use Eccube\Service\PluginService;
27
use Eccube\Service\SystemService;
28
use Eccube\Util\FormUtil;
29
use Knp\Component\Pager\Paginator;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
31
use Symfony\Component\HttpFoundation\RedirectResponse;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpFoundation\Response;
34
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
35
use Symfony\Component\Routing\Annotation\Route;
36
37
/**
38
 * @Route("/%eccube_admin_route%/store/plugin/api")
39
 */
40
class OwnerStoreController extends AbstractController
41
{
42
    /**
43
     * @var PluginRepository
44
     */
45
    protected $pluginRepository;
46
47
    /**
48
     * @var PluginService
49
     */
50
    protected $pluginService;
51
52
    /**
53
     * @var ComposerServiceInterface
54
     */
55
    protected $composerService;
56
57
    /**
58
     * @var SystemService
59
     */
60
    protected $systemService;
61
62
    /**
63
     * @var PluginApiService
64
     */
65
    protected $pluginApiService;
66
67
    private static $vendorName = 'ec-cube';
68
69
    /**
70
     * OwnerStoreController constructor.
71
     *
72
     * @param PluginRepository $pluginRepository
73
     * @param PluginService $pluginService
74
     * @param ComposerProcessService $composerProcessService
75
     * @param ComposerApiService $composerApiService
76
     * @param SystemService $systemService
77
     * @param PluginApiService $pluginApiService
78
     */
79
    public function __construct(
80
        PluginRepository $pluginRepository,
81
        PluginService $pluginService,
82
        ComposerProcessService $composerProcessService,
83
        ComposerApiService $composerApiService,
84
        SystemService $systemService,
85
        PluginApiService $pluginApiService
86
    ) {
87
        $this->pluginRepository = $pluginRepository;
88
        $this->pluginService = $pluginService;
89
        $this->systemService = $systemService;
90
        $this->pluginApiService = $pluginApiService;
91
92
        // TODO: Check the flow of the composer service below
93
        $memoryLimit = $this->systemService->getMemoryLimit();
94
        if ($memoryLimit == -1 or $memoryLimit >= $this->eccubeConfig['eccube_composer_memory_limit']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
95
            $this->composerService = $composerApiService;
96
        } else {
97
            $this->composerService = $composerProcessService;
98
        }
99
    }
100
101
    /**
102
     * Owner's Store Plugin Installation Screen - Search function
103
     *
104
     * @Route("/search", name="admin_store_plugin_owners_search")
105
     * @Route("/search/page/{page_no}", name="admin_store_plugin_owners_search_page", requirements={"page_no" = "\d+"})
106
     * @Template("@admin/Store/plugin_search.twig")
107
     *
108
     * @param Request     $request
109
     * @param int $page_no
110
     * @param Paginator $paginator
111
     *
112
     * @return array
113
     */
114
    public function search(Request $request, $page_no = null, Paginator $paginator)
115
    {
116
        // Acquire downloadable plug-in information from owners store
117
        $items = [];
118
        $message = '';
119
        $total = 0;
120
        $category = [];
121
122
        list($json, $info) = $this->pluginApiService->getCategory();
123
        if (!empty($json)) {
124
            $data = json_decode($json, true);
125
            $category = array_column($data, 'name', 'id');
126
        }
127
128
        // build form with master data
129
        $builder = $this->formFactory
130
            ->createBuilder(SearchPluginApiType::class, null, ['category' => $category]);
131
        $searchForm = $builder->getForm();
132
133
        $searchForm->handleRequest($request);
134
        $searchData = $searchForm->getData();
135
        if ($searchForm->isSubmitted()) {
136
            if ($searchForm->isValid()) {
137
                $page_no = 1;
138
                $searchData = $searchForm->getData();
139
                $this->session->set('eccube.admin.plugin_api.search', FormUtil::getViewData($searchForm));
140
                $this->session->set('eccube.admin.plugin_api.search.page_no', $page_no);
141
            }
142
        } else {
143
            // quick search
144
            if (is_numeric($categoryId = $request->get('category_id')) && array_key_exists($categoryId, $category)) {
145
                $searchForm['category_id']->setData($categoryId);
146
            }
147
            // reset page count
148
            $this->session->set('eccube.admin.plugin_api.search.page_count', $this->eccubeConfig->get('eccube_default_page_count'));
149 View Code Duplication
            if (null !== $page_no || $request->get('resume')) {
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...
150
                if ($page_no) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $page_no of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
151
                    $this->session->set('eccube.admin.plugin_api.search.page_no', (int) $page_no);
152
                } else {
153
                    $page_no = $this->session->get('eccube.admin.plugin_api.search.page_no', 1);
154
                }
155
                $viewData = $this->session->get('eccube.admin.plugin_api.search', []);
156
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
157
            } else {
158
                $page_no = 1;
159
                // submit default value
160
                $viewData = FormUtil::getViewData($searchForm);
161
                $searchData = FormUtil::submitAndGetData($searchForm, $viewData);
162
                $this->session->set('eccube.admin.plugin_api.search', $searchData);
163
                $this->session->set('eccube.admin.plugin_api.search.page_no', $page_no);
164
            }
165
        }
166
167
        // set page count
168
        $pageCount = $this->session->get('eccube.admin.plugin_api.search.page_count', $this->eccubeConfig->get('eccube_default_page_count'));
169
        if (($PageMax = $searchForm['page_count']->getData()) instanceof PageMax) {
170
            $pageCount = $PageMax->getId();
171
            $this->session->set('eccube.admin.plugin_api.search.page_count', $pageCount);
172
        }
173
174
        // Owner's store communication
175
        $searchData['page_no'] = $page_no;
176
        $searchData['page_count'] = $pageCount;
177
        list($json, $info) = $this->pluginApiService->getPlugins($searchData);
178
        if (empty($json)) {
179
            $message = $this->pluginApiService->getResponseErrorMessage($info);
180
        } else {
181
            $data = json_decode($json, true);
182
            $total = $data['total'];
183
            if (isset($data['plugins']) && count($data['plugins']) > 0) {
184
                // Check plugin installed
185
                $pluginInstalled = $this->pluginRepository->findAll();
186
                // Update_status 1 : not install/purchased 、2 : Installed、 3 : Update、4 : not purchased
187
                foreach ($data['plugins'] as $item) {
188
                    // Not install/purchased
189
                    $item['update_status'] = 1;
190
                    /** @var Plugin $plugin */
191
                    foreach ($pluginInstalled as $plugin) {
192
                        if ($plugin->getSource() == $item['id']) {
193
                            // Installed
194
                            $item['update_status'] = 2;
195
                            if ($this->pluginService->isUpdate($plugin->getVersion(), $item['version'])) {
196
                                // Need update
197
                                $item['update_status'] = 3;
198
                            }
199
                        }
200
                    }
201
                    if ($item['purchased'] == false && (isset($item['purchase_required']) && $item['purchase_required'] == true)) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $item['purchase_required'] of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
202
                        // Not purchased with paid items
203
                        $item['update_status'] = 4;
204
                    }
205
                    $items[] = $item;
206
                }
207
208
                // EC-CUBE version check
209
                foreach ($items as &$item) {
210
                    // Not applicable version
211
                    $item['version_check'] = 0;
212
                    if (in_array(Constant::VERSION, $item['supported_versions'])) {
213
                        // Match version
214
                        $item['version_check'] = 1;
215
                    }
216
                    // Add plugin dependency
217
                    $item['depend'] = $this->pluginService->getRequirePluginName($items, $item);
218
                }
219
                unset($item);
220
221
            // Todo: news api will remove this?
222
                // Promotion item
0 ignored issues
show
Unused Code Comprehensibility introduced by
52% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
223
//                $i = 0;
224
//                foreach ($items as $item) {
225
//                    if ($item['promotion'] == 1) {
226
//                        $promotionItems[] = $item;
227
//                        unset($items[$i]);
228
//                    }
229
//                    $i++;
230
//                }
231
            } else {
232
                $message = trans('ownerstore.text.error.ec_cube_error');
233
            }
234
        }
235
236
        // The usage is set because `$items` are already paged.
237
        // virtual paging
238
        $pagination = $paginator->paginate($items, 1, $pageCount);
239
        $pagination->setTotalItemCount($total);
240
        $pagination->setCurrentPageNumber($page_no);
241
        $pagination->setItemNumberPerPage($pageCount);
242
243
        return [
244
            'pagination' => $pagination,
245
            'total' => $total,
246
            'searchForm' => $searchForm->createView(),
247
            'page_no' => $page_no,
248
            'message' => $message,
249
            'Categories' => $category,
250
        ];
251
    }
252
253
    /**
254
     * Do confirm page
255
     *
256
     * @Route("/install/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_install_confirm")
257
     * @Template("@admin/Store/plugin_confirm.twig")
258
     *
259
     * @param Request $request
260
     * @param string $id
261
     *
262
     * @return array
263
     */
264
    public function doConfirm(Request $request, $id)
265
    {
266
        // Owner's store communication
267
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json';
268
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Deprecated Code introduced by
The method Eccube\Controller\Admin\...roller::getRequestApi() has been deprecated with message: since release, please preference 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...
269
        $data = json_decode($json, true);
270
        $items = $data['item'];
271
272
        // Find plugin in api
273
        $index = array_search($id, array_column($items, 'product_id'));
274
        if ($index === false) {
275
            throw new NotFoundHttpException();
276
        }
277
278
        $pluginCode = $items[$index]['product_code'];
279
280
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
281
282
        // Prevent infinity loop: A -> B -> A.
283
        $dependents[] = $plugin;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dependents was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dependents = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

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

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

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

    return array();
}

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

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

Loading history...
285
        // Unset first param
286
        unset($dependents[0]);
287
288
        return [
289
            'item' => $plugin,
290
            'dependents' => $dependents,
291
            'is_update' => $request->get('is_update', false),
292
        ];
293
    }
294
295
    /**
296
     * Api Install plugin by composer connect with package repo
297
     *
298
     * @Route("/install", name="admin_store_plugin_api_install")
299
     *
300
     * @param Request $request
301
     *
302
     * @return RedirectResponse
303
     */
304
    public function apiInstall(Request $request)
305
    {
306
        $pluginCode = $request->get('pluginCode');
307
        $eccubeVersion = $request->get('eccubeVersion');
308
        $version = $request->get('version');
309
310
        // Check plugin code
311
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json'.'?eccube_version='.$eccubeVersion.'&plugin_code='.$pluginCode.'&version='.$version;
312
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Deprecated Code introduced by
The method Eccube\Controller\Admin\...roller::getRequestApi() has been deprecated with message: since release, please preference 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...
313
        $existFlg = false;
314
        $data = json_decode($json, true);
315
        if (isset($data['item']) && !empty($data['item'])) {
316
            $existFlg = $this->pluginService->checkPluginExist($data['item'], $pluginCode);
317
        }
318
        if ($existFlg === false) {
319
            log_info(sprintf('%s plugin not found!', $pluginCode));
320
            $this->addError('admin.plugin.not.found', 'admin');
321
322
            return $this->redirectToRoute('admin_store_plugin_owners_search');
323
        }
324
325
        $items = $data['item'];
326
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
327
        $dependents[] = $plugin;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dependents was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dependents = array(); before regardless.

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

Let’s take a look at an example:

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

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

    // do something with $myArray
}

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

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

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

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

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

    return array();
}

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

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

Loading history...
329
        // Unset first param
330
        unset($dependents[0]);
331
        $dependentModifier = [];
332
        $packageNames = '';
333
        if (!empty($dependents)) {
334
            foreach ($dependents as $key => $item) {
335
                $pluginItem = [
336
                    'product_code' => $item['product_code'],
337
                    'version' => $item['version'],
338
                ];
339
                array_push($dependentModifier, $pluginItem);
340
                // Re-format plugin code
341
                $dependents[$key]['product_code'] = self::$vendorName.'/'.$item['product_code'];
342
            }
343
            $packages = array_column($dependents, 'version', 'product_code');
344
            $packageNames = $this->pluginService->parseToComposerCommand($packages);
345
        }
346
        $packageNames .= ' '.self::$vendorName.'/'.$pluginCode.':'.$version;
347
        $data = [
348
            'code' => $pluginCode,
349
            'version' => $version,
350
            'core_version' => $eccubeVersion,
351
            'php_version' => phpversion(),
352
            'db_version' => $this->systemService->getDbversion(),
353
            'os' => php_uname('s').' '.php_uname('r').' '.php_uname('v'),
354
            'host' => $request->getHost(),
355
            'web_server' => $request->server->get('SERVER_SOFTWARE'),
356
            'composer_version' => $this->composerService->composerVersion(),
357
            'composer_execute_mode' => $this->composerService->getMode(),
358
            'dependents' => json_encode($dependentModifier),
359
        ];
360
361
        try {
362
            $this->composerService->execRequire($packageNames);
363
            // Do report to package repo
364
            $url = $this->eccubeConfig['eccube_package_repo_url'].'/report';
365
            $this->postRequestApi($url, $data);
0 ignored issues
show
Deprecated Code introduced by
The method Eccube\Controller\Admin\...oller::postRequestApi() has been deprecated with message: since release, please preference 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...
366
            $this->addSuccess('admin.plugin.install.complete', 'admin');
367
368
            return $this->redirectToRoute('admin_store_plugin');
369
        } catch (\Exception $exception) {
370
            log_info($exception);
371
        }
372
373
        // Do report to package repo
374
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/report/fail';
375
        $this->postRequestApi($url, $data);
0 ignored issues
show
Deprecated Code introduced by
The method Eccube\Controller\Admin\...oller::postRequestApi() has been deprecated with message: since release, please preference 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...
376
        $this->addError('admin.plugin.install.fail', 'admin');
377
378
        return $this->redirectToRoute('admin_store_plugin_owners_search');
379
    }
380
381
    /**
382
     * Do confirm page
383
     *
384
     * @Route("/delete/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_delete_confirm")
385
     * @Template("@admin/Store/plugin_confirm_uninstall.twig")
386
     *
387
     * @param Plugin $Plugin
388
     *
389
     * @return array|RedirectResponse
390
     */
391
    public function deleteConfirm(Plugin $Plugin)
392
    {
393
        // Owner's store communication
394
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json';
395
        list($json, $info) = $this->getRequestApi($url);
0 ignored issues
show
Unused Code introduced by
The assignment to $info is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
Deprecated Code introduced by
The method Eccube\Controller\Admin\...roller::getRequestApi() has been deprecated with message: since release, please preference 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...
396
        $data = json_decode($json, true);
397
        $items = $data['item'];
398
399
        // The plugin depends on it
400
        $pluginCode = $Plugin->getCode();
401
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
402
403
        if (!empty($otherDepend)) {
404
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
405
            $dependName = $otherDepend[0];
406
            if ($DependPlugin) {
407
                $dependName = $DependPlugin->getName();
408
            }
409
            $message = trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
410
            $this->addError($message, 'admin');
411
412
            return $this->redirectToRoute('admin_store_plugin');
413
        }
414
415
        // Check plugin in api
416
        $pluginSource = $Plugin->getSource();
417
        $index = array_search($pluginSource, array_column($items, 'product_id'));
418
        if ($index === false) {
419
            throw new NotFoundHttpException();
420
        }
421
422
        // Build info
423
        $pluginCode = $Plugin->getCode();
424
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
425
        $plugin['id'] = $Plugin->getId();
426
427
        return [
428
            'item' => $plugin,
429
        ];
430
    }
431
432
    /**
433
     * New ways to remove plugin: using composer command
434
     *
435
     * @Route("/delete/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_api_uninstall", methods={"DELETE"})
436
     *
437
     * @param Plugin $Plugin
438
     *
439
     * @return RedirectResponse
440
     */
441
    public function apiUninstall(Plugin $Plugin)
442
    {
443
        $this->isTokenValid();
444
445
        if ($Plugin->isEnabled()) {
446
            $this->addError('admin.plugin.uninstall.error.not_disable', 'admin');
447
448
            return $this->redirectToRoute('admin_store_plugin');
449
        }
450
451
        $pluginCode = $Plugin->getCode();
452
        $packageName = self::$vendorName.'/'.$pluginCode;
453
        try {
454
            $this->composerService->execRemove($packageName);
455
            $this->addSuccess('admin.plugin.uninstall.complete', 'admin');
456
        } catch (\Exception $exception) {
457
            log_info($exception);
458
            $this->addError('admin.plugin.uninstall.error', 'admin');
459
        }
460
461
        return $this->redirectToRoute('admin_store_plugin');
462
    }
463
464
    /**
465
     * オーナーズブラグインインストール、アップデート
466
     *
467
     * @Route("/upgrade/{pluginCode}/{version}", name="admin_store_plugin_api_upgrade", methods={"PUT"})
468
     *
469
     * @param string $pluginCode
470
     * @param string $version
471
     *
472
     * @return RedirectResponse
473
     */
474
    public function apiUpgrade($pluginCode, $version)
475
    {
476
        $this->isTokenValid();
477
        // Run install plugin
478
        $this->forward($this->generateUrl('admin_store_plugin_api_install', ['pluginCode' => $pluginCode, 'eccubeVersion' => Constant::VERSION, 'version' => $version]));
479
480
        if ($this->session->getFlashBag()->has('eccube.admin.error')) {
481
            $this->session->getFlashBag()->clear();
482
            $this->addError('admin.plugin.update.error', 'admin');
483
484
            return $this->redirectToRoute('admin_store_plugin');
485
        }
486
        $this->session->getFlashBag()->clear();
487
        $this->addSuccess('admin.plugin.update.complete', 'admin');
488
489
        return $this->redirectToRoute('admin_store_plugin');
490
    }
491
492
    /**
493
     * Do confirm update page
494
     *
495
     * @Route("/upgrade/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_update_confirm")
496
     * @Template("@admin/Store/plugin_confirm.twig")
497
     *
498
     * @param Plugin $plugin
499
     *
500
     * @return Response
501
     */
502
    public function doUpdateConfirm(Plugin $plugin)
503
    {
504
        $source = $plugin->getSource();
505
        $url = $this->generateUrl('admin_store_plugin_install_confirm', ['id' => $source, 'is_update' => true]);
506
507
        return $this->forward($url);
508
    }
509
510
    /**
511
     * API request processing
512
     *
513
     * @param string $url
514
     *
515
     * @return array
516
     *
517
     * @deprecated since release, please preference PluginApiService
518
     */
519
    private function getRequestApi($url)
520
    {
521
        $curl = curl_init($url);
522
523
        // Option array
524
        $options = [
525
            // HEADER
526
            CURLOPT_HTTPGET => true,
527
            CURLOPT_SSL_VERIFYPEER => false,
528
            CURLOPT_RETURNTRANSFER => true,
529
            CURLOPT_FAILONERROR => true,
530
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
531
        ];
532
533
        // Set option value
534
        curl_setopt_array($curl, $options);
535
        $result = curl_exec($curl);
536
        $info = curl_getinfo($curl);
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
     * API post request processing
548
     *
549
     * @param string $url
550
     * @param array $data
551
     *
552
     * @return array
553
     *
554
     * @deprecated since release, please preference PluginApiService
555
     */
556
    private function postRequestApi($url, $data)
557
    {
558
        $curl = curl_init($url);
559
        curl_setopt($curl, CURLOPT_URL, $url);
560
        curl_setopt($curl, CURLOPT_POST, 1);
561
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
562
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
563
        $result = curl_exec($curl);
564
        $info = curl_getinfo($curl);
565
        $message = curl_error($curl);
566
        $info['message'] = $message;
567
        curl_close($curl);
568
        log_info('http post_info', $info);
569
570
        return [$result, $info];
571
    }
572
}
573