GetUpdateData::updateDataSubSeller()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 52
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 52
rs 8.7697
cc 6
nc 8
nop 1

How to fix   Long Method   

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 Data Sub Seller on Getnet.
27
 */
28
class GetUpdateData 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 getUpdateData(int $subSellerId)
100
    {
101
        $this->writeln('Init Sync Data Sub Seller');
102
        $this->updateDataSubSeller($subSellerId);
103
        $this->writeln(__('Finished'));
104
    }
105
106
    /**
107
     * Create Update Data.
108
     *
109
     * @param int $subSellerId
110
     *
111
     * @return void
112
     */
113
    protected function updateDataSubSeller(int $subSellerId)
114
    {
115
        try {
116
            $subSeller = $this->subSellerRepository->get($subSellerId);
117
        } catch (LocalizedException $exc) {
118
            $this->writeln('<error>'.$exc->getMessage().'</error>');
119
120
            return;
121
        }
122
123
        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...
124
            if (!$subSeller->getIdExt()) {
125
                $messageErrors = __('The Sub Seller does not have a relationship id on Getnet.');
126
                $this->writeln(sprintf('<error>%s</error>', $messageErrors));
127
            }
128
129
            $typePersona = (bool) $subSeller->getType();
130
            $legalDocument = preg_replace('/[^0-9]/', '', $subSeller->getLegalDocumentNumber());
131
132
            $messageInfo = __('Get Data to Sub Seller internal code: %1', $subSeller->getCode());
133
            $this->writeln(sprintf('<info>%s</info>', $messageInfo));
134
135
            $response = $this->getDataOnGetnet(
136
                $typePersona,
137
                $legalDocument,
138
                $subSeller->getMerchantId()
0 ignored issues
show
Bug introduced by
It seems like $subSeller->getMerchantId() can also be of type null; however, parameter $merchantId of Getnet\SubSellerMagento\...Data::getDataOnGetnet() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

138
                /** @scrutinizer ignore-type */ $subSeller->getMerchantId()
Loading history...
139
            );
140
141
            if ($response->getSubsellerId()) {
142
                if ($response->getEnabled() === 'S') {
143
                    $subSeller->setIdExt($response->getSubsellerId());
144
                    $subSeller->setStatus(3);
145
                    $subSeller->setStatusComment(null);
146
                    $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

146
                    $subSeller->/** @scrutinizer ignore-call */ 
147
                                save();
Loading history...
147
                }
148
149
                $messageResponse = __(
150
                    'Success, sub seller id: %1, enable to sale: %2',
151
                    $response->getSubsellerId(),
152
                    $response->getEnabled()
153
                );
154
                $this->writeln(sprintf('<info>%s</info>', $messageResponse));
155
156
                return;
157
            }
158
159
            $messageErrorConection = __('Error: %1', $response->getDetails());
160
            $this->writeln(sprintf('<error>%s</error>', $messageErrorConection));
161
162
            return;
163
        }
164
        $this->writeln('<error>'.__('Error').'</error>');
165
    }
166
167
    /**
168
     * Get Data On Getnet.
169
     *
170
     * @param bool   $typePersona
171
     * @param string $legalNumber
172
     * @param string $merchantId
173
     *
174
     * @return \Magento\Framework\DataObject
175
     */
176
    protected function getDataOnGetnet(
177
        bool $typePersona,
178
        string $legalNumber,
179
        string $merchantId
180
    ): \Magento\Framework\DataObject {
181
        $client = $this->httpClientFactory->create();
182
        $uriBase = $this->getnetConfig->getUri();
183
        $bearer = $this->getnetConfig->getAuth();
184
        $type = 'pf';
185
186
        if ($typePersona) {
187
            $type = 'pj';
188
        }
189
190
        $uri = sprintf('%sv1/mgm/%s/callback/%s/%s', $uriBase, $type, $merchantId, $legalNumber);
191
192
        $client->setUri($uri);
193
        $client->setHeaders('Authorization', 'Bearer '.$bearer);
194
        $client->setMethod(ZendClient::GET);
195
        $getnetData = new \Magento\Framework\DataObject();
196
197
        try {
198
            $result = $client->request()->getBody();
199
            $response = $this->json->unserialize($result);
200
            $getnetData->setData($response);
201
202
            return $getnetData;
203
        } catch (Exception $e) {
204
            $this->logger->info($this->json->serialize(['error' => $e->getMessage()]));
205
206
            return $getnetData->setDetails($e->getMessage());
207
        }
208
    }
209
}
210