Refresh::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 10
c 2
b 0
f 0
nc 1
nop 9
dl 0
loc 22
rs 9.9332

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\PaymentMagento\Model\Console\Command\Basic;
12
13
use Exception;
14
use Getnet\PaymentMagento\Gateway\Config\Config as GetnetConfig;
15
use Getnet\PaymentMagento\Model\Console\Command\AbstractModel;
16
use Magento\Config\Model\ResourceModel\Config;
17
use Magento\Framework\App\Cache\Frontend\Pool;
18
use Magento\Framework\App\Cache\TypeListInterface;
19
use Magento\Framework\App\State;
20
use Magento\Framework\HTTP\ZendClient;
21
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...
22
use Magento\Framework\Serialize\Serializer\Json;
23
use Magento\Payment\Model\Method\Logger;
24
use Magento\Store\Model\ScopeInterface;
25
use Magento\Store\Model\StoreManagerInterface;
26
27
/**
28
 * Class Refresh Token.
29
 *
30
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
31
 */
32
class Refresh extends AbstractModel
33
{
34
    /**
35
     * @var TypeListInterface
36
     */
37
    protected $cacheTypeList;
38
39
    /**
40
     * @var Pool
41
     */
42
    protected $cacheFrontendPool;
43
44
    /**
45
     * @var State
46
     */
47
    protected $state;
48
49
    /**
50
     * @var GetnetConfig
51
     */
52
    protected $getnetConfig;
53
54
    /**
55
     * @var Config
56
     */
57
    protected $config;
58
59
    /**
60
     * @var StoreManagerInterface
61
     */
62
    protected $storeManager;
63
64
    /**
65
     * @var Json
66
     */
67
    protected $json;
68
69
    /**
70
     * @var ZendClientFactory
71
     */
72
    protected $httpClientFactory;
73
74
    /**
75
     * @param TypeListInterface     $cacheTypeList
76
     * @param Pool                  $cacheFrontendPool
77
     * @param Logger                $logger
78
     * @param State                 $state
79
     * @param GetnetConfig          $getnetConfig
80
     * @param Config                $config
81
     * @param StoreManagerInterface $storeManager
82
     * @param Json                  $json
83
     * @param ZendClientFactory     $httpClientFactory
84
     */
85
    public function __construct(
86
        TypeListInterface $cacheTypeList,
87
        Pool $cacheFrontendPool,
88
        Logger $logger,
89
        State $state,
90
        GetnetConfig $getnetConfig,
91
        Config $config,
92
        StoreManagerInterface $storeManager,
93
        Json $json,
94
        ZendClientFactory $httpClientFactory
95
    ) {
96
        parent::__construct(
97
            $logger
98
        );
99
        $this->cacheTypeList = $cacheTypeList;
100
        $this->cacheFrontendPool = $cacheFrontendPool;
101
        $this->state = $state;
102
        $this->getnetConfig = $getnetConfig;
103
        $this->config = $config;
104
        $this->storeManager = $storeManager;
105
        $this->json = $json;
106
        $this->httpClientFactory = $httpClientFactory;
107
    }
108
109
    /**
110
     * Command Preference.
111
     *
112
     * @param int|null $storeId
113
     *
114
     * @return void
115
     */
116
    public function newToken($storeId = null)
117
    {
118
        $storeIds = $storeId ?: null;
119
        $this->writeln('Init Referesh Token');
120
        if (!$storeIds) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $storeIds of type integer|null is loosely compared to false; 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...
121
            foreach ($this->storeManager->getStores() as $stores) {
122
                $storeId = (int) $stores->getId();
123
                $this->storeManager->setCurrentStore($stores);
124
                $webSiteId = (int) $stores->getWebsiteId();
125
                $this->writeln(__('For Store Id %1 Web Site Id %2', $storeId, $webSiteId));
126
                $this->createNewToken($storeId, $webSiteId);
127
            }
128
        }
129
        $this->writeln(__('Finished'));
130
    }
131
132
    /**
133
     * Create New Token.
134
     *
135
     * @param int $storeId
136
     * @param int $webSiteId
137
     *
138
     * @return void
139
     */
140
    protected function createNewToken(int $storeId = 0, int $webSiteId = 0)
141
    {
142
        $newToken = $this->getNewToken($storeId);
143
        if ($newToken['success']) {
144
            $token = $newToken['response'];
145
            if (isset($token['access_token'])) {
146
                $registryConfig = $this->setNewToken($token['access_token'], $storeId, $webSiteId);
147
                if ($registryConfig['success']) {
148
                    $this->cacheTypeList->cleanType('config');
149
150
                    // phpcs:ignore Generic.Files.LineLength
151
                    $this->writeln('<info>'.__('Token Refresh Successfully.').'</info>');
152
153
                    return;
154
                }
155
                // phpcs:ignore Generic.Files.LineLength
156
                $this->writeln('<error>'.__('Error saving information in database: %1', $registryConfig['error']).'</error>');
157
            }
158
            // phpcs:ignore Generic.Files.LineLength
159
            $this->writeln('<error>'.__('Refresh Token Error: %1', $token['error_description']).'</error>');
160
161
            return;
162
        }
163
        $this->writeln('<error>'.__('Token update request error: %1', $newToken['error']).'<error>');
164
    }
165
166
    /**
167
     * Get New Token.
168
     *
169
     * @param int $storeId
170
     *
171
     * @return array
172
     */
173
    protected function getNewToken(int $storeId = 0): array
174
    {
175
        $uri = $this->getnetConfig->getApiUrl($storeId);
176
        $clientId = $this->getnetConfig->getMerchantGatewayClientId($storeId);
177
        $clientSecret = $this->getnetConfig->getMerchantGatewayClientSecret($storeId);
178
        $dataSend = [
179
            'scope'      => 'oob',
180
            'grant_type' => 'client_credentials',
181
        ];
182
        $client = $this->httpClientFactory->create();
183
        $client->setUri($uri.'auth/oauth/v2/token');
184
        $client->setAuth($clientId, $clientSecret);
185
        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
186
        $client->setHeaders(['content' => 'application/x-www-form-urlencoded']);
187
        $client->setParameterPost($dataSend);
188
        $client->setMethod(ZendClient::POST);
189
190
        try {
191
            $result = $client->request()->getBody();
192
            $response = $this->json->unserialize($result);
193
            $this->logger->debug(['response' => $response]);
194
195
            return [
196
                'success'    => true,
197
                'response'   => $response,
198
            ];
199
        } catch (Exception $e) {
200
            $this->logger->debug(['error' => $e->getMessage()]);
201
202
            return ['success' => false, 'error' =>  $e->getMessage()];
203
        }
204
    }
205
206
    /**
207
     * Set New Token.
208
     *
209
     * @param string $token
210
     * @param int    $storeId
211
     * @param int    $webSiteId
212
     *
213
     * @return array
214
     */
215
    protected function setNewToken(string $token, int $storeId = 0, int $webSiteId = 0): array
216
    {
217
        $environment = $this->getnetConfig->getEnvironmentMode($storeId);
218
        $pathPattern = 'payment/getnet_paymentmagento/%s_%s';
219
        $pathConfigId = sprintf($pathPattern, 'access_token', $environment);
220
221
        try {
222
            $this->config->saveConfig(
223
                $pathConfigId,
224
                $token,
225
                ScopeInterface::SCOPE_WEBSITES,
226
                $webSiteId
227
            );
228
        } catch (Exception $e) {
229
            return ['success' => false, 'error' => $e->getMessage()];
230
        }
231
232
        return ['success' => true];
233
    }
234
}
235