Passed
Pull Request — master (#23)
by Cesar
02:07
created

PaylaterPaymentModuleFrontController::addLog()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 20
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 25
rs 9.6
1
<?php
2
3
require_once('AbstractController.php');
4
5
/**
6
 * Class PaylaterRedirectModuleFrontController
7
 */
8
class PaylaterPaymentModuleFrontController extends AbstractController
9
{
10
    /**
11
     * @param $customer
12
     * @param $exception
13
     */
14
    protected function addLog($customer, $exception)
15
    {
16
        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...
17
            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...
18
                'PagaMasTarde Exception For user ' .
19
                $customer->email .
20
                ' : ' .
21
                $exception->getMessage(),
22
                3,
23
                $exception->getCode(),
24
                null,
25
                null,
26
                true
27
            );
28
        } else {
29
            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...
30
                'PagaMasTarde Exception For user ' .
31
                $customer->email .
32
                ' : ' .
33
                $exception->getMessage(),
34
                3,
35
                $exception->getCode(),
36
                null,
37
                null,
38
                true
39
            );
40
        }
41
    }
42
43
    /**
44
     * Process Post Request
45
     *
46
     * @throws \Exception
47
     */
48
    public function postProcess()
49
    {
50
        /** @var Cart $cart */
51
        $cart = $this->context->cart;
52
53
        if (!$cart->id) {
54
            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...
55
        }
56
57
        /** @var Customer $customer */
58
        $customer = $this->context->customer;
59
        $query = array(
60
            'id_cart' => $cart->id,
61
            'key' => $cart->secure_key,
62
        );
63
64
        $koUrl = $this->context->link->getPageLink(
65
            'order',
66
            null,
67
            null,
68
            array('step'=>3)
69
        );
70
        $iframe = getenv('PMT_FORM_DISPLAY_TYPE');
71
        $cancelUrl = (getenv('PMT_URL_KO') !== '') ? getenv('PMT_URL_KO') : $koUrl;
72
        $paylaterPublicKey = Configuration::get('pmt_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...
73
        $paylaterPrivateKey = Configuration::get('pmt_private_key');
74
        $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...
75
                 .'index.php?canonical=true&fc=module&module=paylater&controller=notify&'
76
                 .http_build_query($query)
77
        ;
78
79
        $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...
80
        $billingAddress = new Address($cart->id_address_invoice);
81
        $curlInfo = curl_version();
82
        $curlVersion = $curlInfo['version'];
83
        $metadata = array(
84
            '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...
85
            'pmt' => $this->module->version,
86
            'php' => phpversion(),
87
            'curl' => $curlVersion,
88
        );
89
90
        try {
91
            $userAddress =  new \PagaMasTarde\OrdersApiClient\Model\Order\User\Address();
92
            $userAddress
93
                ->setZipCode($shippingAddress->postcode)
94
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
95
                ->setCountryCode('ES')
96
                ->setCity($shippingAddress->city)
97
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
98
            ;
99
100
            $orderShippingAddress =  new \PagaMasTarde\OrdersApiClient\Model\Order\User\Address();
101
            $orderShippingAddress
102
                ->setZipCode($shippingAddress->postcode)
103
                ->setFullName($shippingAddress->firstname . ' ' . $shippingAddress->lastname)
104
                ->setCountryCode('ES')
105
                ->setCity($shippingAddress->city)
106
                ->setAddress($shippingAddress->address1 . ' ' . $shippingAddress->address2)
107
                ->setDni($shippingAddress->dni)
108
                ->setFixPhone($shippingAddress->phone)
109
                ->setMobilePhone($shippingAddress->phone_mobile)
110
            ;
111
112
            $orderBillingAddress = new \PagaMasTarde\OrdersApiClient\Model\Order\User\Address();
113
            $orderBillingAddress
114
                ->setZipCode($billingAddress->postcode)
115
                ->setFullName($billingAddress->firstname . ' ' . $billingAddress->lastname)
116
                ->setCountryCode('ES')
117
                ->setCity($billingAddress->city)
118
                ->setAddress($billingAddress->address1 . ' ' . $billingAddress->address2)
119
                ->setDni($billingAddress->dni)
120
                ->setFixPhone($billingAddress->phone)
121
                ->setMobilePhone($billingAddress->phone_mobile)
122
            ;
123
124
            $orderUser = new \PagaMasTarde\OrdersApiClient\Model\Order\User();
125
            $orderUser
126
                ->setAddress($userAddress)
127
                ->setFullName($orderShippingAddress->getFullName())
128
                ->setBillingAddress($orderBillingAddress)
129
                ->setEmail($this->context->cookie->logged ? $this->context->cookie->email : $customer->email)
130
                ->setFixPhone($shippingAddress->phone)
131
                ->setMobilePhone($shippingAddress->phone_mobile)
132
                ->setShippingAddress($orderShippingAddress)
133
                ->setDni($shippingAddress->dni)
134
            ;
135
136
            if ($customer->birthday!='0000-00-00') {
137
                $orderUser->setDateOfBirth($customer->birthday);
138
            }
139
140
            $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...
141
            /** @var \PrestaShop\PrestaShop\Adapter\Entity\Order $order */
142
            foreach ($orders as $order) {
143
                if ($order['valid']) {
144
                    $orderHistory = new \PagaMasTarde\OrdersApiClient\Model\Order\User\OrderHistory();
145
                    $orderHistory
146
                        ->setAmount(intval(100 * $order['total_paid']))
147
                        ->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 PagaMasTarde\OrdersApiCl...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

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