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

PagantisPaymentModuleFrontController   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 246
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 175
dl 0
loc 246
rs 10
c 0
b 0
f 0
wmc 18

2 Methods

Rating   Name   Duplication   Size   Complexity  
A addLog() 0 25 2
F postProcess() 0 206 16
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 = getenv('PAGANTIS_FORM_DISPLAY_TYPE');
81
        $cancelUrl = (getenv('PAGANTIS_URL_KO') !== '') ? getenv('PAGANTIS_URL_KO') : $koUrl;
82
        $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...
83
        $pagantisPrivateKey = Configuration::get('pagantis_private_key');
84
        $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...
85
                 .'index.php?canonical=true&fc=module&module=pagantis&controller=notify&'
86
                 .http_build_query($query)
87
        ;
88
89
        $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...
90
        $billingAddress = new Address($cart->id_address_invoice);
91
        $curlInfo = curl_version();
92
        $curlVersion = $curlInfo['version'];
93
        $metadata = array(
94
            '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...
95
            'pagantis' => $this->module->version,
96
            'php' => phpversion(),
97
            'curl' => $curlVersion,
98
        );
99
100
        try {
101
            $userAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
102
            $userAddress
103
                ->setZipCode($shippingAddress->postcode)
104
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
105
                ->setCountryCode('ES')
106
                ->setCity($shippingAddress->city)
107
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
108
            ;
109
110
            $orderShippingAddress =  new \Pagantis\OrdersApiClient\Model\Order\User\Address();
111
            $orderShippingAddress
112
                ->setZipCode($shippingAddress->postcode)
113
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
114
                ->setCountryCode('ES')
115
                ->setCity($shippingAddress->city)
116
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
117
                ->setDni($shippingAddress->dni)
118
                ->setFixPhone($shippingAddress->phone)
119
                ->setMobilePhone($shippingAddress->phone_mobile)
120
            ;
121
122
            $orderBillingAddress = new \Pagantis\OrdersApiClient\Model\Order\User\Address();
123
            $orderBillingAddress
124
                ->setZipCode($billingAddress->postcode)
125
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
126
                ->setCountryCode('ES')
127
                ->setCity($billingAddress->city)
128
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
129
                ->setDni($billingAddress->dni)
130
                ->setFixPhone($billingAddress->phone)
131
                ->setMobilePhone($billingAddress->phone_mobile)
132
            ;
133
134
            $orderUser = new \Pagantis\OrdersApiClient\Model\Order\User();
135
            $orderUser
136
                ->setAddress($userAddress)
137
                ->setFullName($orderShippingAddress->getFullName())
138
                ->setBillingAddress($orderBillingAddress)
139
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
140
                ->setFixPhone($shippingAddress->phone)
141
                ->setMobilePhone($shippingAddress->phone_mobile)
142
                ->setShippingAddress($orderShippingAddress)
143
                ->setDni($shippingAddress->dni)
144
            ;
145
146
            if ($customer->birthday!='0000-00-00') {
147
                $orderUser->setDateOfBirth($customer->birthday);
148
            }
149
150
            $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...
151
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
152
            foreach ($orders as $order) {
153
                if ($order['valid']) {
154
                    $orderHistory = new \Pagantis\OrdersApiClient\Model\Order\User\OrderHistory();
155
                    $orderHistory
156
                        ->setAmount((int) (100 * $order['total_paid']))
157
                        ->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

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