Completed
Pull Request — experimental/3.1 (#2570)
by
unknown
40:15
created

OwnerStoreController::getRequestApi()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 16
nc 1
nop 2
dl 0
loc 26
ccs 0
cts 1
cp 0
crap 2
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
25
namespace Eccube\Controller\Admin\Store;
26
27
use Eccube\Annotation\Inject;
28
use Eccube\Application;
29
use Eccube\Common\Constant;
30
use Eccube\Controller\AbstractController;
31
use Eccube\Entity\Plugin;
32
use Eccube\Repository\PluginRepository;
33
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
34
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
35
use Symfony\Component\Config\Definition\Exception\Exception;
36
use Symfony\Component\HttpFoundation\RedirectResponse;
37
use Symfony\Component\HttpFoundation\Request;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39
use Symfony\Component\Process\Process;
40
41
/**
42
 * @Route(service=OwnerStoreController::class)
43
 */
44
class OwnerStoreController extends AbstractController
45
{
46
    /**
47
     * @Inject("config")
48
     * @var array
49
     */
50
    protected $appConfig;
51
52
    /**
53
     * @Inject(PluginRepository::class)
54
     * @var PluginRepository
55
     */
56
    protected $pluginRepository;
57
58
    /**
59
     * Owner's Store Plugin Installation Screen - Search function
60
     *
61
     * @Route("/{_admin}/store/plugin/search", name="admin_store_plugin_owners_search")
62
     * @Template("Store/plugin_search.twig")
63
     * @param Application $app
64
     * @param Request     $request
65
     * @return array
66
     */
67
    public function search(Application $app, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
68
    {
69
        // Acquire downloadable plug-in information from owners store
70
        $success = 0;
71
        $items = array();
72
        $promotionItems = array();
73
        $message = '';
74
        // Owner's store communication
75
        $url = $this->appConfig['owners_store_url'].'?method=list';
76
        list($json, $info) = $this->getRequestApi($url, $app);
77
        if ($json === false) {
78
            $message = $this->getResponseErrorMessage($info);
79
        } else {
80
            $data = json_decode($json, true);
81
            if (isset($data['success'])) {
82
                $success = $data['success'];
83
                if ($success == '1') {
84
                    $items = array();
85
                    // Check plugin installed
86
                    $arrPluginInstalled = $this->pluginRepository->findAll();
87
                    // Update_status 1 : not install/purchased 、2 : Installed、 3 : Update、4 : paid purchase
88
                    foreach ($data['item'] as $item) {
89
                        // Not install/purchased
90
                        $item['update_status'] = 1;
91
                        /** @var Plugin $plugin */
92
                        foreach ($arrPluginInstalled as $plugin) {
93
                            if ($plugin->getSource() == $item['product_id']) {
94
                                // Need update
95
                                $item['update_status'] = 3;
96
                                if ($plugin->getVersion() == $item['version']) {
97
                                    // Installed
98
                                    $item['update_status'] = 2;
99
                                }
100
                            }
101
                        }
102
                        $items[] = $item;
103
                    }
104
105
                    // EC-CUBE version check
106 View Code Duplication
                    foreach ($items as &$item) {
107
                        // Not applicable version
108
                        $item['version_check'] = 0;
109
                        if (in_array(Constant::VERSION, $item['eccube_version'])) {
110
                            // Match version
111
                            $item['version_check'] = 1;
112
                        }
113
                        if ($item['price'] != '0' && $item['purchased'] == '0') {
114
                            // Not purchased with paid items
115
                            $item['update_status'] = 4;
116
                        }
117
                    }
118
                    unset($item);
119
120
                    // Promotion item
121
                    $i = 0;
122 View Code Duplication
                    foreach ($items as $item) {
123
                        if ($item['promotion'] == 1) {
124
                            $promotionItems[] = $item;
125
                            unset($items[$i]);
126
                        }
127
                        $i++;
128
                    }
129
                } else {
130
                    $message = $data['error_code'] . ' : ' . $data['error_message'];
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
131
                }
132
            } else {
133
                $success = 0;
134
                $message = "EC-CUBEオーナーズストアにエラーが発生しています。";
135
            }
136
        }
137
138
        return [
139
            'success' => $success,
140
            'items' => $items,
141
            'promotionItems' => $promotionItems,
142
            'message' => $message,
143
        ];
144
    }
145
146
    /**
147
     * Do confirm page
148
     *
149
     * @Route("/{_admin}/store/plugin/confirm/{pluginId}" , name="admin_store_plugin_install_confirm")
150
     * @Template("Store/plugin_confirm.twig")
151
     * @param Application $application
152
     * @param Request     $request
153
     * @param string      $pluginId
154
     * @return array
155
     */
156
    public function doConfirm(Application $application, Request $request, $pluginId)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
157
    {
158
        // Owner's store communication
159
        $url = $this->appConfig['owners_store_url'].'?method=list';
160
        list($json, $info) = $this->getRequestApi($url, $application);
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...
161
        $data = json_decode($json, true);
162
        $items = $data['item'];
163
164
        // Find plugin
165
        $index = array_search($pluginId, array_column($items, 'product_id'));
166
        if ($index === false) {
167
            throw new NotFoundHttpException();
168
        }
169
170
        $arrPlugin = [];
171
172
        $plugin = $items[$index];
173
        $plugin['version_check'] = 0;
174
        if (in_array(Constant::VERSION, $plugin['eccube_version'])) {
175
            // Match version
176
            $plugin['version_check'] = 1;
177
        }
178
        $arrPlugin[] = $plugin;
179
180
        return [
181
            'items' => $arrPlugin,
182
        ];
183
    }
184
185
    /**
186
     * Api Install plugin by composer connect with package repo
187
     *
188
     * @Route("/{_admin}/store/plugin/api/{pluginCode}/{eccubeVersion}/{version}" , name="admin_store_plugin_api_install")
189
     *
190
     * @param Application $app
191
     * @param Request     $request
192
     * @param string      $pluginCode
193
     * @param string      $eccubeVersion
194
     * @param string      $version
195
     * @return RedirectResponse
196
     */
197
    public function apiInstall(Application $app, Request $request, $pluginCode, $eccubeVersion, $version)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
198
    {
199
        // Check plugin code
200
        $url = $this->appConfig['owners_store_url'].'?eccube_version='.$eccubeVersion.'&plugin_code='.$pluginCode.'&version='.$version;
201
        list($json, $info) = $this->getRequestApi($url, $app);
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...
202
        $existFlg = false;
203
        $data = json_decode($json, true);
204
        if ($data && isset($data['success'])) {
205
            $success = $data['success'];
206
            if ($success == '1') {
207
                foreach ($data['item'] as $item) {
208
                    if ($item['product_code'] == $pluginCode) {
209
                        $existFlg = true;
210
                        break;
211
                    }
212
                }
213
            }
214
        }
215
        if ($existFlg === false) {
216
            $app->log(sprintf('%s plugin not found!', $pluginCode));
217
            $app->addError('admin.plugin.not.found', 'admin');
218
219
            return $app->redirect($app->url('admin_store_plugin_owners_search'));
220
        }
221
222
        try {
223
            $execute = sprintf('cd %s &&', $this->appConfig['root_dir']);
224
            $execute .= sprintf(' composer require ec-cube/%s', $pluginCode);
225
226
            $install = new Process($execute);
227
            $install->setTimeout(null);
228
            $install->run();
229
            if ($install->isSuccessful()) {
230
                $app->addSuccess('admin.plugin.install.complete', 'admin');
231
                $app->log(sprintf('Install %s plugin successful!', $pluginCode));
232
233
                return $app->redirect($app->url('admin_store_plugin'));
234
            }
235
            $app->addError('admin.plugin.install.fail', 'admin');
236
        } catch (Exception $exception) {
237
            $app->addError($exception->getMessage(), 'admin');
238
            $app->log($exception->getCode().' : '.$exception->getMessage());
239
        }
240
        $app->log(sprintf('Install %s plugin fail!', $pluginCode));
241
242
        return $app->redirect($app->url('admin_store_plugin_owners_search'));
243
    }
244
245
    /**
246
     * API request processing
247
     *
248
     * @param string  $url
249
     * @param Application $app
250
     * @return array
251
     */
252
    private function getRequestApi($url, $app)
253
    {
254
        $curl = curl_init($url);
255
256
        // Option array
257
        $options = array(
258
            // HEADER
259
            CURLOPT_HTTPGET => true,
260
            CURLOPT_SSL_VERIFYPEER => false,
261
            CURLOPT_RETURNTRANSFER => true,
262
            CURLOPT_FAILONERROR => true,
263
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
264
        );
265
266
        // Set option value
267
        curl_setopt_array($curl, $options);
268
        $result = curl_exec($curl);
269
        $info = curl_getinfo($curl);
270
        $message = curl_error($curl);
271
        $info['message'] = $message;
272
        curl_close($curl);
273
274
        $app->log('http get_info', $info);
275
276
        return array($result, $info);
277
    }
278
279
    /**
280
     * Get message
281
     *
282
     * @param $info
283
     * @return string
284
     */
285 View Code Duplication
    private function getResponseErrorMessage($info)
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...
286
    {
287
        if (!empty($info)) {
288
            $statusCode = $info['http_code'];
289
            $message = $info['message'];
290
291
            $message = $statusCode.' : '.$message;
292
        } else {
293
            $message = "タイムアウトエラーまたはURLの指定に誤りがあります。";
294
        }
295
296
        return $message;
297
    }
298
}
299