Passed
Pull Request — master (#34)
by Raúl
02:07
created

PaylaterPaymentModuleFrontController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 246
Duplicated Lines 0 %

Importance

Changes 15
Bugs 1 Features 2
Metric Value
eloc 175
c 15
b 1
f 2
dl 0
loc 246
rs 10
wmc 18

1 Method

Rating   Name   Duplication   Size   Complexity  
A PagantisPaymentModuleFrontController::addLog() 0 25 2
1
<?php
2
/**
3
 * This file is part of the official Pagantis module for PrestaShop.
4
 *
5
 * @author    Pagantis <[email protected]>
6
 * @copyright 2019 Pagantis
7
 * @license   proprietary
8
 */
9
10
require_once('AbstractController.php');
11
12
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
13
use Pagantis\ModuleUtils\Exception\UnknownException;
14
15
/**
16
 * Class PagantisRedirectModuleFrontController
17
 */
18
class PagantisPaymentModuleFrontController extends AbstractController
19
{
20
    /**
21
     * @param $customer
22
     * @param $exception
23
     */
24
    protected function addLog($customer, $exception)
25
    {
26
        if (_PS_VERSION_ < 1.6) {
0 ignored issues
show
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
27
            Logger::addLog(
0 ignored issues
show
Bug introduced by
The type Logger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
28
                'Pagantis Exception For user ' .
29
                $customer->email .
30
                ' : ' .
31
                $exception->getMessage(),
32
                3,
33
                $exception->getCode(),
34
                null,
35
                null,
36
                true
37
            );
38
        } else {
39
            PrestaShopLogger::addLog(
0 ignored issues
show
Bug introduced by
The type PrestaShopLogger was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
40
                'Pagantis Exception For user ' .
41
                $customer->email .
42
                ' : ' .
43
                $exception->getMessage(),
44
                3,
45
                $exception->getCode(),
46
                null,
47
                null,
48
                true
49
            );
50
        }
51
    }
52
53
    /**
54
     * Process Post Request
55
     *
56
     * @throws \Exception
57
     */
58
    public function postProcess()
59
    {
60
        /** @var Cart $cart */
61
        $cart = $this->context->cart;
62
63
        if (!$cart->id) {
64
            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...
65
        }
66
67
        /** @var Customer $customer */
68
        $customer = $this->context->customer;
69
        $query = array(
70
            'id_cart' => $cart->id,
71
            'key' => $cart->secure_key,
72
        );
73
74
        $koUrl = $this->context->link->getPageLink(
75
            'order',
76
            null,
77
            null,
78
            array('step'=>3)
79
        );
80
        $iframe = Pagantis::getExtraConfig('PAGANTIS_FORM_DISPLAY_TYPE');
81
        $cancelUrl = (Pagantis::getExtraConfig('PAGANTIS_URL_KO') !== '') ?
82
            Pagantis::getExtraConfig('PAGANTIS_URL_KO') : $koUrl;
83
        $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...
84
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
85
        $okUrl = _PS_BASE_URL_.__PS_BASE_URI__
0 ignored issues
show
Bug introduced by
The constant _PS_BASE_URL_ 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...
86
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&'
87
                 .http_build_query($query)
88
        ;
89
90
        $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...
91
        $billingAddress = new Address($cart->id_address_invoice);
92
        $curlInfo = curl_version();
93
        $curlVersion = $curlInfo['version'];
94
        $metadata = array(
95
            '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...
96
            'pagantis' => $this->module->version,
97
            'php' => phpversion(),
98
            'curl' => $curlVersion,
99
        );
100
101
        try {
102
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
103
            $userAddress
104
                ->setZipCode($shippingAddress->postcode)
105
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
106
                ->setCountryCode('ES')
107
                ->setCity($shippingAddress->city)
108
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
109
            ;
110
111
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
112
            $orderShippingAddress
113
                ->setZipCode($shippingAddress->postcode)
114
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
115
                ->setCountryCode('ES')
116
                ->setCity($shippingAddress->city)
117
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
118
                ->setDni($shippingAddress->dni)
119
                ->setFixPhone($shippingAddress->phone)
120
                ->setMobilePhone($shippingAddress->phone_mobile)
121
            ;
122
123
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
124
            $orderBillingAddress
125
                ->setZipCode($billingAddress->postcode)
126
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
127
                ->setCountryCode('ES')
128
                ->setCity($billingAddress->city)
129
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
130
                ->setDni($billingAddress->dni)
131
                ->setFixPhone($billingAddress->phone)
132
                ->setMobilePhone($billingAddress->phone_mobile)
133
            ;
134
135
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
136
            $orderUser
137
                ->setAddress($userAddress)
138
                ->setFullName($orderShippingAddress->getFullName())
139
                ->setBillingAddress($orderBillingAddress)
140
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
141
                ->setFixPhone($shippingAddress->phone)
142
                ->setMobilePhone($shippingAddress->phone_mobile)
143
                ->setShippingAddress($orderShippingAddress)
144
                ->setDni($shippingAddress->dni)
145
            ;
146
147
            if ($customer->birthday!='0000-00-00') {
148
                $orderUser->setDateOfBirth($customer->birthday);
149
            }
150
151
            $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...
152
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
153
            foreach ($orders as $order) {
154
                if ($order['valid']) {
155
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
156
                    $orderHistory
157
                        ->setAmount((int) (100 * $order['total_paid']))
158
                        ->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

158
                        ->setDate(/** @scrutinizer ignore-type */ new \DateTime($order['date_add']))
Loading history...
159
                    ;
160
                    $orderUser->addOrderHistory($orderHistory);
161
                }
162
            }
163
164
            $details = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details();
165
            $details->setShippingCost((int) (100 * $cart->getTotalShippingCost()));
166
            $items = $cart->getProducts();
167
            foreach ($items as $key => $item) {
168
                $product = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product();
169
                $product
170
                    ->setAmount((int) (100 * $item['price_wt']))
171
                    ->setQuantity($item['quantity'])
172
                    ->setDescription($item['name']);
173
                $details->addProduct($product);
174
            }
175
176
            $orderShoppingCart = new \Pagantis\OrdersApiClient\Model\Order\ShoppingCart();
177
            $orderShoppingCart
178
                ->setDetails($details)
179
                ->setOrderReference($cart->id)
180
                ->setPromotedAmount(0)
181
                ->setTotalAmount((int) (100 * $cart->getOrderTotal(true)))
182
            ;
183
184
            $orderConfigurationUrls = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Urls();
185
            $orderConfigurationUrls
186
                ->setCancel($cancelUrl)
187
                ->setKo($cancelUrl)
188
                ->setAuthorizedNotificationCallback($okUrl)
189
                ->setRejectedNotificationCallback($okUrl)
190
                ->setOk($okUrl)
191
            ;
192
193
            $orderChannel = new \Pagantis\OrdersApiClient\Model\Order\Configuration\Channel();
194
            $orderChannel
195
                ->setAssistedSale(false)
196
                ->setType(\Pagantis\OrdersApiClient\Model\Order\Configuration\Channel::ONLINE)
197
            ;
198
199
            $orderConfiguration = new \Pagantis\OrdersApiClient\Model\Order\Configuration();
200
            $orderConfiguration
201
                ->setChannel($orderChannel)
202
                ->setUrls($orderConfigurationUrls)
203
            ;
204
205
            $metadataOrder = new \Pagantis\OrdersApiClient\Model\Order\Metadata();
206
            foreach ($metadata as $key => $metadatum) {
207
                $metadataOrder
208
                    ->addMetadata($key, $metadatum);
209
            }
210
211
            $order = new \Pagantis\OrdersApiClient\Model\Order();
212
            $order
213
                ->setConfiguration($orderConfiguration)
214
                ->setMetadata($metadataOrder)
215
                ->setShoppingCart($orderShoppingCart)
216
                ->setUser($orderUser)
217
            ;
218
        } catch (\Exception $exception) {
219
            $this->saveLog(array(), $exception);
220
            Tools::redirect($cancelUrl);
221
        }
222
223
        $url ='';
224
        try {
225
            $orderClient = new \Pagantis\OrdersApiClient\Client(
226
                $pagantisPublicKey,
227
                $pagantisPrivateKey
228
            );
229
            $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...
230
            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...
231
                $url = $order->getActionUrls()->getForm();
232
                $orderId = $order->getId();
233
                $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...
234
                     VALUES ('$cart->id','$orderId') 
235
                     ON DUPLICATE KEY UPDATE `order_id` = '$orderId'";
236
                $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...
237
                if (!$result) {
238
                    throw new UnknownException('Unable to save pagantis-order-id in database: '. $sql);
239
                }
240
            } else {
241
                throw new OrderNotFoundException();
242
            }
243
        } catch (\Exception $exception) {
244
            $this->saveLog(array(), $exception);
245
            Tools::redirect($cancelUrl);
246
        }
247
248
        if (!$iframe) {
249
            Tools::redirect($url);
250
        } else {
251
            $this->context->smarty->assign(array(
252
                'url'           => $url,
253
                'checkoutUrl'   => $cancelUrl,
254
            ));
255
256
            try {
257
                if (_PS_VERSION_ < 1.7) {
258
                    $this->setTemplate('payment-15.tpl');
259
                } else {
260
                    $this->setTemplate('module:pagantis/views/templates/front/payment-17.tpl');
261
                }
262
            } catch (\Exception $exception) {
263
                $this->saveLog(array(), $exception);
264
                Tools::redirect($url);
265
            }
266
        }
267
    }
268
}
269