Failed Conditions
Push — dev/recommend-plugins ( 237cf5 )
by Kiyotaka
07:46
created

PluginApiService::getRecommended()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 9
Ratio 100 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 9
loc 9
rs 9.9666
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\Service;
15
16
use Eccube\Common\Constant;
17
use Eccube\Common\EccubeConfig;
18
use Eccube\Entity\BaseInfo;
19
use Eccube\Entity\Plugin;
20
use Eccube\Exception\PluginApiException;
21
use Eccube\Repository\BaseInfoRepository;
22
use Eccube\Repository\PluginRepository;
23
use Symfony\Component\HttpFoundation\RequestStack;
24
25
class PluginApiService
26
{
27
    /**
28
     * Url for Api
29
     *
30
     * @var string
31
     */
32
    private $apiUrl;
33
34
    /**
35
     * @var EccubeConfig
36
     */
37
    private $eccubeConfig;
38
39
    /**
40
     * @var RequestStack
41
     */
42
    private $requestStack;
43
44
    /**
45
     * @var BaseInfo
46
     */
47
    private $BaseInfo;
48
    /**
49
     * @var PluginRepository
50
     */
51
    private $pluginRepository;
52
    /**
53
     * @var PluginService
54
     */
55
    private $pluginService;
56
57
    /**
58
     * PluginApiService constructor.
59
     *
60
     * @param EccubeConfig $eccubeConfig
61
     * @param RequestStack $requestStack
62
     * @param BaseInfoRepository $baseInfoRepository
63
     *
64
     * @param PluginRepository $pluginRepository
65
     * @param PluginService $pluginService
66
     * @throws \Doctrine\ORM\NoResultException
67
     * @throws \Doctrine\ORM\NonUniqueResultException
68
     */
69 View Code Duplication
    public function __construct(EccubeConfig $eccubeConfig, RequestStack $requestStack, BaseInfoRepository $baseInfoRepository, PluginRepository $pluginRepository, PluginService $pluginService)
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...
70
    {
71
        $this->eccubeConfig = $eccubeConfig;
72
        $this->requestStack = $requestStack;
73
        $this->BaseInfo = $baseInfoRepository->get();
74
        $this->pluginRepository = $pluginRepository;
75
        $this->pluginService = $pluginService;
76
    }
77
78
    /**
79
     * @return mixed
80
     */
81
    public function getApiUrl()
82
    {
83
        if (empty($this->apiUrl)) {
84
            return $this->eccubeConfig->get('eccube_package_api_url');
85
        }
86
87
        return $this->apiUrl;
88
    }
89
90
    /**
91
     * @param mixed $apiUrl
92
     */
93
    public function setApiUrl($apiUrl)
94
    {
95
        $this->apiUrl = $apiUrl;
96
    }
97
98
    /**
99
     * Get master data: category
100
     *
101
     * @return array
102
     * @throws PluginApiException
103
     */
104
    public function getCategory()
105
    {
106
        $urlCategory = $this->getApiUrl().'/category';
107
108
        return $this->getRequestApi($urlCategory);
109
    }
110
111
    /**
112
     * Get plugins list
113
     *
114
     * @param $data
115
     * @return array
116
     * @throws PluginApiException
117
     */
118
    public function getPlugins($data)
119
    {
120
        $url = $this->getApiUrl().'/plugins';
121
        $params['category_id'] = $data['category_id'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$params was never initialized. Although not strictly required by PHP, it is generally a good practice to add $params = 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...
122
        $params['price_type'] = empty($data['price_type']) ? 'all' : $data['price_type'];
123
        $params['keyword'] = $data['keyword'];
124
        $params['sort'] = $data['sort'];
125
        $params['page'] = (isset($data['page_no']) && !empty($data['page_no'])) ? $data['page_no'] : 1;
126
        $params['per_page'] = (isset($data['page_count']) && !empty($data['page_count'])) ? $data['page_count'] : $this->eccubeConfig->get('eccube_default_page_count');
127
128
        $payload = $this->getRequestApi($url, $params);
129
        $data = json_decode($payload, true);
130
131
        if (isset($data['plugins'])) {
132
            $this->buildPlugins($data['plugins']);
133
        }
134
135
        return $data;
136
    }
137
138
    /**
139
     * Get purchased plugins list
140
     *
141
     * @return array
142
     * @throws PluginApiException
143
     */
144 View Code Duplication
    public function getPurchased()
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...
145
    {
146
        $url = $this->getApiUrl().'/plugins/purchased';
147
148
        $payload = $this->getRequestApi($url);
149
        $plugins = json_decode($payload, true);
150
151
        return $this->buildPlugins($plugins);
152
    }
153
154
    /**
155
     * Get recommended plugins list
156
     *
157
     * @return array($result, $info)
0 ignored issues
show
Documentation introduced by
The doc-type array($result, could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
158
     * @throws PluginApiException
159
     */
160 View Code Duplication
    public function getRecommended()
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...
161
    {
162
        $url = $this->getApiUrl().'/plugins/recommended';
163
164
        $payload = $this->getRequestApi($url);
165
        $plugins = json_decode($payload, true);
166
167
        return $this->buildPlugins($plugins);
168
    }
169
170
    private function buildPlugins(&$plugins)
171
    {
172
        /** @var Plugin[] $pluginInstalled */
173
        $pluginInstalled = $this->pluginRepository->findAll();
174
        // Update_status 1 : not install/purchased 、2 : Installed、 3 : Update、4 : not purchased
175
        foreach ($plugins as &$item) {
176
            // Not install/purchased
177
            $item['update_status'] = 1;
178
            foreach ($pluginInstalled as $plugin) {
179
                if ($plugin->getSource() == $item['id']) {
180
                    // Installed
181
                    $item['update_status'] = 2;
182
                    if ($this->pluginService->isUpdate($plugin->getVersion(), $item['version'])) {
183
                        // Need update
184
                        $item['update_status'] = 3;
185
                    }
186
                }
187
            }
188
            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...
189
                // Not purchased with paid items
190
                $item['update_status'] = 4;
191
            }
192
193
            $item = $this->pluginService->buildInfo($item);
194
            $items[] = $item;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$items was never initialized. Although not strictly required by PHP, it is generally a good practice to add $items = 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...
195
        }
196
197
        return $plugins;
198
    }
199
200
    /**
201
     * Get a plugin
202
     *
203
     * @param int|string $id Id or plugin code
204
     *
205
     * @return array
206
     * @throws PluginApiException
207
     */
208
    public function getPlugin($id)
209
    {
210
        $url = $this->getApiUrl().'/plugin/'.$id;
211
212
        $payload = $this->getRequestApi($url);
213
        $json = json_decode($payload, true);
214
        return $this->pluginService->buildInfo($json);
215
    }
216
217
    /**
218
     * API request processing
219
     *
220
     * @param string $url
221
     * @param array $data
222
     *
223
     * @return array
224
     * @throws PluginApiException
225
     */
226
    public function getRequestApi($url, $data = [])
227
    {
228
        if (count($data) > 0) {
229
            $url .= '?'.http_build_query($data);
230
        }
231
232
        $curl = curl_init($url);
233
234
        $key = $this->BaseInfo->getAuthenticationKey();
235
        $baseUrl = $this->requestStack->getCurrentRequest()->getSchemeAndHttpHost().$this->requestStack->getCurrentRequest()->getBasePath();
236
237
        // Option array
238
        $options = [
239
            // HEADER
240
            CURLOPT_HTTPHEADER => [
241
                'X-ECCUBE-KEY: '.$key,
242
                'X-ECCUBE-URL: '.$baseUrl,
243
                'X-ECCUBE-VERSION: '.Constant::VERSION,
244
            ],
245
            CURLOPT_HTTPGET => true,
246
            CURLOPT_SSL_VERIFYPEER => false,
247
            CURLOPT_RETURNTRANSFER => true,
248
            CURLOPT_FAILONERROR => true,
249
            CURLOPT_CAINFO => \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(),
250
        ];
251
252
        // Set option value
253
        curl_setopt_array($curl, $options);
254
        $result = curl_exec($curl);
255
        $info = curl_getinfo($curl);
256
        $message = curl_error($curl);
257
        $info['message'] = $message;
258
        curl_close($curl);
259
260
        log_info('http get_info', $info);
261
262
        if ($info['http_code'] !== 200) {
263
            throw new PluginApiException($info);
264
        }
265
266
        return $result;
267
    }
268
}
269