Completed
Push — master ( e05d95...575141 )
by pablo
24s queued 11s
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
        $this->getUserLanguage();
64
65
        /** @var Cart $cart */
66
        $cart = $this->context->cart;
67
68
        if (!$cart->id) {
69
            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...
70
        }
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
        $iframe = Pagantis::getExtraConfig('PAGANTIS_FORM_DISPLAY_TYPE');
86
        $cancelUrl = (Pagantis::getExtraConfig('PAGANTIS_URL_KO') !== '') ?
87
            Pagantis::getExtraConfig('PAGANTIS_URL_KO') : $koUrl;
88
        $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...
89
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
90
        $okUrl = _PS_BASE_URL_SSL_.__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_SSL_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
91
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&'
92
                 .http_build_query($query)
93
        ;
94
95
        $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...
96
        $billingAddress = new Address($cart->id_address_invoice);
97
        $curlInfo = curl_version();
98
        $curlVersion = $curlInfo['version'];
99
        $metadata = array(
100
            '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...
101
            'pagantis' => $this->module->version,
102
            'php' => phpversion(),
103
            'curl' => $curlVersion,
104
        );
105
106
        try {
107
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
108
            $userAddress
109
                ->setZipCode($shippingAddress->postcode)
110
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
111
                ->setCountryCode($this->language)
112
                ->setCity($shippingAddress->city)
113
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
114
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
115
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
116
            ;
117
118
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
119
            $orderShippingAddress
120
                ->setZipCode($shippingAddress->postcode)
121
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
122
                ->setCountryCode($this->language)
123
                ->setCity($shippingAddress->city)
124
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
125
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
126
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
127
                ->setFixPhone($shippingAddress->phone)
128
                ->setMobilePhone($shippingAddress->phone_mobile)
129
            ;
130
131
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
132
            $orderBillingAddress
133
                ->setZipCode($billingAddress->postcode)
134
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
135
                ->setCountryCode($this->language)
136
                ->setCity($billingAddress->city)
137
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
138
                ->setTaxId($this->getTaxId($customer, $billingAddress, $shippingAddress))
139
                ->setNationalId($this->getNationalId($customer, $billingAddress, $shippingAddress))
140
                ->setFixPhone($billingAddress->phone)
141
                ->setMobilePhone($billingAddress->phone_mobile)
142
            ;
143
144
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
145
            $orderUser
146
                ->setAddress($userAddress)
147
                ->setFullName($orderShippingAddress->getFullName())
148
                ->setBillingAddress($orderBillingAddress)
149
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
150
                ->setFixPhone($shippingAddress->phone)
151
                ->setMobilePhone($shippingAddress->phone_mobile)
152
                ->setShippingAddress($orderShippingAddress)
153
                ->setTaxId($this->getTaxId($customer, $shippingAddress, $billingAddress))
154
                ->setNationalId($this->getNationalId($customer, $shippingAddress, $billingAddress))
155
            ;
156
157
            if ($customer->birthday!='0000-00-00') {
158
                $orderUser->setDateOfBirth($customer->birthday);
159
            }
160
161
            $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...
162
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
163
            foreach ($orders as $order) {
164
                if ($order['valid']) {
165
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
166
                    $orderHistory
167
                        ->setAmount((string) floor(100 * $order['total_paid']))
168
                        ->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

168
                        ->setDate(/** @scrutinizer ignore-type */ new \DateTime($order['date_add']))
Loading history...
169
                    ;
170
                    $orderUser->addOrderHistory($orderHistory);
171
                }
172
            }
173
174
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
175
            foreach ($metadata as $key => $metadatum) {
176
                $metadataOrder->addMetadata($key, $metadatum);
177
            }
178
179
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
180
            $details->setShippingCost((string) floor(100 * $cart->getTotalShippingCost()));
181
            $items = $cart->getProducts();
182
            $promotedAmount = 0;
183
            foreach ($items as $key => $item) {
184
                $promotedProduct = $this->isPromoted($item['id_product']);
185
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
186
                $product
187
                    ->setAmount((string) floor(100 * $item['price_wt']))
188
                    ->setQuantity($item['quantity'])
189
                    ->setDescription($item['name']);
190
                if ($promotedProduct) {
191
                    $promotedAmount+=$product->getAmount();
192
                    $productId = $item['id_product'];
193
                    $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...
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, $this->arrayColumn($itemCategories, 'name')) !== false) {
347
            return true;
348
        }
349
        return false;
350
    }
351
352
    /**
353
     * Get user language
354
     */
355
    private function getUserLanguage()
356
    {
357
        $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...
358
        $langArray = explode("-", $lang['language_code']);
359
        if (count($langArray) != 2 && isset($lang['locale'])) {
360
            $langArray = explode("-", $lang['locale']);
361
        }
362
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
363
        // Prevent null language detection
364
        $this->language = ($this->language) ? $this->language : 'ES';
365
    }
366
367
    /**
368
     * @param array $input
369
     * @param       $columnKey
370
     * @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...
371
     *
372
     * @return array|bool
373
     */
374
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
375
    {
376
        $array = array();
377
        foreach ($input as $value) {
378
            if (!array_key_exists($columnKey, $value)) {
379
                trigger_error("Key \"$columnKey\" does not exist in array");
380
                return false;
381
            }
382
            if (is_null($indexKey)) {
383
                $array[] = $value[$columnKey];
384
            } else {
385
                if (!array_key_exists($indexKey, $value)) {
386
                    trigger_error("Key \"$indexKey\" does not exist in array");
387
                    return false;
388
                }
389
                if (!is_scalar($value[$indexKey])) {
390
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
391
                    return false;
392
                }
393
                $array[$value[$indexKey]] = $value[$columnKey];
394
            }
395
        }
396
        return $array;
397
    }
398
}
399