Passed
Pull Request — master (#46)
by
unknown
02:54
created

PagantisPaymentModuleFrontController::isPromoted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 7
rs 10
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->language = $this->getUserLanguage();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $this->language is correct as $this->getUserLanguage() targeting PagantisPaymentModuleFro...ller::getUserLanguage() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
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_.__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...
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
                    $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...
193
                    $promotedMessage = 'Promoted Item: ' . $product->getDescription() .
194
                         ' Price: ' . $finalPrice .
195
                         ' Qty: ' . $product->getQuantity() .
196
                         ' Item ID: ' . $item['id_product'];
197
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
198
                }
199
                $details->addProduct($product);
200
            }
201
202
203
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
204
            $totalAmount = (string) floor(100 * $cart->getOrderTotal(true));
205
            $orderShoppingCart
206
                ->setDetails($details)
207
                ->setOrderReference($cart->id)
208
                ->setTotalAmount($totalAmount)
209
                ->setPromotedAmount($promotedAmount)
210
            ;
211
212
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
213
            $orderConfigurationUrls
214
                ->setCancel($cancelUrl)
215
                ->setKo($cancelUrl)
216
                ->setAuthorizedNotificationCallback($okUrl)
217
                ->setRejectedNotificationCallback($okUrl)
218
                ->setOk($okUrl)
219
            ;
220
221
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
222
            $orderChannel
223
                ->setAssistedSale(false)
224
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
225
            ;
226
227
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
228
            $orderConfiguration
229
                ->setChannel($orderChannel)
230
                ->setUrls($orderConfigurationUrls)
231
                ->setPurchaseCountry($this->language)
232
            ;
233
234
            $order = new \Pagantis\OrdersApiClient\Model\Order();
235
            $order
236
                ->setConfiguration($orderConfiguration)
237
                ->setMetadata($metadataOrder)
238
                ->setShoppingCart($orderShoppingCart)
239
                ->setUser($orderUser)
240
            ;
241
        } catch (\Exception $exception) {
242
            $this->saveLog(array(), $exception);
243
            Tools::redirect($cancelUrl);
244
        }
245
246
        $url ='';
247
        try {
248
            $orderClient = new \Pagantis\OrdersApiClient\Client(
249
                $pagantisPublicKey,
250
                $pagantisPrivateKey
251
            );
252
            $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...
253
254
            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...
255
                $url = $order->getActionUrls()->getForm();
256
                $orderId = $order->getId();
257
                $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...
258
                     VALUES ('$cart->id','$orderId') 
259
                     ON DUPLICATE KEY UPDATE `order_id` = '$orderId'";
260
                $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...
261
                if (!$result) {
262
                    throw new UnknownException('Unable to save pagantis-order-id in database: '. $sql);
263
                }
264
            } else {
265
                throw new OrderNotFoundException();
266
            }
267
        } catch (\Exception $exception) {
268
            $this->saveLog(array(), $exception);
269
            Tools::redirect($cancelUrl);
270
        }
271
272
        if (!$iframe) {
273
            Tools::redirect($url);
274
        } else {
275
            $this->context->smarty->assign(array(
276
                'url'           => $url,
277
                'checkoutUrl'   => $cancelUrl,
278
            ));
279
280
            try {
281
                if (_PS_VERSION_ < 1.7) {
282
                    $this->setTemplate('payment-15.tpl');
283
                } else {
284
                    $this->setTemplate('module:pagantis/views/templates/front/payment-17.tpl');
285
                }
286
            } catch (\Exception $exception) {
287
                $this->saveLog(array(), $exception);
288
                Tools::redirect($url);
289
            }
290
        }
291
    }
292
293
    /**
294
     * @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...
295
     * @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...
296
     * @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...
297
     * @return mixed|null
298
     */
299
    private function getNationalId($customer = null, $addressOne = null, $addressTwo = null)
300
    {
301
        if ($customer !== null && isset($customer->national_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
302
            return $customer->national_id;
303
        } elseif ($addressOne !== null and isset($addressOne->national_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
304
            return $addressOne->national_id;
305
        } elseif ($addressOne !== null and isset($addressOne->dni)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
306
            return $addressOne->dni;
307
        } elseif ($addressTwo !== null and isset($addressTwo->national_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
308
            return $addressTwo->national_id;
309
        } elseif ($addressTwo !== null and isset($addressTwo->dni)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
310
            return $addressTwo->dni;
311
        } else {
312
            return null;
313
        }
314
    }
315
316
    /**
317
     * @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...
318
     * @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...
319
     * @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...
320
     * @return mixed|null
321
     */
322
    private function getTaxId($customer = null, $addressOne = null, $addressTwo = null)
323
    {
324
        if ($customer !== null && isset($customer->tax_id)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
325
            return $customer->tax_id;
326
        } elseif ($customer !== null && isset($customer->fiscalcode)) {
0 ignored issues
show
introduced by
The condition $customer !== null is always false.
Loading history...
327
            return $customer->fiscalcode;
328
        } elseif ($addressOne !== null and isset($addressOne->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressOne !== null is always false.
Loading history...
329
            return $addressOne->tax_id;
330
        } elseif ($addressTwo !== null and isset($addressTwo->tax_id)) {
0 ignored issues
show
introduced by
The condition $addressTwo !== null is always false.
Loading history...
331
            return $addressTwo->tax_id;
332
        } else {
333
            return null;
334
        }
335
    }
336
337
    /**
338
     * @param $item
339
     *
340
     * @return bool
341
     */
342
    private function isPromoted($itemId)
343
    {
344
        $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...
345
        if (in_array(PROMOTIONS_CATEGORY_NAME, array_column($itemCategories, 'name')) !== false) {
346
            return true;
347
        }
348
        return false;
349
    }
350
351
    /**
352
     * Get user language
353
     */
354
    private function getUserLanguage()
355
    {
356
        $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...
357
        $langArray = explode("-", $lang['language_code']);
358
        if (count($langArray) != 2 && isset($lang['locale'])) {
359
            $langArray = explode("-", $lang['locale']);
360
        }
361
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
362
        // Prevent null language detection
363
        $this->language = ($this->language) ? $this->language : 'ES';
364
    }
365
}
366