Update::updateSubSeller()   C
last analyzed

Complexity

Conditions 12
Paths 16

Size

Total Lines 74
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 47
c 1
b 0
f 0
dl 0
loc 74
rs 6.9666
cc 12
nc 16
nop 1

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
 * Copyright © Getnet. All rights reserved.
4
 *
5
 * @author    Bruno Elisei <[email protected]>
6
 * See LICENSE for license details.
7
 */
8
9
declare(strict_types=1);
10
11
namespace Getnet\SubSellerMagento\Model\Console\Command\Synchronize;
12
13
use Exception;
14
use Getnet\SubSellerMagento\Api\SubSellerRepositoryInterface;
15
use Getnet\SubSellerMagento\Helper\Data as GetnetHelper;
16
use Getnet\SubSellerMagento\Logger\Logger;
17
use Getnet\SubSellerMagento\Model\Config as GetnetConfig;
18
use Getnet\SubSellerMagento\Model\Console\Command\AbstractModel;
19
use Magento\Framework\App\State;
20
use Magento\Framework\Exception\LocalizedException;
21
use Magento\Framework\HTTP\ZendClient;
22
use Magento\Framework\HTTP\ZendClientFactory;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\HTTP\ZendClientFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
23
use Magento\Framework\Serialize\Serializer\Json;
24
25
/**
26
 * Class Update Sub Seller on Getnet.
27
 */
28
class Update extends AbstractModel
29
{
30
    /**
31
     * @var State
32
     */
33
    protected $state;
34
35
    /**
36
     * @var Logger
37
     */
38
    protected $logger;
39
40
    /**
41
     * @var GetnetConfig
42
     */
43
    protected $getnetConfig;
44
45
    /**
46
     * @var GetnetHelper
47
     */
48
    protected $getnetHelper;
49
50
    /**
51
     * @var SubSellerRepositoryInterface
52
     */
53
    protected $subSellerRepository;
54
55
    /**
56
     * @var Json
57
     */
58
    protected $json;
59
60
    /**
61
     * @var ZendClientFactory
62
     */
63
    protected $httpClientFactory;
64
65
    /**
66
     * @param State                        $state
67
     * @param Logger                       $logger
68
     * @param GetnetConfig                 $getnetConfig
69
     * @param GetnetHelper                 $getnetHelper
70
     * @param SubSellerRepositoryInterface $subSellerRepository
71
     * @param Json                         $json
72
     * @param ZendClientFactory            $httpClientFactory
73
     */
74
    public function __construct(
75
        State $state,
76
        Logger $logger,
77
        GetnetConfig $getnetConfig,
78
        GetnetHelper $getnetHelper,
79
        SubSellerRepositoryInterface $subSellerRepository,
80
        Json $json,
81
        ZendClientFactory $httpClientFactory
82
    ) {
83
        $this->state = $state;
84
        $this->logger = $logger;
85
        $this->getnetConfig = $getnetConfig;
86
        $this->getnetHelper = $getnetHelper;
87
        $this->subSellerRepository = $subSellerRepository;
88
        $this->json = $json;
89
        $this->httpClientFactory = $httpClientFactory;
90
    }
91
92
    /**
93
     * Command Preference.
94
     *
95
     * @param int $subSellerId
96
     *
97
     * @return void
98
     */
99
    public function update(int $subSellerId)
100
    {
101
        $this->writeln('Init Sync Sub Seller');
102
        $this->updateSubSeller($subSellerId);
103
        $this->writeln(__('Finished'));
104
    }
105
106
    /**
107
     * Update Sub Seller.
108
     *
109
     * @param int $subSellerId
110
     *
111
     * @return void
112
     * @SuppressWarnings(PHPMD.NPathComplexity)
113
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
114
     */
115
    protected function updateSubSeller(int $subSellerId)
116
    {
117
        try {
118
            $subSeller = $this->subSellerRepository->get($subSellerId);
119
        } catch (LocalizedException $exc) {
120
            $this->writeln('<error>'.$exc->getMessage().'</error>');
121
122
            return;
123
        }
124
125
        if ($subSeller->getId()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $subSeller->getId() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. 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...
126
            $typePersona = (bool) $subSeller->getType();
127
            if (!$subSeller->getIdExt()) {
128
                $messageErrors = __('The Sub Seller does not have a relationship id on Getnet');
129
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
130
            }
131
132
            $messageInfo = __('Send Sub Seller internal code: %1', $subSeller->getCode());
133
            $this->writeln(sprintf('<info>%s</info>', $messageInfo));
134
            $formatedData = $this->getnetHelper->formatedData($subSeller, $typePersona, 'seller_update');
135
            $this->writeln($this->json->serialize($formatedData));
136
            $response = $this->updateData($formatedData, $typePersona, (int) $subSeller->getStatus());
137
138
            if ($response->getErrors()) {
139
                foreach ($response->getErrors() as $error) {
140
                    $errors[] = $error;
141
                }
142
                $listErrors = implode(', ', $errors);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $errors seems to be defined by a foreach iteration on line 139. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
143
                $messageErrors = __('Could not update registration, errors found: %1', $listErrors);
144
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
145
146
                return;
147
            }
148
149
            if ($response->getMessage()) {
150
                $errors[] = $response->getMessage();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$errors was never initialized. Although not strictly required by PHP, it is generally a good practice to add $errors = array(); before regardless.
Loading history...
151
                if (is_array($response->getMessage())) {
152
                    unset($errors);
153
                    foreach ($response->getMessage() as $key => $error) {
154
                        foreach ($error as $typeError) {
155
                            $errors[] = $typeError.' field '.$key;
156
                        }
157
                    }
158
                }
159
                $listErrors = implode(', ', $errors);
160
                $messageErrors = __('Could not update registration, errors found: %1', $listErrors);
161
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
162
163
                return;
164
            }
165
166
            if ($response->getSuccess()) {
167
                $this->writeln('<info>Done!</info>');
168
169
                return;
170
            }
171
172
            if ($response->getSubsellerId()) {
173
                $messageResponse = __(
174
                    'Success, the sub seller id: %1, enable to sales: %2, id getnet: %3',
175
                    $response->getSubsellerId(),
176
                    $response->getEnabled()
177
                );
178
                $this->writeln(sprintf('<info>%s</info>', $messageResponse));
179
180
                return;
181
            }
182
183
            $messageErrorConection = __('Connection Error: %1', json_encode($response));
184
            $this->writeln(sprintf('<error>%s</error>', $messageErrorConection));
185
186
            return;
187
        }
188
        $this->writeln('<error>'.__('Error').'</error>');
189
    }
190
191
    /**
192
     * Update Data.
193
     *
194
     * @param array $sellerFomarted
195
     * @param bool  $typePersona
196
     * @param int   $status
197
     *
198
     * @return \Magento\Framework\DataObject
199
     */
200
    protected function updateData(
201
        array $sellerFomarted,
202
        bool $typePersona,
203
        int $status
204
    ): \Magento\Framework\DataObject {
205
        $uri = $this->getnetConfig->getUri();
206
        $bearer = $this->getnetConfig->getAuth();
207
        $client = $this->httpClientFactory->create();
208
        $send = $this->json->serialize($sellerFomarted);
209
        $client->setUri($uri.'v1/mgm/pf/update-subseller');
210
211
        if ($typePersona) {
212
            $client->setUri($uri.'v1/mgm/pj/update-subseller');
213
        }
214
215
        if ($status === 5) {
216
            $client->setUri($uri.'v1/mgm/pf/complement');
217
218
            if ($typePersona) {
219
                $client->setUri($uri.'v1/mgm/pj/complement');
220
            }
221
        }
222
223
        $client->setHeaders('Authorization', 'Bearer '.$bearer);
224
        $client->setConfig(['maxredirects' => 0, 'timeout' => 40]);
225
        $client->setRawData($send, 'application/json');
226
        $client->setMethod(ZendClient::PUT);
227
        $getnetData = new \Magento\Framework\DataObject();
228
229
        try {
230
            $result = $client->request()->getBody();
231
            $response = $this->json->unserialize($result);
232
233
            $this->logger->info(
234
                $this->json->serialize([
235
                    'send'     => $send,
236
                    'response' => $response,
237
                ])
238
            );
239
240
            if (isset($response['status_code'])) {
241
                return $getnetData->setDetails($response['details']);
242
            }
243
244
            if (isset($response['Message'])) {
245
                if (isset($response['ModelState'])) {
246
                    $getnetData->setMessage($response['ModelState']);
247
248
                    return $getnetData;
249
                }
250
                $getnetData->setMessage($response['Message']);
251
            }
252
253
            if (isset($response['success'])) {
254
                $getnetData->setSuccess(true);
255
256
                return $getnetData;
257
            }
258
259
            $getnetData->setData($result);
260
261
            return $getnetData;
262
        } catch (Exception $e) {
263
            $this->logger->info($this->json->serialize(['error' => $e->getMessage()]));
264
265
            return $getnetData->setDetails($e->getMessage());
266
        }
267
    }
268
}
269