Failed Conditions
Push — 4.0 ( 35f28e...14891d )
by Ryo
36:06 queued 29:41
created

OwnerStoreController::doUpdateConfirm()   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
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.co.jp/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Eccube\Controller\Admin\Store;
15
16
use Eccube\Common\Constant;
17
use Eccube\Controller\AbstractController;
18
use Eccube\Entity\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')) {
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
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/{pluginCode}/{eccubeVersion}/{version}" , name="admin_store_plugin_api_install")
299
     *
300
     * @param Request $request
301
     * @param string $pluginCode
302
     * @param string $eccubeVersion
303
     * @param string $version
304
     *
305
     * @return RedirectResponse
306
     */
307
    public function apiInstall(Request $request, $pluginCode, $eccubeVersion, $version)
308
    {
309
        // Check plugin code
310
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json'.'?eccube_version='.$eccubeVersion.'&plugin_code='.$pluginCode.'&version='.$version;
311
        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...
312
        $existFlg = false;
313
        $data = json_decode($json, true);
314
        if (isset($data['item']) && !empty($data['item'])) {
315
            $existFlg = $this->pluginService->checkPluginExist($data['item'], $pluginCode);
316
        }
317
        if ($existFlg === false) {
318
            log_info(sprintf('%s plugin not found!', $pluginCode));
319
            $this->addError('admin.plugin.not.found', 'admin');
320
321
            return $this->redirectToRoute('admin_store_plugin_owners_search');
322
        }
323
324
        $items = $data['item'];
325
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
326
        $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...
327
        $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 325 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...
328
        // Unset first param
329
        unset($dependents[0]);
330
        $dependentModifier = [];
331
        $packageNames = '';
332
        if (!empty($dependents)) {
333
            foreach ($dependents as $key => $item) {
334
                $pluginItem = [
335
                    'product_code' => $item['product_code'],
336
                    'version' => $item['version'],
337
                ];
338
                array_push($dependentModifier, $pluginItem);
339
                // Re-format plugin code
340
                $dependents[$key]['product_code'] = self::$vendorName.'/'.$item['product_code'];
341
            }
342
            $packages = array_column($dependents, 'version', 'product_code');
343
            $packageNames = $this->pluginService->parseToComposerCommand($packages);
344
        }
345
        $packageNames .= ' '.self::$vendorName.'/'.$pluginCode.':'.$version;
346
        $data = [
347
            'code' => $pluginCode,
348
            'version' => $version,
349
            'core_version' => $eccubeVersion,
350
            'php_version' => phpversion(),
351
            'db_version' => $this->systemService->getDbversion(),
352
            'os' => php_uname('s').' '.php_uname('r').' '.php_uname('v'),
353
            'host' => $request->getHost(),
354
            'web_server' => $request->server->get('SERVER_SOFTWARE'),
355
            'composer_version' => $this->composerService->composerVersion(),
356
            'composer_execute_mode' => $this->composerService->getMode(),
357
            'dependents' => json_encode($dependentModifier),
358
        ];
359
360
        try {
361
            $this->composerService->execRequire($packageNames);
362
            // Do report to package repo
363
            $url = $this->eccubeConfig['eccube_package_repo_url'].'/report';
364
            $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...
365
            $this->addSuccess('admin.plugin.install.complete', 'admin');
366
367
            return $this->redirectToRoute('admin_store_plugin');
368
        } catch (\Exception $exception) {
369
            log_info($exception);
370
        }
371
372
        // Do report to package repo
373
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/report/fail';
374
        $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...
375
        $this->addError('admin.plugin.install.fail', 'admin');
376
377
        return $this->redirectToRoute('admin_store_plugin_owners_search');
378
    }
379
380
    /**
381
     * Do confirm page
382
     *
383
     * @Route("/delete/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_delete_confirm")
384
     * @Template("@admin/Store/plugin_confirm_uninstall.twig")
385
     *
386
     * @param Plugin $Plugin
387
     *
388
     * @return array|RedirectResponse
389
     */
390
    public function deleteConfirm(Plugin $Plugin)
391
    {
392
        // Owner's store communication
393
        $url = $this->eccubeConfig['eccube_package_repo_url'].'/search/packages.json';
394
        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...
395
        $data = json_decode($json, true);
396
        $items = $data['item'];
397
398
        // The plugin depends on it
399
        $pluginCode = $Plugin->getCode();
400
        $otherDepend = $this->pluginService->findDependentPlugin($pluginCode);
401
402
        if (!empty($otherDepend)) {
403
            $DependPlugin = $this->pluginRepository->findOneBy(['code' => $otherDepend[0]]);
404
            $dependName = $otherDepend[0];
405
            if ($DependPlugin) {
406
                $dependName = $DependPlugin->getName();
407
            }
408
            $message = trans('admin.plugin.uninstall.depend', ['%name%' => $Plugin->getName(), '%depend_name%' => $dependName]);
409
            $this->addError($message, 'admin');
410
411
            return $this->redirectToRoute('admin_store_plugin');
412
        }
413
414
        // Check plugin in api
415
        $pluginSource = $Plugin->getSource();
416
        $index = array_search($pluginSource, array_column($items, 'product_id'));
417
        if ($index === false) {
418
            throw new NotFoundHttpException();
419
        }
420
421
        // Build info
422
        $pluginCode = $Plugin->getCode();
423
        $plugin = $this->pluginService->buildInfo($items, $pluginCode);
424
        $plugin['id'] = $Plugin->getId();
425
426
        return [
427
            'item' => $plugin,
428
        ];
429
    }
430
431
    /**
432
     * New ways to remove plugin: using composer command
433
     *
434
     * @Route("/delete/{id}/uninstall", requirements={"id" = "\d+"}, name="admin_store_plugin_api_uninstall", methods={"DELETE"})
435
     *
436
     * @param Plugin $Plugin
437
     *
438
     * @return RedirectResponse
439
     */
440
    public function apiUninstall(Plugin $Plugin)
441
    {
442
        $this->isTokenValid();
443
444
        if ($Plugin->isEnabled()) {
445
            $this->addError('admin.plugin.uninstall.error.not_disable', 'admin');
446
447
            return $this->redirectToRoute('admin_store_plugin');
448
        }
449
450
        $pluginCode = $Plugin->getCode();
451
        $packageName = self::$vendorName.'/'.$pluginCode;
452
        try {
453
            $this->composerService->execRemove($packageName);
454
            $this->addSuccess('admin.plugin.uninstall.complete', 'admin');
455
        } catch (\Exception $exception) {
456
            log_info($exception);
457
            $this->addError('admin.plugin.uninstall.error', 'admin');
458
        }
459
460
        return $this->redirectToRoute('admin_store_plugin');
461
    }
462
463
    /**
464
     * オーナーズブラグインインストール、アップデート
465
     *
466
     * @Route("/upgrade/{pluginCode}/{version}", name="admin_store_plugin_api_upgrade", methods={"PUT"})
467
     *
468
     * @param string $pluginCode
469
     * @param string $version
470
     *
471
     * @return RedirectResponse
472
     */
473
    public function apiUpgrade($pluginCode, $version)
474
    {
475
        $this->isTokenValid();
476
        // Run install plugin
477
        $this->forward($this->generateUrl('admin_store_plugin_api_install', ['pluginCode' => $pluginCode, 'eccubeVersion' => Constant::VERSION, 'version' => $version]));
478
479
        if ($this->session->getFlashBag()->has('eccube.admin.error')) {
480
            $this->session->getFlashBag()->clear();
481
            $this->addError('admin.plugin.update.error', 'admin');
482
483
            return $this->redirectToRoute('admin_store_plugin');
484
        }
485
        $this->session->getFlashBag()->clear();
486
        $this->addSuccess('admin.plugin.update.complete', 'admin');
487
488
        return $this->redirectToRoute('admin_store_plugin');
489
    }
490
491
    /**
492
     * Do confirm update page
493
     *
494
     * @Route("/upgrade/{id}/confirm", requirements={"id" = "\d+"}, name="admin_store_plugin_update_confirm")
495
     * @Template("@admin/Store/plugin_confirm.twig")
496
     *
497
     * @param Plugin $plugin
498
     *
499
     * @return Response
500
     */
501
    public function doUpdateConfirm(Plugin $plugin)
502
    {
503
        $source = $plugin->getSource();
504
        $url = $this->generateUrl('admin_store_plugin_install_confirm', ['id' => $source, 'is_update' => true]);
505
506
        return $this->forward($url);
507
    }
508
509
    /**
510
     * API request processing
511
     *
512
     * @param string $url
513
     *
514
     * @return array
515
     * @deprecated since release, please preference PluginApiService
516
     */
517
    private function getRequestApi($url)
518
    {
519
        $curl = curl_init($url);
520
521
        // Option array
522
        $options = [
523
            // HEADER
524
            CURLOPT_HTTPGET => true,
525
            CURLOPT_SSL_VERIFYPEER => false,
526
            CURLOPT_RETURNTRANSFER => true,
527
            CURLOPT_FAILONERROR => true,
528
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
529
        ];
530
531
        // Set option value
532
        curl_setopt_array($curl, $options);
533
        $result = curl_exec($curl);
534
        $info = curl_getinfo($curl);
535
        $message = curl_error($curl);
536
        $info['message'] = $message;
537
        curl_close($curl);
538
539
        log_info('http get_info', $info);
540
541
        return [$result, $info];
542
    }
543
544
    /**
545
     * API post request processing
546
     *
547
     * @param string $url
548
     * @param array $data
549
     *
550
     * @return array
551
     * @deprecated since release, please preference PluginApiService
552
     */
553
    private function postRequestApi($url, $data)
554
    {
555
        $curl = curl_init($url);
556
        curl_setopt($curl, CURLOPT_URL, $url);
557
        curl_setopt($curl, CURLOPT_POST, 1);
558
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
559
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
560
        $result = curl_exec($curl);
561
        $info = curl_getinfo($curl);
562
        $message = curl_error($curl);
563
        $info['message'] = $message;
564
        curl_close($curl);
565
        log_info('http post_info', $info);
566
567
        return [$result, $info];
568
    }
569
}
570