Create::createSubSeller()   C
last analyzed

Complexity

Conditions 13
Paths 10

Size

Total Lines 90
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 61
c 1
b 0
f 0
dl 0
loc 90
rs 6.6166
cc 13
nc 10
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 Create Sub Seller on Getnet.
27
 */
28
class Create 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 create(int $subSellerId)
100
    {
101
        $this->writeln('Init Sync Sub Seller');
102
        $this->createSubSeller($subSellerId);
103
        $this->writeln(__('Finished'));
104
    }
105
106
    /**
107
     * Create Sub Seller.
108
     *
109
     * @param int $subSellerId
110
     *
111
     * @return void
112
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
113
     * @SuppressWarnings(PHPMD.NPathComplexity)
114
     * phpcs:disable Generic.Metrics.NestingLevel
115
     */
116
    protected function createSubSeller(int $subSellerId)
117
    {
118
        try {
119
            $subSeller = $this->subSellerRepository->get($subSellerId);
120
        } catch (LocalizedException $exc) {
121
            $this->writeln('<error>'.$exc->getMessage().'</error>');
122
123
            return;
124
        }
125
126
        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...
127
            $typePersona = (bool) $subSeller->getType();
128
            if ($subSeller->getIdExt()) {
129
                $messageErrors = __('O Sub Seller já possuí id de relacionamento na Getnet');
130
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
131
132
                return;
133
            }
134
135
            $formatedData = $this->getnetHelper->formatedData($subSeller, $typePersona);
136
            $messageInfo = __('Send Sub Seller internal code: %1', $subSeller->getCode());
137
            $this->writeln(sprintf('<info>%s</info>', $messageInfo));
138
            $this->writeln($this->json->serialize($formatedData));
139
            $response = $this->sendData($formatedData, $typePersona);
140
141
            if ($response->getErrors()) {
142
                foreach ($response->getErrors() as $error) {
143
                    $errors[] = $error;
144
                }
145
                $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 142. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
146
147
                $subSeller->setStatus('4');
148
                $subSeller->setStatusComment($listErrors);
149
                $subSeller->save();
0 ignored issues
show
Bug introduced by
The method save() does not exist on Getnet\SubSellerMagento\...Data\SubSellerInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to Getnet\SubSellerMagento\...Data\SubSellerInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

149
                $subSeller->/** @scrutinizer ignore-call */ 
150
                            save();
Loading history...
150
                $messageErrors = __('Unable to register, errors found: %1', $listErrors);
151
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
152
153
                return;
154
            }
155
156
            if ($response->getMessage()) {
157
                $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...
158
                if (is_array($response->getMessage())) {
159
                    unset($errors);
160
                    foreach ($response->getMessage() as $key => $error) {
161
                        $errors[] = $error;
162
                        if (is_array($error)) {
163
                            unset($errors);
164
                            foreach ($error as $typeError) {
165
                                $errors[] = $typeError.' field '.$key;
166
                            }
167
                        }
168
                    }
169
                }
170
                $listErrors = implode(', ', $errors);
171
                $subSeller->setStatus('5');
172
                $subSeller->setStatusComment($listErrors);
173
                $subSeller->save();
174
                $messageErrors = __('Unable to register, errors found: %1', $listErrors);
175
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
176
177
                return;
178
            }
179
180
            if ($response->getSubsellerId()) {
181
                $subSeller->setIdExt($response->getSubsellerId());
182
                $subSeller->setStatus('2');
183
                $subSeller->setStatusComment('Waiting for registration approval.');
184
185
                if ($response->getEnabled() === 'S') {
186
                    $subSeller->setStatus('3');
187
                    $subSeller->setStatusComment('Authorized for sales.');
188
                }
189
190
                $subSeller->save();
191
                $messageResponse = __(
192
                    'Success, the sub seller id: %1, enable to sales: %2, id getnet: %3',
193
                    $response->getCode(),
194
                    $response->getEnabled(),
195
                    $response->getSubsellerId()
196
                );
197
                $this->writeln(sprintf('<info>%s</info>', $messageResponse));
198
199
                return;
200
            }
201
202
            $messageErrorConection = __('Connection Error: %1', $response->getDetails());
203
            $this->writeln(sprintf('<error>%s</error>', $messageErrorConection));
204
205
            return;
206
        }
207
    }
208
209
    /**
210
     * Send Data.
211
     *
212
     * @param array $sellerFomarted
213
     * @param bool  $typePersona
214
     *
215
     * @return \Magento\Framework\DataObject
216
     */
217
    protected function sendData(
218
        array $sellerFomarted,
219
        bool $typePersona
220
    ): \Magento\Framework\DataObject {
221
        $uri = $this->getnetConfig->getUri();
222
        $bearer = $this->getnetConfig->getAuth();
223
        $client = $this->httpClientFactory->create();
224
        $send = $this->json->serialize($sellerFomarted);
225
        $client->setUri($uri.'v1/mgm/pf/create-presubseller');
226
        if ($typePersona) {
227
            $client->setUri($uri.'v1/mgm/pj/create-presubseller');
228
        }
229
        $client->setHeaders('Authorization', 'Bearer '.$bearer);
230
        $client->setConfig(['maxredirects' => 0, 'timeout' => 40]);
231
        $client->setRawData($send, 'application/json');
232
        $client->setMethod(ZendClient::POST);
233
        $getnetData = new \Magento\Framework\DataObject();
234
235
        try {
236
            $result = $client->request()->getBody();
237
            $response = $this->json->unserialize($result);
238
            $this->logger->info(
239
                $this->json->serialize([
240
                    'send'     => $send,
241
                    'response' => $response,
242
                ])
243
            );
244
245
            if (isset($response['status_code'])) {
246
                return $getnetData->setDetails($response['details']);
247
            }
248
249
            if (isset($response['Message'])) {
250
                if (isset($response['ModelState'])) {
251
                    $getnetData->setMessage($response['ModelState']);
252
253
                    return $getnetData;
254
                }
255
                $getnetData->setMessage($response);
256
257
                return $getnetData;
258
            }
259
260
            $getnetData->setData($response);
261
262
            return $getnetData;
263
        } catch (Exception $e) {
264
            $this->logger->info($this->json->serialize(['error' => $e->getMessage()]));
265
266
            return $getnetData->setDetails($e->getMessage());
267
        }
268
    }
269
}
270