Passed
Pull Request — master (#45)
by Raúl
05:08
created

PagantisPaymentModuleFrontController   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 332
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 222
dl 0
loc 332
rs 8.96
c 2
b 0
f 1
wmc 43

5 Methods

Rating   Name   Duplication   Size   Complexity  
A addLog() 0 25 2
B getTaxId() 0 12 9
A isPromoted() 0 7 2
B getNationalId() 0 14 11
F postProcess() 0 232 19

How to fix   Complexity   

Complex Class

Complex classes like PagantisPaymentModuleFrontController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PagantisPaymentModuleFrontController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * This file is part of the official Pagantis module for PrestaShop.
4
 *
5
 * @author    Pagantis <[email protected]>
6
 * @copyright 2019 Pagantis
7
 * @license   proprietary
8
 */
9
10
require_once('AbstractController.php');
11
12
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
13
use Pagantis\ModuleUtils\Exception\UnknownException;
14
15
/**
16
 * Class PagantisRedirectModuleFrontController
17
 */
18
class PagantisPaymentModuleFrontController extends AbstractController
19
{
20
    /**
21
     * @param $customer
22
     * @param $exception
23
     */
24
    protected function addLog($customer, $exception)
25
    {
26
        if (_PS_VERSION_ < 1.6) {
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
27
            Logger::addLog(
0 ignored issues
show
Bug introduced by
The type 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...
28
                'Pagantis Exception For user ' .
29
                $customer->email .
30
                ' : ' .
31
                $exception->getMessage(),
32
                3,
33
                $exception->getCode(),
34
                null,
35
                null,
36
                true
37
            );
38
        } else {
39
            PrestaShopLogger::addLog(
0 ignored issues
show
Bug introduced by
The type PrestaShopLogger 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...
40
                'Pagantis Exception For user ' .
41
                $customer->email .
42
                ' : ' .
43
                $exception->getMessage(),
44
                3,
45
                $exception->getCode(),
46
                null,
47
                null,
48
                true
49
            );
50
        }
51
    }
52
53
    /**
54
     * Process Post Request
55
     *
56
     * @throws \Exception
57
     */
58
    public function postProcess()
59
    {
60
        $lang = Language::getLanguage($this->context->language->id);
0 ignored issues
show
Bug introduced by
The type Language 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...
61
        $langArray = explode("-", $lang['language_code']);
62
        if (count($langArray) != 2 && isset($lang['locale'])) {
63
            $langArray = explode("-", $lang['locale']);
0 ignored issues
show
Unused Code introduced by
The assignment to $langArray is dead and can be removed.
Loading history...
64
        }
65
66
        /** @var Cart $cart */
67
        $cart = $this->context->cart;
68
69
        if (!$cart->id) {
70
            Tools::redirect('index.php?controller=order');
0 ignored issues
show
Bug introduced by
The type Tools 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
73
        /** @var Customer $customer */
74
        $customer = $this->context->customer;
75
        $query = array(
76
            'id_cart' => $cart->id,
77
            'key' => $cart->secure_key,
78
        );
79
80
        $koUrl = $this->context->link->getPageLink(
81
            'order',
82
            null,
83
            null,
84
            array('step'=>3)
85
        );
86
        $iframe = Pagantis::getExtraConfig('PAGANTIS_FORM_DISPLAY_TYPE');
87
        $cancelUrl = (Pagantis::getExtraConfig('PAGANTIS_URL_KO') !== '') ?
88
            Pagantis::getExtraConfig('PAGANTIS_URL_KO') : $koUrl;
89
        $pagantisPublicKey = Configuration::get('pagantis_public_key');
0 ignored issues
show
Bug introduced by
The type Configuration 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...
90
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
91
        $okUrl = _PS_BASE_URL_.__PS_BASE_URI__
0 ignored issues
show
Bug introduced by
The constant __PS_BASE_URI__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant _PS_BASE_URL_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
92
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&'
93
                 .http_build_query($query)
94
        ;
95
96
        $shippingAddress = new Address($cart->id_address_delivery);
0 ignored issues
show
Bug introduced by
The type Address 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...
97
        $billingAddress = new Address($cart->id_address_invoice);
98
        $curlInfo = curl_version();
99
        $curlVersion = $curlInfo['version'];
100
        $metadata = array(
101
            'ps' => _PS_VERSION_,
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
102
            'pagantis' => $this->module->version,
103
            'php' => phpversion(),
104
            'curl' => $curlVersion,
105
        );
106
107
        try {
108
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
109
            $userAddress
110
                ->setZipCode($shippingAddress->postcode)
111
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
112
                ->setCountryCode($this->language)
113
                ->setCity($shippingAddress->city)
114
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
115
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
116
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
117
            ;
118
119
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
120
            $orderShippingAddress
121
                ->setZipCode($shippingAddress->postcode)
122
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
123
                ->setCountryCode($this->language)
124
                ->setCity($shippingAddress->city)
125
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
126
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
127
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
128
                ->setFixPhone($shippingAddress->phone)
129
                ->setMobilePhone($shippingAddress->phone_mobile)
130
            ;
131
132
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
133
            $orderBillingAddress
134
                ->setZipCode($billingAddress->postcode)
135
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
136
                ->setCountryCode($this->language)
137
                ->setCity($billingAddress->city)
138
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
139
                ->setTaxId($this->getTaxId($customer, $billingAddress, $shippingAddress))
140
                ->setNationalId($this->getNationalId($customer, $billingAddress, $shippingAddress))
141
                ->setFixPhone($billingAddress->phone)
142
                ->setMobilePhone($billingAddress->phone_mobile)
143
            ;
144
145
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
146
            $orderUser
147
                ->setAddress($userAddress)
148
                ->setFullName($orderShippingAddress->getFullName())
149
                ->setBillingAddress($orderBillingAddress)
150
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
151
                ->setFixPhone($shippingAddress->phone)
152
                ->setMobilePhone($shippingAddress->phone_mobile)
153
                ->setShippingAddress($orderShippingAddress)
154
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
155
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
156
            ;
157
158
            if ($customer->birthday!='0000-00-00') {
159
                $orderUser->setDateOfBirth($customer->birthday);
160
            }
161
162
            $orders = Order::getCustomerOrders($customer->id);
0 ignored issues
show
Bug introduced by
The type Order 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...
163
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
164
            foreach ($orders as $order) {
165
                if ($order['valid']) {
166
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
167
                    $orderHistory
168
                        ->setAmount((string) floor(100 * $order['total_paid']))
169
                        ->setDate(new \DateTime($order['date_add']))
0 ignored issues
show
Bug introduced by
new DateTime($order['date_add']) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

169
                        ->setDate(/** @scrutinizer ignore-type */ new \DateTime($order['date_add']))
Loading history...
170
                    ;
171
                    $orderUser->addOrderHistory($orderHistory);
172
                }
173
            }
174
175
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
176
            foreach ($metadata as $key => $metadatum) {
177
                $metadataOrder->addMetadata($key, $metadatum);
178
            }
179
180
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
181
            $details->setShippingCost((string) floor(100 * $cart->getTotalShippingCost()));
182
            $items = $cart->getProducts();
183
            $promotedAmount = 0;
184
            foreach ($items as $key => $item) {
185
                $promotedProduct = $this->isPromoted($item['id_product']);
186
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
187
                $product
188
                    ->setAmount((string) floor(100 * $item['price_wt']))
189
                    ->setQuantity($item['quantity'])
190
                    ->setDescription($item['name']);
191
                if ($promotedProduct) {
192
                    $promotedAmount+=$product->getAmount();
193
                    $finalPrice = Product::getPriceStatic($item['id_product']);
0 ignored issues
show
Bug introduced by
The type Product 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...
194
                    $promotedMessage = 'Promoted Item: ' . $product->getDescription() .
195
                         ' Price: ' . $finalPrice .
196
                         ' Qty: ' . $product->getQuantity() .
197
                         ' Item ID: ' . $item['id_product'];
198
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
199
                }
200
                $details->addProduct($product);
201
            }
202
203
204
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
205
            $totalAmount = (string) floor(100 * $cart->getOrderTotal(true));
206
            $orderShoppingCart
207
                ->setDetails($details)
208
                ->setOrderReference($cart->id)
209
                ->setTotalAmount($totalAmount)
210
                ->setPromotedAmount($promotedAmount)
211
            ;
212
213
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
214
            $orderConfigurationUrls
215
                ->setCancel($cancelUrl)
216
                ->setKo($cancelUrl)
217
                ->setAuthorizedNotificationCallback($okUrl)
218
                ->setRejectedNotificationCallback($okUrl)
219
                ->setOk($okUrl)
220
            ;
221
222
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
223
            $orderChannel
224
                ->setAssistedSale(false)
225
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
226
            ;
227
228
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
229
            $orderConfiguration
230
                ->setChannel($orderChannel)
231
                ->setUrls($orderConfigurationUrls)
232
                ->setPurchaseCountry($this->language)
233
            ;
234
235
            $order = new \Pagantis\OrdersApiClient\Model\Order();
236
            $order
237
                ->setConfiguration($orderConfiguration)
238
                ->setMetadata($metadataOrder)
239
                ->setShoppingCart($orderShoppingCart)
240
                ->setUser($orderUser)
241
            ;
242
        } catch (\Exception $exception) {
243
            $this->saveLog(array(), $exception);
244
            Tools::redirect($cancelUrl);
245
        }
246
247
        $url ='';
248
        try {
249
            $orderClient = new \Pagantis\OrdersApiClient\Client(
250
                $pagantisPublicKey,
251
                $pagantisPrivateKey
252
            );
253
            $order = $orderClient->createOrder($order);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $order does not seem to be defined for all execution paths leading up to this point.
Loading history...
254
255
            if ($order instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$order is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
256
                $url = $order->getActionUrls()->getForm();
257
                $orderId = $order->getId();
258
                $sql = "INSERT INTO `" . _DB_PREFIX_ . "pagantis_order` (`id`, `order_id`)
0 ignored issues
show
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
259
                     VALUES ('$cart->id','$orderId') 
260
                     ON DUPLICATE KEY UPDATE `order_id` = '$orderId'";
261
                $result = Db::getInstance()->execute($sql);
0 ignored issues
show
Bug introduced by
The type Db 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...
262
                if (!$result) {
263
                    throw new UnknownException('Unable to save pagantis-order-id in database: '. $sql);
264
                }
265
            } else {
266
                throw new OrderNotFoundException();
267
            }
268
        } catch (\Exception $exception) {
269
            $this->saveLog(array(), $exception);
270
            Tools::redirect($cancelUrl);
271
        }
272
273
        if (!$iframe) {
274
            Tools::redirect($url);
275
        } else {
276
            $this->context->smarty->assign(array(
277
                'url'           => $url,
278
                'checkoutUrl'   => $cancelUrl,
279
            ));
280
281
            try {
282
                if (_PS_VERSION_ < 1.7) {
283
                    $this->setTemplate('payment-15.tpl');
284
                } else {
285
                    $this->setTemplate('module:pagantis/views/templates/front/payment-17.tpl');
286
                }
287
            } catch (\Exception $exception) {
288
                $this->saveLog(array(), $exception);
289
                Tools::redirect($url);
290
            }
291
        }
292
    }
293
294
    /**
295
     * @param null $customer
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $customer is correct as it would always require null to be passed?
Loading history...
296
     * @param null $addressOne
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressOne is correct as it would always require null to be passed?
Loading history...
297
     * @param null $addressTwo
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressTwo is correct as it would always require null to be passed?
Loading history...
298
     * @return mixed|null
299
     */
300
    private function getNationalId($customer = null, $addressOne = null, $addressTwo = null)
301
    {
302
        if ($customer !== null && isset($customer->national_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
303
            return $customer->national_id;
304
        } elseif ($addressOne !== null and isset($addressOne->national_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
305
            return $addressOne->national_id;
306
        } elseif ($addressOne !== null and isset($addressOne->dni)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
307
            return $addressOne->dni;
308
        } elseif ($addressTwo !== null and isset($addressTwo->national_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
309
            return $addressTwo->national_id;
310
        } elseif ($addressTwo !== null and isset($addressTwo->dni)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
311
            return $addressTwo->dni;
312
        } else {
313
            return null;
314
        }
315
    }
316
317
    /**
318
     * @param null $customer
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $customer is correct as it would always require null to be passed?
Loading history...
319
     * @param null $addressOne
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressOne is correct as it would always require null to be passed?
Loading history...
320
     * @param null $addressTwo
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $addressTwo is correct as it would always require null to be passed?
Loading history...
321
     * @return mixed|null
322
     */
323
    private function getTaxId($customer = null, $addressOne = null, $addressTwo = null)
324
    {
325
        if ($customer !== null && isset($customer->tax_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
326
            return $customer->tax_id;
327
        } elseif ($customer !== null && isset($customer->fiscalcode)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
328
            return $customer->fiscalcode;
329
        } elseif ($addressOne !== null and isset($addressOne->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
330
            return $addressOne->tax_id;
331
        } elseif ($addressTwo !== null and isset($addressTwo->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
332
            return $addressTwo->tax_id;
333
        } else {
334
            return null;
335
        }
336
    }
337
338
    /**
339
     * @param $item
340
     *
341
     * @return bool
342
     */
343
    private function isPromoted($itemId)
344
    {
345
        $itemCategories = ProductCore::getProductCategoriesFull($itemId);
0 ignored issues
show
Bug introduced by
The type ProductCore 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...
346
        if (in_array(PROMOTIONS_CATEGORY_NAME, array_column($itemCategories, 'name')) !== false) {
347
            return true;
348
        }
349
        return false;
350
    }
351
}
352