Refund::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 12
c 1
b 0
f 0
nc 1
nop 12
dl 0
loc 26
rs 9.8666

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 © Wirecard Brasil. All rights reserved.
4
 *
5
 * @author    Bruno Elisei <[email protected]>
6
 * See COPYING.txt for license details.
7
 */
8
declare(strict_types=1);
9
10
namespace Moip\Magento2\Controller\Webhooks;
11
12
use Exception;
13
use Magento\Framework\Api\SearchCriteriaBuilder;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Api\SearchCriteriaBuilder 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...
14
use Magento\Framework\App\Action\Action;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Action\Action 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...
15
use Magento\Framework\App\Action\Context;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Action\Context 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...
16
use Magento\Framework\App\CsrfAwareActionInterface as Crsf;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\CsrfAwareActionInterface 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...
17
use Magento\Framework\App\Request\InvalidRequestException;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Re...InvalidRequestException 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\App\RequestInterface;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\RequestInterface 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...
19
use Magento\Framework\Controller\Result\JsonFactory;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Controller\Result\JsonFactory 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...
20
use Magento\Framework\Serialize\Serializer\Json;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Serialize\Serializer\Json 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\Payment\Model\Method\Logger;
0 ignored issues
show
Bug introduced by
The type Magento\Payment\Model\Method\Logger 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\Sales\Api\CreditmemoRepositoryInterface;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Api\CreditmemoRepositoryInterface 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\Sales\Api\Data\OrderInterfaceFactory;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Api\Data\OrderInterfaceFactory 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...
24
use Magento\Sales\Model\Order\Creditmemo;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Order\Creditmemo 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\Sales\Model\Order\CreditmemoFactory;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Order\CreditmemoFactory 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...
26
use Magento\Sales\Model\Order\Invoice;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Order\Invoice 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...
27
use Magento\Sales\Model\Service\CreditmemoService;
0 ignored issues
show
Bug introduced by
The type Magento\Sales\Model\Service\CreditmemoService 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...
28
use Magento\Store\Model\StoreManagerInterface;
0 ignored issues
show
Bug introduced by
The type Magento\Store\Model\StoreManagerInterface 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...
29
use Moip\Magento2\Gateway\Config\Config;
30
31
/**
32
 * Class Refund - Receives communication for refunded payment.
33
 */
34
class Refund extends Action implements Crsf
35
{
36
    /**
37
     * createCsrfValidationException.
38
     *
39
     * @param RequestInterface $request
40
     *
41
     * @return null
42
     */
43
    public function createCsrfValidationException(RequestInterface $request): InvalidRequestException
44
    {
45
        if ($request) {
0 ignored issues
show
introduced by
$request is of type Magento\Framework\App\RequestInterface, thus it always evaluated to true.
Loading history...
46
            return null;
0 ignored issues
show
Bug Best Practice introduced by
The expression return null returns the type null which is incompatible with the type-hinted return Magento\Framework\App\Re...InvalidRequestException.
Loading history...
47
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 45 is false. This is incompatible with the type-hinted return Magento\Framework\App\Re...InvalidRequestException. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
48
    }
49
50
    /**
51
     * validateForCsrf.
52
     *
53
     * @param RequestInterface $request
54
     *
55
     * @return bool true
56
     */
57
    public function validateForCsrf(RequestInterface $request): bool
58
    {
59
        if ($request) {
0 ignored issues
show
introduced by
$request is of type Magento\Framework\App\RequestInterface, thus it always evaluated to true.
Loading history...
60
            return true;
61
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 59 is false. This is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
62
    }
63
64
    /**
65
     * @var logger
66
     */
67
    protected $logger;
68
69
    /**
70
     * @var orderFactory
0 ignored issues
show
Bug introduced by
The type Moip\Magento2\Controller\Webhooks\orderFactory 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...
71
     */
72
    protected $orderFactory;
73
74
    /**
75
     * @var resultJsonFactory
0 ignored issues
show
Bug introduced by
The type Moip\Magento2\Controller...hooks\resultJsonFactory 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...
76
     */
77
    protected $resultJsonFactory;
78
79
    /**
80
     * @var storeManager
0 ignored issues
show
Bug introduced by
The type Moip\Magento2\Controller\Webhooks\storeManager 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...
81
     */
82
    protected $storeManager;
83
84
    /**
85
     * @var Json
86
     */
87
    protected $json;
88
89
    /**
90
     * @var CreditmemoRepositoryInterface
91
     */
92
    private $creditmemoRepository;
93
94
    /**
95
     * @var schCriteriaBuilder
0 ignored issues
show
Bug introduced by
The type Moip\Magento2\Controller...ooks\schCriteriaBuilder 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...
96
     */
97
    protected $schCriteriaBuilder;
98
99
    /**
100
     * @param Context               $context
101
     * @param logger                $logger
102
     * @param Config                $config
103
     * @param OrderInterfaceFactory $orderFactory
104
     * @param JsonFactory           $resultJsonFactory
105
     * @param Json                  $json
106
     */
107
    public function __construct(
108
        Context $context,
109
        Config $config,
110
        Logger $logger,
111
        OrderInterfaceFactory $orderFactory,
112
        CreditmemoFactory $creditmemoFactory,
113
        CreditmemoService $creditmemoService,
114
        Invoice $invoice,
115
        StoreManagerInterface $storeManager,
116
        JsonFactory $resultJsonFactory,
117
        Json $json,
118
        CreditmemoRepositoryInterface $creditmemoRepository,
119
        SearchCriteriaBuilder $schCriteriaBuilder
120
    ) {
121
        parent::__construct($context);
122
        $this->config = $config;
0 ignored issues
show
Bug Best Practice introduced by
The property config does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
123
        $this->logger = $logger;
124
        $this->orderFactory = $orderFactory;
125
        $this->creditmemoFactory = $creditmemoFactory;
0 ignored issues
show
Bug Best Practice introduced by
The property creditmemoFactory does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
126
        $this->creditmemoService = $creditmemoService;
0 ignored issues
show
Bug Best Practice introduced by
The property creditmemoService does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
127
        $this->invoice = $invoice;
0 ignored issues
show
Bug Best Practice introduced by
The property invoice does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
128
        $this->storeManager = $storeManager;
129
        $this->resultJsonFactory = $resultJsonFactory;
130
        $this->json = $json;
131
        $this->creditmemoRepository = $creditmemoRepository;
132
        $this->schCriteriaBuilder = $schCriteriaBuilder;
133
    }
134
135
    /**
136
     * Command Refund.
137
     *
138
     * @return json
139
     */
140
    public function execute()
141
    {
142
        if (!$this->getRequest()->isPost()) {
143
            $resultPage = $this->resultJsonFactory->create();
144
            $resultPage->setHttpResponseCode(404);
145
146
            return $resultPage;
147
        }
148
149
        $resultPage = $this->resultJsonFactory->create();
150
        $response = $this->getRequest()->getContent();
151
        $originalNotification = $this->json->unserialize($response);
152
        $authorization = $this->getRequest()->getHeader('Authorization');
153
        $storeId = $this->storeManager->getStore()->getId();
154
        $storeCaptureToken = $this->config->getMerchantGatewayRefundToken($storeId);
155
156
        if ($storeCaptureToken === $authorization) {
157
            $resource = $originalNotification['resource'];
158
            $extRefundId = $resource['refund']['id'];
159
            $extStatus = $resource['refund']['status'];
160
161
            $creditmemos = $this->getCreditMemoByTransactionId($extRefundId);
162
            if (count($creditmemos)) {
163
                foreach ($creditmemos as $creditmemo) {
164
                    if ($extStatus === 'REQUESTED') {
165
                        $creditmemo->setState(Creditmemo::STATE_OPEN);
166
                    } elseif ($extStatus === 'COMPLETED') {
167
                        $creditmemo->setState(Creditmemo::STATE_REFUNDED);
168
                    } elseif ($extStatus === 'FAILED') {
169
                        $creditmemo->setState(Creditmemo::STATE_CANCELED);
170
                    }
171
172
                    try {
173
                        $creditmemo->save();
174
                    } catch (\Exception $exc) {
175
                        $resultPage->setHttpResponseCode(500);
176
                        $resultPage->setJsonData(
177
                            $this->json->serialize([
178
                                'error'   => 400,
179
                                'message' => $exc->getMessage(),
180
                            ])
181
                        );
182
                    }
183
184
                    continue;
185
                }
186
            } else {
187
                $extOrderId = $resource['refund']['_links']['order']['title'];
188
                $creditmemo = $this->createNewCreditMemo($extOrderId, $extRefundId);
189
                if ($creditmemo) {
0 ignored issues
show
introduced by
$creditmemo is of type Magento\Sales\Model\Order\Creditmemo, thus it always evaluated to true.
Loading history...
190
                    if ($extStatus === 'REQUESTED') {
191
                        $creditmemo->setState(Creditmemo::STATE_OPEN);
192
                    } elseif ($extStatus === 'COMPLETED') {
193
                        $creditmemo->setState(Creditmemo::STATE_REFUNDED);
194
                    } elseif ($extStatus === 'FAILED') {
195
                        $creditmemo->setState(Creditmemo::STATE_CANCELED);
196
                    }
197
198
                    try {
199
                        $this->creditmemoService->refund($creditmemo);
200
                    } catch (\Exception $exc) {
201
                        $resultPage->setHttpResponseCode(500);
202
                        $resultPage->setJsonData(
203
                            $this->json->serialize([
204
                                'error'   => 400,
205
                                'message' => $exc->getMessage(),
206
                            ])
207
                        );
208
                    }
209
                } else {
210
                    return $resultPage->setJsonData(
211
                        $this->json->serialize([
212
                            'error'   => 404,
213
                            'message' => 'The transaction could not be refund',
214
                        ])
215
                    );
216
                }
217
            }
218
219
            return $resultPage->setJsonData(
220
                $this->json->serialize([
221
                    'success'    => 1,
222
                    'extOrderId' => $extRefundId,
223
                    'state'      => $creditmemo->getState(),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $creditmemo does not seem to be defined for all execution paths leading up to this point.
Loading history...
224
                ])
225
            );
226
        }
227
228
        $resultPage->setHttpResponseCode(401);
229
230
        return $resultPage;
231
    }
232
233
    /**
234
     * Get Creditmemo.
235
     *
236
     * @params $extOrderId
237
     *
238
     * @return creditmemo
239
     */
240
    public function getCreditMemoByTransactionId(string $transactionId)
241
    {
242
        $searchCriteria = $this->schCriteriaBuilder
243
            ->addFilter('transaction_id', $transactionId)->create();
244
245
        try {
246
            $creditmemos = $this->creditmemoRepository->getList($searchCriteria);
247
            $creditmemoRecords = $creditmemos->getItems();
248
        } catch (Exception $exception) {
249
            $this->logger->critical($exception->getMessage());
250
            $creditmemoRecords = null;
251
        }
252
253
        return $creditmemoRecords;
254
    }
255
256
    /**
257
     * Create new creditmemo.
258
     *
259
     * @params $extOrderId
260
     * @parmas $extRefundId
261
     *
262
     * @return creditmemo
263
     */
264
    public function createNewCreditMemo(string $extOrderId, string $extRefundId)
265
    {
266
        $order = $this->orderFactory->create()->load($extOrderId, 'ext_order_id');
267
        $creditmemo = null;
268
269
        $payment = $order->getPayment();
270
        $invoices = $order->getInvoiceCollection();
271
272
        if ($invoices) {
273
            foreach ($invoices as $invoiceLoad) {
274
                $invoiceincrementid = $invoiceLoad->getIncrementId();
275
            }
276
            $invoiceobj = $this->invoice->loadByIncrementId($invoiceincrementid);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $invoiceincrementid seems to be defined by a foreach iteration on line 273. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
277
            $creditmemo = $this->creditmemoFactory->createByOrder($order);
278
            $payment->setTransactionId($extRefundId);
279
            $creditmemo->setInvoice($invoiceobj);
280
        }
281
282
        return $creditmemo;
283
    }
284
}
285