CreateOrderPaymentTwoCcClient::placeRequest()   B
last analyzed

Complexity

Conditions 6
Paths 27

Size

Total Lines 71
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 41
c 1
b 0
f 0
nc 27
nop 1
dl 0
loc 71
rs 8.6417

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\PaymentMagento\Gateway\Http\Client;
12
13
use Exception;
14
use Getnet\PaymentMagento\Gateway\Config\Config;
15
use InvalidArgumentException;
16
use Magento\Framework\HTTP\ZendClient;
17
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...
18
use Magento\Framework\Serialize\Serializer\Json;
19
use Magento\Payment\Gateway\Http\ClientInterface;
20
use Magento\Payment\Gateway\Http\TransferInterface;
21
use Magento\Payment\Model\Method\Logger;
22
23
/**
24
 * Class Create Order Payment Two Cc Client - create authorization for payment by Cc.
25
 *
26
 * @SuppressWarnings(PHPCPD)
27
 */
28
class CreateOrderPaymentTwoCcClient implements ClientInterface
29
{
30
    /**
31
     * Result Code - Block name.
32
     */
33
    public const RESULT_CODE = 'RESULT_CODE';
34
35
    /**
36
     * Store Id - Block name.
37
     */
38
    public const STORE_ID = 'store_id';
39
40
    /**
41
     * External Order Id - Block name.
42
     */
43
    public const EXT_ORD_ID = 'EXT_ORD_ID';
44
45
    /**
46
     * @var Logger
47
     */
48
    private $logger;
49
50
    /**
51
     * @var ZendClientFactory
52
     */
53
    private $httpClientFactory;
54
55
    /**
56
     * @var Config
57
     */
58
    private $config;
59
60
    /**
61
     * @var Json
62
     */
63
    private $json;
64
65
    /**
66
     * @param Logger            $logger
67
     * @param ZendClientFactory $httpClientFactory
68
     * @param Config            $config
69
     * @param Json              $json
70
     */
71
    public function __construct(
72
        Logger $logger,
73
        ZendClientFactory $httpClientFactory,
74
        Config $config,
75
        Json $json
76
    ) {
77
        $this->config = $config;
78
        $this->httpClientFactory = $httpClientFactory;
79
        $this->logger = $logger;
80
        $this->json = $json;
81
    }
82
83
    /**
84
     * Places request to gateway.
85
     *
86
     * @param TransferInterface $transferObject
87
     *
88
     * @return array
89
     */
90
    public function placeRequest(TransferInterface $transferObject)
91
    {
92
        /** @var ZendClient $client */
93
        $isSuccess = false;
94
        $client = $this->httpClientFactory->create();
95
        $request = $transferObject->getBody();
96
        $storeId = $request[self::STORE_ID];
97
        $url = $this->config->getApiUrl($storeId);
98
        $apiBearer = $this->config->getMerchantGatewayOauth($storeId);
99
        unset($request[self::STORE_ID]);
100
101
        try {
102
            $client->setUri($url.'v1/payments/combined');
103
            $client->setConfig(['maxredirects' => 0, 'timeout' => 45000]);
104
            $client->setHeaders(
105
                [
106
                    'Authorization'               => 'Bearer '.$apiBearer,
107
                    'x-transaction-channel-entry' => 'MG',
108
                ]
109
            );
110
            $client->setRawData($this->json->serialize($request), 'application/json');
111
            $client->setMethod(ZendClient::POST);
112
113
            $responseBody = $client->request()->getBody();
114
            $data = $this->json->unserialize($responseBody);
115
            $response = array_merge(
116
                [
117
                    self::RESULT_CODE  => 0,
118
                ],
119
                $data
120
            );
121
122
            if (isset($data['payments'])) {
123
                foreach ($data['payments'] as $payment) {
124
                    if (isset($payment['payment_id'])) {
125
                        $isSuccess = true;
126
                    }
127
                }
128
            }
129
130
            if ($isSuccess) {
131
                $response = array_merge(
132
                    [
133
                        self::RESULT_CODE => 1,
134
                        self::EXT_ORD_ID  => $data['combined_id'],
135
                    ],
136
                    $data
137
                );
138
            }
139
140
            $this->logger->debug(
141
                [
142
                    'url'      => $url.'v1/payments/combined',
143
                    'request'  => $this->json->serialize($transferObject->getBody()),
144
                    'response' => $responseBody,
145
                ]
146
            );
147
        } catch (InvalidArgumentException $e) {
148
            $this->logger->debug(
149
                [
150
                    'exception' => $e->getMessage(),
151
                    'url'       => $url.'v1/payments/combined',
152
                    'request'   => $this->json->serialize($transferObject->getBody()),
153
                    'response'  => $responseBody,
154
                ]
155
            );
156
            // phpcs:ignore Magento2.Exceptions.DirectThrow
157
            throw new Exception('Invalid JSON was returned by the gateway');
158
        }
159
160
        return $response;
161
    }
162
}
163