Token::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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

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\SubSellerMagento\Model\Console\Command\Administrative;
12
13
use Exception;
14
use Getnet\SubSellerMagento\Helper\Data as GetnetHelper;
15
use Getnet\SubSellerMagento\Logger\Logger;
16
use Getnet\SubSellerMagento\Model\Config as GetnetConfig;
17
use Getnet\SubSellerMagento\Model\Console\Command\AbstractModel;
18
use Magento\Config\Model\ResourceModel\Config;
19
use Magento\Framework\App\Cache\Frontend\Pool;
20
use Magento\Framework\App\Cache\TypeListInterface;
21
use Magento\Framework\App\Config\ScopeConfigInterface;
22
use Magento\Framework\App\State;
23
use Magento\Framework\HTTP\ZendClient;
24
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...
25
use Magento\Framework\Serialize\Serializer\Json;
26
27
/**
28
 * Class Generate Token.
29
 */
30
class Token extends AbstractModel
31
{
32
    /**
33
     * @var TypeListInterface
34
     */
35
    protected $cacheTypeList;
36
37
    /**
38
     * @var Pool
39
     */
40
    protected $cacheFrontendPool;
41
42
    /**
43
     * @var ScopeConfigInterface
44
     */
45
    protected $scopeConfig;
46
47
    /**
48
     * @var State
49
     */
50
    protected $state;
51
52
    /**
53
     * @var GetnetConfig
54
     */
55
    protected $getnetConfig;
56
57
    /**
58
     * @var GetnetHelper
59
     */
60
    protected $getnetHelper;
61
62
    /**
63
     * @var Config
64
     */
65
    protected $config;
66
67
    /**
68
     * @var Json
69
     */
70
    protected $json;
71
72
    /**
73
     * @var ZendClientFactory
74
     */
75
    protected $httpClientFactory;
76
77
    /**
78
     * @param TypeListInterface    $cacheTypeList
79
     * @param Pool                 $cacheFrontendPool
80
     * @param Logger               $logger
81
     * @param ScopeConfigInterface $scopeConfig
82
     * @param State                $state
83
     * @param GetnetConfig         $getnetConfig
84
     * @param GetnetHelper         $getnetHelper
85
     * @param Config               $config
86
     * @param Json                 $json
87
     * @param ZendClientFactory    $httpClientFactory
88
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
89
     */
90
    public function __construct(
91
        TypeListInterface $cacheTypeList,
92
        Pool $cacheFrontendPool,
93
        Logger $logger,
94
        ScopeConfigInterface $scopeConfig,
95
        State $state,
96
        GetnetConfig $getnetConfig,
97
        GetnetHelper $getnetHelper,
0 ignored issues
show
Unused Code introduced by
The parameter $getnetHelper is not used and could be removed. ( Ignorable by Annotation )

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

97
        /** @scrutinizer ignore-unused */ GetnetHelper $getnetHelper,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
98
        Config $config,
99
        Json $json,
100
        ZendClientFactory $httpClientFactory
101
    ) {
102
        parent::__construct(
103
            $logger
104
        );
105
        $this->cacheTypeList = $cacheTypeList;
106
        $this->cacheFrontendPool = $cacheFrontendPool;
107
        $this->state = $state;
108
        $this->scopeConfig = $scopeConfig;
109
        $this->getnetConfig = $getnetConfig;
110
        $this->config = $config;
111
        $this->json = $json;
112
        $this->httpClientFactory = $httpClientFactory;
113
    }
114
115
    /**
116
     * Command Preference.
117
     *
118
     * @param int|null $storeId
119
     *
120
     * @return void
121
     */
122
    public function newToken($storeId = null)
123
    {
124
        $storeId = $storeId ?: 0;
125
        $this->writeln('Generate Administrative Token');
126
        $this->createNewToken($storeId);
127
        $this->writeln(__('Finished'));
128
    }
129
130
    /**
131
     * Create New Token.
132
     *
133
     * @param int $storeId
134
     *
135
     * @return void
136
     */
137
    private function createNewToken($storeId)
138
    {
139
        $newToken = $this->getNewToken();
140
        if ($newToken['success']) {
141
            $token = $newToken['response'];
142
            if (isset($token['access_token'])) {
143
                $registryConfig = $this->setNewToken($token['access_token'], $storeId);
144
                if ($registryConfig['success']) {
145
                    $this->cacheTypeList->cleanType('config');
146
147
                    // phpcs:ignore Generic.Files.LineLength
148
                    $this->writeln('<info>'.__('Token Refresh Successfully.').'</info>');
149
150
                    return;
151
                }
152
                // phpcs:ignore Generic.Files.LineLength
153
                $this->writeln('<error>'.__('Error saving information in database: %1', $registryConfig['error']).'</error>');
154
            }
155
            // phpcs:ignore Generic.Files.LineLength
156
            $this->writeln('<error>'.__('Refresh Token Error: %1', $token['error_description']).'</error>');
157
158
            return;
159
        }
160
        $this->writeln('<error>'.__('Token update request error: %1', $newToken['error']).'</error>');
161
    }
162
163
    /**
164
     * Get New Token.
165
     *
166
     * @return array
167
     */
168
    private function getNewToken(): array
169
    {
170
        $uri = $this->getnetConfig->getUri();
171
        $clientId = $this->getnetConfig->getMerchantGatewayClientId();
172
        $clientSecret = $this->getnetConfig->getMerchantGatewayClientSecret();
173
        $dataSend = [
174
            'scope'      => 'mgm',
175
            'grant_type' => 'client_credentials',
176
        ];
177
        $client = $this->httpClientFactory->create();
178
        $client->setUri($uri.'credenciamento/auth/oauth/v2/token');
179
        $client->setAuth($clientId, $clientSecret);
180
        $client->setConfig(['maxredirects' => 0, 'timeout' => 30]);
181
        $client->setHeaders(['content' => 'application/x-www-form-urlencoded']);
182
        $client->setParameterPost($dataSend);
183
        $client->setMethod(ZendClient::POST);
184
185
        try {
186
            $result = $client->request()->getBody();
187
            $response = $this->json->unserialize($result);
188
            $this->logger->info($this->json->serialize(['response' => $response]));
189
190
            return [
191
                'success'    => true,
192
                'response'   => $response,
193
            ];
194
        } catch (Exception $exc) {
195
            $this->logger->debug($this->json->serialize(['error' => $exc->getMessage()]));
196
197
            return ['success' => false, 'error' =>  $exc->getMessage()];
198
        }
199
    }
200
201
    /**
202
     * Set New Token.
203
     *
204
     * @param string $token
205
     * @param int    $storeId
206
     *
207
     * @return array
208
     */
209
    private function setNewToken(string $token, int $storeId): array
210
    {
211
        $environment = $this->getnetConfig->getEnvironment();
212
        $pathPattern = 'getnet_sub_seller/general/credentials/%s_%s';
213
        $pathConfigId = sprintf($pathPattern, 'access_token', $environment);
214
215
        try {
216
            $this->config->saveConfig(
217
                $pathConfigId,
218
                $token,
219
                'default',
220
                $storeId
221
            );
222
        } catch (Exception $e) {
223
            return ['success' => false, 'error' => $e->getMessage()];
224
        }
225
226
        return ['success' => true];
227
    }
228
}
229