PagantisPaymentModuleFrontController   F
last analyzed

Complexity

Total Complexity 61

Size/Duplication

Total Lines 419
Duplicated Lines 0 %

Importance

Changes 13
Bugs 2 Features 2
Metric Value
eloc 271
c 13
b 2
f 2
dl 0
loc 419
rs 3.52
wmc 61

7 Methods

Rating   Name   Duplication   Size   Complexity  
A addLog() 0 25 2
A arrayColumn() 0 23 6
B getUserLanguage() 0 26 8
B getTaxId() 0 12 9
A isPromoted() 0 7 2
C getNationalId() 0 18 15
F postProcess() 0 247 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
    /** @var string $language */
21
    protected $language;
22
23
    /**
24
     * @param $customer
25
     * @param $exception
26
     */
27
    protected function addLog($customer, $exception)
28
    {
29
        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...
30
            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...
31
                'Pagantis Exception For user ' .
32
                $customer->email .
33
                ' : ' .
34
                $exception->getMessage(),
35
                3,
36
                $exception->getCode(),
37
                null,
38
                null,
39
                true
40
            );
41
        } else {
42
            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...
43
                'Pagantis Exception For user ' .
44
                $customer->email .
45
                ' : ' .
46
                $exception->getMessage(),
47
                3,
48
                $exception->getCode(),
49
                null,
50
                null,
51
                true
52
            );
53
        }
54
    }
55
56
    /**
57
     * Process Post Request
58
     *
59
     * @throws \Exception
60
     */
61
    public function postProcess()
62
    {
63
        /** @var Cart $cart */
64
        $cart = $this->context->cart;
65
66
        if (!$cart->id) {
67
            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...
68
        }
69
70
        $urlToken = strtoupper(md5(uniqid(rand(), true)));
71
72
        /** @var Customer $customer */
73
        $customer = $this->context->customer;
74
        $query = array(
75
            'id_cart' => $cart->id,
76
            'key' => $cart->secure_key,
77
        );
78
79
        $koUrl = $this->context->link->getPageLink(
80
            'order',
81
            null,
82
            null,
83
            array('step'=>3)
84
        );
85
        $cancelUrl = (Pagantis::getExtraConfig('URL_KO') !== '') ? Pagantis::getExtraConfig('URL_KO', null) : $koUrl;
86
87
        $product = Tools::getValue('product');
88
        $configs = json_decode(Pagantis::getExtraConfig($product, null), true);
89
        $iframe = Pagantis::getExtraConfig('FORM_DISPLAY_TYPE', $product);
90
91
        $pagantisPublicKey = Configuration::get(Tools::strtolower($configs['CODE']) . '_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...
92
        $pagantisPrivateKey = Configuration::get(Tools::strtolower($configs['CODE']) . '_private_key');
93
94
        $okUrl = _PS_BASE_URL_SSL_.__PS_BASE_URI__
0 ignored issues
show
Bug introduced by
The constant _PS_BASE_URL_SSL_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
Bug introduced by
The constant __PS_BASE_URI__ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
95
            .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&token='.$urlToken.'&origin=redirect&product=' . Tools::strtolower($configs['CODE']) . '&'
96
            .http_build_query($query)
97
        ;
98
        $notificationOkUrl = _PS_BASE_URL_SSL_.__PS_BASE_URI__
99
            .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&token='.$urlToken.'&origin=notification&product=' . Tools::strtolower($configs['CODE']) . '&'
100
            .http_build_query($query)
101
        ;
102
103
        $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...
104
        $billingAddress = new Address($cart->id_address_invoice);
105
        $metadata = array(
106
            'pg_module' => 'prestashop',
107
            'pg_version' => $this->module->version,
108
            'ec_module' => 'prestashop',
109
            'ec_version' => _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...
110
        );
111
112
        try {
113
            $shippingCountry = Country::getIsoById($shippingAddress->id_country);
0 ignored issues
show
Bug introduced by
The type Country 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...
114
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
115
            $userAddress
116
                ->setZipCode($shippingAddress->postcode)
117
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
118
                ->setCountryCode($shippingCountry)
119
                ->setCity($shippingAddress->city)
120
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
121
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
122
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
123
                ->setDni($this->getNationalId($customer, $shippingAddress, $billingAddress))
124
            ;
125
126
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
127
            $shippingPhone = (empty($shippingAddress->phone_mobile)) ?
128
                $shippingAddress->phone : $shippingAddress->phone_mobile;
129
            $orderShippingAddress
130
                ->setZipCode($shippingAddress->postcode)
131
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
132
                ->setCountryCode($shippingCountry)
133
                ->setCity($shippingAddress->city)
134
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
135
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
136
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
137
                ->setDni($this->getNationalId($customer, $shippingAddress, $billingAddress))
138
                ->setFixPhone($shippingAddress->phone)
139
                ->setMobilePhone($shippingPhone)
140
            ;
141
142
            $billingCountry = Country::getIsoById($billingAddress->id_country);
143
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
144
            $billingPhone = (empty($billingAddress->phone_mobile)) ?
145
                $billingAddress->phone : $billingAddress->phone_mobile;
146
            $orderBillingAddress
147
                ->setZipCode($billingAddress->postcode)
148
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
149
                ->setCountryCode($billingCountry)
150
                ->setCity($billingAddress->city)
151
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
152
                ->setTaxId($this->getTaxId($customer, $billingAddress, $shippingAddress))
153
                ->setNationalId($this->getNationalId($customer, $billingAddress, $shippingAddress))
154
                ->setDni($this->getNationalId($customer, $shippingAddress, $billingAddress))
155
                ->setFixPhone($billingAddress->phone)
156
                ->setMobilePhone($billingPhone)
157
            ;
158
159
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
160
            $email = $this->context->cookie->logged ? $this->context->cookie->email : $customer->email;
161
            $orderUser
162
                ->setAddress($userAddress)
163
                ->setFullName($orderShippingAddress->getFullName())
164
                ->setBillingAddress($orderBillingAddress)
165
                ->setEmail($email)
166
                ->setFixPhone($shippingAddress->phone)
167
                ->setMobilePhone($shippingPhone)
168
                ->setShippingAddress($orderShippingAddress)
169
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
170
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
171
                ->setDni($this->getNationalId($customer, $shippingAddress, $billingAddress))
172
            ;
173
174
            if ($customer->birthday!='0000-00-00') {
175
                $orderUser->setDateOfBirth($customer->birthday);
176
            }
177
178
            $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...
179
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
180
            foreach ($orders as $order) {
181
                if ($order['valid']) {
182
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
183
                    $orderHistory
184
                        ->setAmount((string) floor(100 * $order['total_paid']))
185
                        ->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

185
                        ->setDate(/** @scrutinizer ignore-type */ new \DateTime($order['date_add']))
Loading history...
186
                    ;
187
                    $orderUser->addOrderHistory($orderHistory);
188
                }
189
            }
190
191
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
192
            foreach ($metadata as $key => $metadatum) {
193
                $metadataOrder->addMetadata($key, $metadatum);
194
            }
195
196
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
197
            $details->setShippingCost((string) floor(100 * $cart->getTotalShippingCost()));
198
            $items = $cart->getProducts();
199
            $promotedAmount = 0;
200
            foreach ($items as $key => $item) {
201
                $promotedProduct = $this->isPromoted($item['id_product']);
202
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
203
                $product
204
                    ->setAmount((string) floor(100 * $item['price_wt']))
205
                    ->setQuantity($item['quantity'])
206
                    ->setDescription($item['name']);
207
                if ($promotedProduct) {
208
                    $promotedAmount+=$product->getAmount();
209
                    $productId = $item['id_product'];
210
                    $finalPrice = Product::getPriceStatic($productId);
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...
211
                    $promotedMessage = 'Promoted Item: ' . $product->getDescription() .
212
                        ' Price: ' . $finalPrice .
213
                        ' Qty: ' . $product->getQuantity() .
214
                        ' Item ID: ' . $item['id_product'];
215
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
216
                }
217
                $details->addProduct($product);
218
            }
219
220
221
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
222
            $totalAmount = (string) floor(100 * $cart->getOrderTotal(true));
223
            $orderShoppingCart
224
                ->setDetails($details)
225
                ->setOrderReference($cart->id)
226
                ->setTotalAmount($totalAmount)
227
                ->setPromotedAmount($promotedAmount)
228
            ;
229
230
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
231
            $orderConfigurationUrls
232
                ->setCancel($cancelUrl)
233
                ->setKo($cancelUrl)
234
                ->setAuthorizedNotificationCallback($notificationOkUrl)
235
                ->setRejectedNotificationCallback(null)
236
                ->setOk($okUrl)
237
            ;
238
239
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
240
            $orderChannel
241
                ->setAssistedSale(false)
242
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
243
            ;
244
245
            $purchaseCountry = $this->getUserLanguage($shippingAddress, $billingAddress);
246
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
247
            $orderConfiguration
248
                ->setChannel($orderChannel)
249
                ->setUrls($orderConfigurationUrls)
250
                ->setPurchaseCountry($purchaseCountry)
251
            ;
252
253
            $order = new \Pagantis\OrdersApiClient\Model\Order();
254
            $order
255
                ->setConfiguration($orderConfiguration)
256
                ->setMetadata($metadataOrder)
257
                ->setShoppingCart($orderShoppingCart)
258
                ->setUser($orderUser)
259
            ;
260
        } catch (\Exception $exception) {
261
            $this->saveLog(array(), $exception);
262
            Tools::redirect($cancelUrl);
263
        }
264
265
        $url ='';
266
        try {
267
            $orderClient = new \Pagantis\OrdersApiClient\Client(
268
                trim($pagantisPublicKey),
269
                trim($pagantisPrivateKey)
270
            );
271
            $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...
272
273
            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...
274
                $url = $order->getActionUrls()->getForm();
275
                /** @var string $orderId MD5 value */
276
                $orderId = $order->getId();
277
                $sql = "INSERT INTO `" . _DB_PREFIX_ . "pagantis_order` (`id`, `order_id`, `token`)
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...
278
                     VALUES ('$cart->id','$orderId', '$urlToken')";
279
                $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...
280
                if (!$result) {
281
                    throw new UnknownException('Unable to save pagantis-order-id in database: '. $sql);
282
                }
283
            } else {
284
                throw new OrderNotFoundException();
285
            }
286
        } catch (\Exception $exception) {
287
            $this->saveLog(array(), $exception);
288
            Tools::redirect($cancelUrl);
289
        }
290
291
        if (!$iframe) {
292
            Tools::redirect($url);
293
        } else {
294
            $this->context->smarty->assign(array(
295
                'url'           => $url,
296
                'checkoutUrl'   => $cancelUrl,
297
            ));
298
299
            try {
300
                if (_PS_VERSION_ < 1.7) {
301
                    $this->setTemplate('payment-15.tpl');
302
                } else {
303
                    $this->setTemplate('module:pagantis/views/templates/front/payment-17.tpl');
304
                }
305
            } catch (\Exception $exception) {
306
                $this->saveLog(array(), $exception);
307
                Tools::redirect($url);
308
            }
309
        }
310
    }
311
312
    /**
313
     * @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...
314
     * @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...
315
     * @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...
316
     * @return mixed|null
317
     */
318
    private function getNationalId($customer = null, $addressOne = null, $addressTwo = null)
319
    {
320
        if ($customer !== null && !empty($customer->national_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
321
            return $customer->national_id;
322
        } elseif ($addressOne !== null and !empty($addressOne->national_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
323
            return $addressOne->national_id;
324
        } elseif ($addressOne !== null and !empty($addressOne->dni)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
325
            return $addressOne->dni;
326
        } elseif ($addressOne !== null and !empty($addressOne->vat_number)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
327
            return $addressOne->vat_number;
328
        } elseif ($addressTwo !== null and !empty($addressTwo->national_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
329
            return $addressTwo->national_id;
330
        } elseif ($addressTwo !== null and !empty($addressTwo->dni)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
331
            return $addressTwo->dni;
332
        } elseif ($addressTwo !== null and !empty($addressTwo->vat_number)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
333
            return $addressTwo->vat_number;
334
        } else {
335
            return null;
336
        }
337
    }
338
339
    /**
340
     * @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...
341
     * @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...
342
     * @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...
343
     * @return mixed|null
344
     */
345
    private function getTaxId($customer = null, $addressOne = null, $addressTwo = null)
346
    {
347
        if ($customer !== null && isset($customer->tax_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
348
            return $customer->tax_id;
349
        } elseif ($customer !== null && isset($customer->fiscalcode)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
350
            return $customer->fiscalcode;
351
        } elseif ($addressOne !== null and isset($addressOne->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
352
            return $addressOne->tax_id;
353
        } elseif ($addressTwo !== null and isset($addressTwo->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
354
            return $addressTwo->tax_id;
355
        } else {
356
            return null;
357
        }
358
    }
359
360
    /**
361
     * @param $item
362
     *
363
     * @return bool
364
     */
365
    private function isPromoted($itemId)
366
    {
367
        $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...
368
        if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
369
            return true;
370
        }
371
        return false;
372
    }
373
374
    /**
375
     * @param array $input
376
     * @param       $columnKey
377
     * @param null  $indexKey
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $indexKey is correct as it would always require null to be passed?
Loading history...
378
     *
379
     * @return array|bool
380
     */
381
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
382
    {
383
        $array = array();
384
        foreach ($input as $value) {
385
            if (!array_key_exists($columnKey, $value)) {
386
                trigger_error("Key \"$columnKey\" does not exist in array");
387
                return false;
388
            }
389
            if (is_null($indexKey)) {
390
                $array[] = $value[$columnKey];
391
            } else {
392
                if (!array_key_exists($indexKey, $value)) {
393
                    trigger_error("Key \"$indexKey\" does not exist in array");
394
                    return false;
395
                }
396
                if (!is_scalar($value[$indexKey])) {
397
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
398
                    return false;
399
                }
400
                $array[$value[$indexKey]] = $value[$columnKey];
401
            }
402
        }
403
        return $array;
404
    }
405
406
    /**
407
     * @param null $shippingAddress
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $shippingAddress is correct as it would always require null to be passed?
Loading history...
408
     * @param null $billingAddress
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $billingAddress is correct as it would always require null to be passed?
Loading history...
409
     * @return string
410
     */
411
    private function getUserLanguage($shippingAddress = null, $billingAddress = null)
412
    {
413
        $allowedCountries    = unserialize(Pagantis::getExtraConfig('ALLOWED_COUNTRIES', null));
414
        $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...
415
        $langArray = explode("-", $lang['language_code']);
416
        if (count($langArray) != 2 && isset($lang['locale'])) {
417
            $langArray = explode("-", $lang['locale']);
418
        }
419
        $language = Tools::strtoupper($langArray[count($langArray)-1]);
420
        // Prevent null language detection
421
        if (in_array(Tools::strtolower($language), $allowedCountries)) {
422
            return $language;
423
        }
424
        if ($shippingAddress) {
0 ignored issues
show
introduced by
$shippingAddress is of type null, thus it always evaluated to false.
Loading history...
425
            $language = Country::getIsoById($shippingAddress->id_country);
426
            if (in_array(Tools::strtolower($language), $allowedCountries)) {
427
                return $language;
428
            }
429
        }
430
        if ($billingAddress) {
0 ignored issues
show
introduced by
$billingAddress is of type null, thus it always evaluated to false.
Loading history...
431
            $language = Country::getIsoById($billingAddress->id_country);
432
            if (in_array(Tools::strtolower($language), $allowedCountries)) {
433
                return $language;
434
            }
435
        }
436
        return 'ES';
437
    }
438
}
439