CardIdManagement   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 154
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 53
c 1
b 0
f 0
dl 0
loc 154
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDetailsCardId() 0 24 2
A getCardId() 0 43 3
A __construct() 0 16 1
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;
12
13
use Getnet\PaymentMagento\Api\CardIdManagementInterface;
14
use Getnet\PaymentMagento\Api\Data\CardIdInterface;
15
use Getnet\PaymentMagento\Gateway\Config\Config as ConfigBase;
16
use InvalidArgumentException;
17
use Magento\Framework\Exception\CouldNotSaveException;
18
use Magento\Framework\Exception\NoSuchEntityException;
19
use Magento\Framework\HTTP\ZendClient;
20
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...
21
use Magento\Framework\Serialize\Serializer\Json;
22
use Magento\Payment\Gateway\ConfigInterface;
23
use Magento\Payment\Model\Method\Logger;
24
use Magento\Quote\Api\CartRepositoryInterface;
25
use Magento\Quote\Api\Data\CartInterface as QuoteCartInterface;
26
use Magento\Vault\Model\PaymentTokenManagement;
27
28
/**
29
 * Class Card Id Management - Get Details Card Id.
30
 *
31
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
32
 */
33
class CardIdManagement implements CardIdManagementInterface
34
{
35
    /**
36
     * @var Logger
37
     */
38
    private $logger;
39
40
    /**
41
     * @var CartRepositoryInterface
42
     */
43
    protected $quoteRepository;
44
45
    /**
46
     * @var ConfigInterface
47
     */
48
    private $config;
49
50
    /**
51
     * @var ConfigBase
52
     */
53
    private $configBase;
54
55
    /**
56
     * @var ZendClientFactory
57
     */
58
    private $httpClientFactory;
59
60
    /**
61
     * @var Json
62
     */
63
    private $json;
64
65
    /**
66
     * @var PaymentTokenManagement
67
     */
68
    private $tokenManagement;
69
70
    /**
71
     * CardIdManagement constructor.
72
     *
73
     * @param Logger                  $logger
74
     * @param CartRepositoryInterface $quoteRepository
75
     * @param ConfigInterface         $config
76
     * @param ConfigBase              $configBase
77
     * @param ZendClientFactory       $httpClientFactory
78
     * @param Json                    $json
79
     * @param PaymentTokenManagement  $tokenManagement
80
     */
81
    public function __construct(
82
        Logger $logger,
83
        CartRepositoryInterface $quoteRepository,
84
        ConfigInterface $config,
85
        ConfigBase $configBase,
86
        ZendClientFactory $httpClientFactory,
87
        Json $json,
88
        PaymentTokenManagement $tokenManagement
89
    ) {
90
        $this->logger = $logger;
91
        $this->quoteRepository = $quoteRepository;
92
        $this->config = $config;
93
        $this->configBase = $configBase;
94
        $this->httpClientFactory = $httpClientFactory;
95
        $this->json = $json;
96
        $this->tokenManagement = $tokenManagement;
97
    }
98
99
    /**
100
     * Generate Number Token by Card Number.
101
     *
102
     * @param int                                             $cartId
103
     * @param \Getnet\PaymentMagento\Api\Data\CardIdInterface $cardId
104
     *
105
     * @throws CouldNotSaveException
106
     * @throws NoSuchEntityException
107
     *
108
     * @return array
109
     */
110
    public function getDetailsCardId(
111
        $cartId,
112
        CardIdInterface $cardId
113
    ) {
114
        $quote = $this->quoteRepository->getActive($cartId);
115
        if (!$quote->getItemsCount()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $quote->getItemsCount() 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...
116
            throw new NoSuchEntityException(__('Cart %1 doesn\'t contain products', $cartId));
117
        }
118
        $data = [];
119
120
        $hash = $cardId->getCardId();
121
122
        $storeId = $quote->getData(QuoteCartInterface::KEY_STORE_ID);
123
124
        $customerId = $quote->getCustomer()->getId();
125
126
        /** @var PaymentTokenManagement $paymentToken */
127
        $paymentToken = $this->tokenManagement->getByPublicHash($hash, $customerId);
128
129
        $gatawayToken = $paymentToken->getGatewayToken();
0 ignored issues
show
Bug introduced by
The method getGatewayToken() does not exist on Magento\Vault\Model\PaymentTokenManagement. Did you maybe mean getByGatewayToken()? ( Ignorable by Annotation )

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

129
        /** @scrutinizer ignore-call */ 
130
        $gatawayToken = $paymentToken->getGatewayToken();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
130
131
        $data['details'] = $this->getCardId($storeId, $gatawayToken);
132
133
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $data returns the type array which is incompatible with the return type mandated by Getnet\PaymentMagento\Ap...ace::getDetailsCardId() of string.

In the issue above, the returned value is violating the contract defined by the mentioned interface.

Let's take a look at an example:

interface HasName {
    /** @return string */
    public function getName();
}

class Name {
    public $name;
}

class User implements HasName {
    /** @return string|Name */
    public function getName() {
        return new Name('foo'); // This is a violation of the ``HasName`` interface
                                // which only allows a string value to be returned.
    }
}
Loading history...
134
    }
135
136
    /**
137
     * Get Number Token.
138
     *
139
     * @param int    $storeId
140
     * @param string $cardId
141
     *
142
     * @return array
143
     */
144
    public function getCardId($storeId, $cardId)
145
    {
146
        $client = $this->httpClientFactory->create();
147
        $url = $this->configBase->getApiUrl($storeId);
148
        $apiBearer = $this->configBase->getMerchantGatewayOauth($storeId);
149
150
        try {
151
            $client->setUri($url.'v1/cards/'.$cardId);
152
            $client->setConfig(['maxredirects' => 0, 'timeout' => 45000]);
153
            $client->setHeaders('Authorization', 'Bearer '.$apiBearer);
154
            $client->setMethod(ZendClient::GET);
155
156
            $responseBody = $client->request()->getBody();
157
            $data = $this->json->unserialize($responseBody);
158
            $response = [
159
                'success' => 0,
160
            ];
161
            if (isset($data['number_token'])) {
162
                $response = [
163
                    'success' => 1,
164
                    'card'    => $data,
165
                ];
166
            }
167
            $this->logger->debug(
168
                [
169
                    'url'      => $url.'v1/cards/'.$cardId,
170
                    'request'  => $cardId,
171
                    'response' => $responseBody,
172
                ]
173
            );
174
        } catch (InvalidArgumentException $e) {
175
            $this->logger->debug(
176
                [
177
                    'url'      => $url.'v1/cards/'.$cardId,
178
                    'request'  => $cardId,
179
                    'response' => $responseBody,
180
                ]
181
            );
182
            // phpcs:ignore Magento2.Exceptions.DirectThrow
183
            throw new NoSuchEntityException('Invalid JSON was returned by the gateway');
0 ignored issues
show
Bug introduced by
'Invalid JSON was returned by the gateway' of type string is incompatible with the type Magento\Framework\Phrase|null expected by parameter $phrase of Magento\Framework\Except...xception::__construct(). ( Ignorable by Annotation )

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

183
            throw new NoSuchEntityException(/** @scrutinizer ignore-type */ 'Invalid JSON was returned by the gateway');
Loading history...
184
        }
185
186
        return $response;
187
    }
188
}
189