Passed
Pull Request — master (#68)
by Raúl
04:13
created

arrayColumn()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 16
nc 6
nop 3
dl 0
loc 23
rs 9.1111
c 0
b 0
f 0
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
        /** @var Customer $customer */
71
        $customer = $this->context->customer;
72
        $query = array(
73
            'id_cart' => $cart->id,
74
            'key' => $cart->secure_key,
75
        );
76
77
        $koUrl = $this->context->link->getPageLink(
78
            'order',
79
            null,
80
            null,
81
            array('step'=>3)
82
        );
83
        $iframe = Pagantis::getExtraConfig('PAGANTIS_FORM_DISPLAY_TYPE');
84
        $cancelUrl = (Pagantis::getExtraConfig('PAGANTIS_URL_KO') !== '') ?
85
            Pagantis::getExtraConfig('PAGANTIS_URL_KO') : $koUrl;
86
        $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...
87
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
88
        $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...
89
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&origin=redirect&'
90
                 .http_build_query($query)
91
        ;
92
        $notificationOkUrl = _PS_BASE_URL_SSL_.__PS_BASE_URI__
93
            .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&origin=notification&'
94
            .http_build_query($query)
95
        ;
96
97
        $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...
98
        $billingAddress = new Address($cart->id_address_invoice);
99
        $curlInfo = curl_version();
100
        $curlVersion = $curlInfo['version'];
101
        $metadata = array(
102
            '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...
103
            'pagantis' => $this->module->version,
104
            'php' => phpversion(),
105
            'curl' => $curlVersion,
106
        );
107
108
        try {
109
            $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...
110
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
111
            $userAddress
112
                ->setZipCode($shippingAddress->postcode)
113
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
114
                ->setCountryCode($shippingCountry)
115
                ->setCity($shippingAddress->city)
116
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
117
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
118
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
119
            ;
120
121
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
122
            $orderShippingAddress
123
                ->setZipCode($shippingAddress->postcode)
124
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
125
                ->setCountryCode($shippingCountry)
126
                ->setCity($shippingAddress->city)
127
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
128
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
129
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
130
                ->setFixPhone($shippingAddress->phone)
131
                ->setMobilePhone($shippingAddress->phone_mobile)
132
            ;
133
134
            $billingCountry = Country::getIsoById($billingAddress->id_country);
135
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
136
            $orderBillingAddress
137
                ->setZipCode($billingAddress->postcode)
138
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
139
                ->setCountryCode($billingCountry)
140
                ->setCity($billingAddress->city)
141
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
142
                ->setTaxId($this->getTaxId($customer, $billingAddress, $shippingAddress))
143
                ->setNationalId($this->getNationalId($customer, $billingAddress, $shippingAddress))
144
                ->setFixPhone($billingAddress->phone)
145
                ->setMobilePhone($billingAddress->phone_mobile)
146
            ;
147
148
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
149
            $orderUser
150
                ->setAddress($userAddress)
151
                ->setFullName($orderShippingAddress->getFullName())
152
                ->setBillingAddress($orderBillingAddress)
153
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
154
                ->setFixPhone($shippingAddress->phone)
155
                ->setMobilePhone($shippingAddress->phone_mobile)
156
                ->setShippingAddress($orderShippingAddress)
157
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
158
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
159
            ;
160
161
            if ($customer->birthday!='0000-00-00') {
162
                $orderUser->setDateOfBirth($customer->birthday);
163
            }
164
165
            $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...
166
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
167
            foreach ($orders as $order) {
168
                if ($order['valid']) {
169
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
170
                    $orderHistory
171
                        ->setAmount((string) floor(100 * $order['total_paid']))
172
                        ->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

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