Completed
Push — master ( 575141...85fc5b )
by Raúl
25s queued 19s
created

Pagantis::getUserLanguage()   B

Complexity

Conditions 8
Paths 16

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 16
c 1
b 0
f 0
nc 16
nop 0
dl 0
loc 25
rs 8.4444
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
if (!defined('_PS_VERSION_')) {
11
    exit;
12
}
13
14
define('_PS_PAGANTIS_DIR', _PS_MODULE_DIR_. '/pagantis');
0 ignored issues
show
Bug introduced by
The constant _PS_MODULE_DIR_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
15
define('PROMOTIONS_CATEGORY', 'pagantis-promotion-product');
16
define('PROMOTIONS_CATEGORY_NAME', 'Pagantis Promoted Product');
17
18
require _PS_PAGANTIS_DIR.'/vendor/autoload.php';
19
20
/**
21
 * Class Pagantis
22
 */
23
class Pagantis extends PaymentModule
0 ignored issues
show
Bug introduced by
The type PaymentModule 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...
24
{
25
    /**
26
     * @var string
27
     */
28
    public $url = 'https://pagantis.com';
29
30
    /**
31
     * @var bool
32
     */
33
    public $bootstrap = true;
34
35
    /** @var string $language */
36
    public $language;
37
38
    /**
39
     * @var null $shippingAddress
40
     */
41
    protected $shippingAddress = null;
42
    /**
43
     * @var null $billingAddress
44
     */
45
    protected $billingAddress = null;
46
    /**
47
     * @var array $allowedCountries
48
     */
49
    protected $allowedCountries = [];
50
51
    /**
52
     * Default module advanced configuration values
53
     *
54
     * @var array
55
     */
56
    public $defaultConfigs = array(
57
        'PAGANTIS_TITLE' => 'Instant Financing',
58
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE' => 'sdk.simulator.types.SELECTABLE_TEXT_CUSTOM',
59
        'PAGANTIS_SIMULATOR_DISPLAY_SKIN' => 'sdk.simulator.skins.BLUE',
60
        'PAGANTIS_SIMULATOR_DISPLAY_POSITION' => 'hookDisplayProductButtons',
61
        'PAGANTIS_SIMULATOR_START_INSTALLMENTS' => '3',
62
        'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
63
        'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION' => 'sdk.simulator.positions.INNER',
64
        'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR' => 'default',
65
        'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'default',
66
        'PAGANTIS_FORM_DISPLAY_TYPE' => '0',
67
        'PAGANTIS_DISPLAY_MIN_AMOUNT' => '1',
68
        'PAGANTIS_URL_OK' => '',
69
        'PAGANTIS_URL_KO' => '',
70
        'PAGANTIS_ALLOWED_COUNTRIES' => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
71
        'PAGANTIS_PROMOTION_EXTRA' => 'Finance this product <span class="pg-no-interest">without interest!</span>',
72
        'PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR' => '.',
73
        'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR' => ',',
74
    );
75
76
    /**
77
     * Pagantis constructor.
78
     *
79
     * Define the module main properties so that prestashop understands what are the module requirements
80
     * and how to manage the module.
81
     *
82
     */
83
    public function __construct()
84
    {
85
        $this->name = 'pagantis';
0 ignored issues
show
Bug Best Practice introduced by
The property name does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
86
        $this->tab = 'payments_gateways';
0 ignored issues
show
Bug Best Practice introduced by
The property tab does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
87
        $this->version = '8.2.15';
0 ignored issues
show
Bug Best Practice introduced by
The property version does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
88
        $this->author = 'Pagantis';
0 ignored issues
show
Bug Best Practice introduced by
The property author does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
89
        $this->currencies = true;
0 ignored issues
show
Bug Best Practice introduced by
The property currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
90
        $this->currencies_mode = 'checkbox';
0 ignored issues
show
Bug Best Practice introduced by
The property currencies_mode does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
91
        $this->module_key = '2b9bc901b4d834bb7069e7ea6510438f';
0 ignored issues
show
Bug Best Practice introduced by
The property module_key does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
92
        $this->ps_versions_compliancy = array('min' => '1.5', 'max' => _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...
Bug Best Practice introduced by
The property ps_versions_compliancy does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
93
        $this->displayName = $this->l('Pagantis');
0 ignored issues
show
Bug Best Practice introduced by
The property displayName does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
94
        $this->description = $this->l(
0 ignored issues
show
Bug Best Practice introduced by
The property description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
95
            'Instant, easy and effective financial tool for your customers'
96
        );
97
98
        $sql_file = dirname(__FILE__).'/sql/install.sql';
99
        $this->loadSQLFile($sql_file);
100
101
        $this->checkEnvVariables();
102
103
        $this->migrate();
104
105
        $this->checkHooks();
106
107
        $this->checkPromotionCategory();
108
109
        parent::__construct();
110
111
        $this->getUserLanguage();
112
    }
113
114
    /**
115
     * Configure the variables for Pagantis payment method.
116
     *
117
     * @return bool
118
     */
119
    public function install()
120
    {
121
        if (!extension_loaded('curl')) {
122
            $this->_errors[] =
0 ignored issues
show
Bug Best Practice introduced by
The property _errors does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
123
                $this->l('You have to enable the cURL extension on your server to install this module');
124
            return false;
125
        }
126
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
127
            $this->_errors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
128
            return false;
129
        }
130
131
        Configuration::updateValue('pagantis_is_enabled', 1);
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...
132
        Configuration::updateValue('pagantis_simulator_is_enabled', 1);
133
        Configuration::updateValue('pagantis_public_key', '');
134
        Configuration::updateValue('pagantis_private_key', '');
135
136
        $return =  (parent::install()
137
            && $this->registerHook('displayShoppingCart')
138
            && $this->registerHook('paymentOptions')
139
            && $this->registerHook('displayRightColumn')
140
            && $this->registerHook('displayLeftColumn')
141
            && $this->registerHook('displayRightColumnProduct')
142
            && $this->registerHook('displayLeftColumnProduct')
143
            && $this->registerHook('displayProductButtons')
144
            && $this->registerHook('displayOrderConfirmation')
145
            && $this->registerHook('header')
146
        );
147
148
        if ($return && _PS_VERSION_ < "1.7") {
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...
149
            $this->registerHook('payment');
150
        }
151
152
        return $return;
153
    }
154
155
    /**
156
     * Remove the production private api key and remove the files
157
     *
158
     * @return bool
159
     */
160
    public function uninstall()
161
    {
162
        Configuration::deleteByName('pagantis_public_key');
163
        Configuration::deleteByName('pagantis_private_key');
164
165
        return parent::uninstall();
166
    }
167
168
    /**
169
     * Migrate the configs of older versions < 7x to new configurations
170
     */
171
    public function migrate()
172
    {
173
        if (Configuration::get('PAGANTIS_MIN_AMOUNT')) {
174
            Db::getInstance()->update(
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...
175
                'pagantis_config',
176
                array('value' => Configuration::get('PAGANTIS_MIN_AMOUNT')),
177
                'config = \'PAGANTIS_DISPLAY_MIN_AMOUNT\''
178
            );
179
            Configuration::updateValue('PAGANTIS_MIN_AMOUNT', false);
180
            Configuration::updateValue('pagantis_is_enabled', 1);
181
            Configuration::updateValue('pagantis_simulator_is_enabled', 1);
182
183
            // migrating pk/tk from previous version
184
            if (Configuration::get('pagantis_public_key') === false
185
                && Configuration::get('PAGANTIS_PUBLIC_KEY_PROD')
186
            ) {
187
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAGANTIS_PUBLIC_KEY_PROD'));
188
                Configuration::updateValue('PAGANTIS_PUBLIC_KEY_PROD', false);
189
            } elseif (Configuration::get('pagantis_public_key') === false
190
                && Configuration::get('PAGANTIS_PUBLIC_KEY_TEST')
191
            ) {
192
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAGANTIS_PUBLIC_KEY_TEST'));
193
                Configuration::updateValue('PAGANTIS_PUBLIC_KEY_TEST', false);
194
            }
195
196
            if (Configuration::get('pagantis_private_key') === false
197
                && Configuration::get('PAGANTIS_PRIVATE_KEY_PROD')
198
            ) {
199
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAGANTIS_PRIVATE_KEY_PROD'));
200
                Configuration::updateValue('PAGANTIS_PRIVATE_KEY_PROD', false);
201
            } elseif (Configuration::get('pagantis_private_key') === false
202
                && Configuration::get('PAGANTIS_PRIVATE_KEY_TEST')
203
            ) {
204
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAGANTIS_PRIVATE_KEY_TEST'));
205
                Configuration::updateValue('PAGANTIS_PRIVATE_KEY_TEST', false);
206
            }
207
        }
208
    }
209
210
    /**
211
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
212
     *
213
     * @throws PrestaShopDatabaseException
214
     */
215
    public function checkHooks()
216
    {
217
        try {
218
            $sql_content = 'select * from ' . _DB_PREFIX_. 'hook_module where 
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...
219
            id_module = \'' . Module::getModuleIdByName($this->name) . '\' and 
0 ignored issues
show
Bug introduced by
The type Module 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...
220
            id_shop = \'' . Shop::getContextShopID() . '\' and 
0 ignored issues
show
Bug introduced by
The type Shop 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...
221
            id_hook = \'' . Hook::getIdByName('header') . '\'';
0 ignored issues
show
Bug introduced by
The type Hook 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...
222
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
223
            if (empty($hook_exists)) {
224
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
225
            (id_module, id_shop, id_hook, position)
226
            values
227
            (\''. Module::getModuleIdByName($this->name) . '\',
228
            \''. Shop::getContextShopID() . '\',
229
            \''. Hook::getIdByName('header') . '\',
230
            150)';
231
                Db::getInstance()->execute($sql_insert);
232
            }
233
        } catch (\Exception $exception) {
234
            // continue without errors
235
        }
236
    }
237
238
    /**
239
     * @throws PrestaShopDatabaseException
240
     */
241
    public function checkEnvVariables()
242
    {
243
        $sql_content = 'select * from ' . _DB_PREFIX_. 'pagantis_config';
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...
244
        $dbConfigs = Db::getInstance()->executeS($sql_content);
245
246
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
247
        $simpleDbConfigs = array();
248
        foreach ($dbConfigs as $config) {
249
            $simpleDbConfigs[$config['config']] = $config['value'];
250
        }
251
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
252
        if (!empty($newConfigs)) {
253
            $data = array();
254
            foreach ($newConfigs as $key => $value) {
255
                $data[] = array(
256
                    'config' => $key,
257
                    'value' => $value,
258
                );
259
            }
260
            Db::getInstance()->insert('pagantis_config', $data);
261
        }
262
    }
263
264
    /**
265
     * @param $sql_file
266
     * @return bool
267
     */
268
    public function loadSQLFile($sql_file)
269
    {
270
        try {
271
            $tableName = _DB_PREFIX_.'pagantis_order';
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...
272
            $sql = ("SHOW TABLES LIKE '$tableName'");
273
            $results = Db::getInstance()->ExecuteS($sql);
274
            if (is_array($results) && count($results) === 1) {
275
                $query = "select COLUMN_TYPE FROM information_schema.COLUMNS where 
276
                          TABLE_NAME='$tableName' AND COLUMN_NAME='ps_order_id'";
277
                $results = $results = Db::getInstance()->ExecuteS($query);
0 ignored issues
show
Unused Code introduced by
The assignment to $results is dead and can be removed.
Loading history...
278
                if (is_array($results) && count($results) === 0) {
279
                    $sql = "ALTER TABLE $tableName ADD COLUMN ps_order_id VARCHAR(60) AFTER order_id";
280
                    Db::getInstance()->Execute($sql);
281
                }
282
                return false;
283
            }
284
        } catch (\Exception $exception) {
285
            // do nothing
286
        }
287
288
        $sql_content = Tools::file_get_contents($sql_file);
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...
289
        $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
290
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
291
292
        $result = true;
293
        foreach ($sql_requests as $request) {
294
            if (!empty($request)) {
295
                $result &= Db::getInstance()->execute(trim($request));
296
            }
297
        }
298
299
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
300
    }
301
302
    /**
303
     * Check amount of order > minAmount
304
     * Check valid currency
305
     * Check API variables are set
306
     *
307
     * @return bool
308
     * @throws PrestaShopDatabaseException
309
     * @throws PrestaShopException
310
     */
311
    public function isPaymentMethodAvailable()
312
    {
313
        $cart                      = $this->context->cart;
314
        $currency                  = new Currency($cart->id_currency);
0 ignored issues
show
Bug introduced by
The type Currency 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...
315
        $availableCurrencies       = array('EUR');
316
        $pagantisDisplayMinAmount  = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
317
        $pagantisPublicKey         = Configuration::get('pagantis_public_key');
318
        $pagantisPrivateKey        = Configuration::get('pagantis_private_key');
319
        $this->allowedCountries    = unserialize(Pagantis::getExtraConfig('PAGANTIS_ALLOWED_COUNTRIES'));
320
        $this->getUserLanguage();
321
        return (
322
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
323
            in_array($currency->iso_code, $availableCurrencies) &&
324
            in_array(Tools::strtolower($this->language), $this->allowedCountries) &&
325
            $pagantisPublicKey &&
326
            $pagantisPrivateKey
327
        );
328
    }
329
330
    /**
331
     * @param Cart $cart
332
     *
333
     * @return array
334
     * @throws Exception
335
     */
336
    private function getButtonTemplateVars(Cart $cart)
0 ignored issues
show
Bug introduced by
The type Cart 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...
337
    {
338
        $currency = new Currency(($cart->id_currency));
339
340
        return array(
341
            'pagantis_button' => '#pagantis_payment_button',
342
            'pagantis_currency_iso' => $currency->iso_code,
343
            'pagantis_cart_total' => $cart->getOrderTotal(),
344
        );
345
    }
346
347
    /**
348
     * Header hook
349
     */
350
    public function hookHeader()
351
    {
352
        $url = 'https://cdn.pagantis.com/js/pg-v2/sdk.js';
353
        if (_PS_VERSION_ >= "1.7") {
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...
354
            $this->context->controller->registerJavascript(
355
                sha1(mt_rand(1, 90000)),
356
                $url,
357
                array('server' => 'remote')
358
            );
359
        } else {
360
            $this->context->controller->addJS($url);
361
        }
362
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
363
    }
364
365
    /**
366
     * @return array
367
     * @throws Exception
368
     */
369
    public function hookPaymentOptions()
370
    {
371
        /** @var Cart $cart */
372
        $cart = $this->context->cart;
373
        $this->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...
Documentation Bug introduced by
It seems like new Address($cart->id_address_delivery) of type Address is incompatible with the declared type null of property $shippingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
374
        $this->billingAddress = new Address($cart->id_address_invoice);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_invoice) of type Address is incompatible with the declared type null of property $billingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
375
        if (!$this->isPaymentMethodAvailable()) {
376
            return array();
377
        }
378
379
        /** @var Cart $cart */
380
        $cart                               = $this->context->cart;
381
        $orderTotal                         = $cart->getOrderTotal();
382
        $promotedAmount                     = 0;
383
        $link                               = $this->context->link;
384
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
385
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
386
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
387
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
388
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
389
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
390
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
391
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
392
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
393
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
394
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
395
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
396
397
        $items = $cart->getProducts(true);
398
        foreach ($items as $item) {
399
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
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...
400
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
401
                $productId = $item['id_product'];
402
                $promotedAmount += 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...
403
            }
404
        }
405
406
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
407
        $this->context->smarty->assign(array(
408
            'amount'                             => $orderTotal,
409
            'locale'                             => $this->language,
410
            'country'                            => $this->language,
411
            'pagantisPublicKey'                  => $pagantisPublicKey,
412
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
413
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
414
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
415
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
416
            'pagantisSimulatorType'              => $pagantisSimulatorType,
417
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
418
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
419
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
420
            'pagantisTitle'                      => $pagantisTitle,
421
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
422
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
423
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
424
            'promotedAmount'                     => $promotedAmount,
425
            'ps_version'                         => str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3)),
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...
426
        ));
427
428
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
429
        $paymentOption = new PrestaShop\PrestaShop\Core\Payment\PaymentOption();
0 ignored issues
show
Bug introduced by
The type PrestaShop\PrestaShop\Core\Payment\PaymentOption 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...
430
        $paymentOption
431
            ->setCallToActionText($pagantisTitle)
432
            ->setAction($link->getModuleLink('pagantis', 'payment'))
433
            ->setLogo($logo)
434
            ->setModuleName(__CLASS__)
435
        ;
436
437
        $paymentOption->setAdditionalInformation(
438
            $this->fetch('module:pagantis/views/templates/hook/checkout.tpl')
439
        );
440
441
        return array($paymentOption);
442
    }
443
444
    /**
445
     * Get the form for editing the BackOffice options of the module
446
     *
447
     * @return array
448
     */
449
    private function getConfigForm()
450
    {
451
        return array(
452
            'form' => array(
453
                'legend' => array(
454
                    'title' => $this->l('Basic Settings'),
455
                    'icon' => 'icon-cogs',
456
                ),
457
                'input' => array(
458
                    array(
459
                        'name' => 'pagantis_is_enabled',
460
                        'type' =>  (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
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...
461
                        'label' => $this->l('Module is enabled'),
462
                        'prefix' => '<i class="icon icon-key"></i>',
463
                        'class' => 't',
464
                        'required' => true,
465
                        'values'=> array(
466
                            array(
467
                                'id' => 'pagantis_is_enabled_true',
468
                                'value' => 1,
469
                                'label' => $this->l('Yes', get_class($this), null, false),
470
                            ),
471
                            array(
472
                                'id' => 'pagantis_is_enabled_false',
473
                                'value' => 0,
474
                                'label' => $this->l('No', get_class($this), null, false),
475
                            ),
476
                        )
477
                    ),
478
                    array(
479
                        'name' => 'pagantis_public_key',
480
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
481
                        'type' => 'text',
482
                        'size' => 60,
483
                        'label' => $this->l('Public Key'),
484
                        'prefix' => '<i class="icon icon-key"></i>',
485
                        'col' => 6,
486
                        'required' => true,
487
                    ),
488
                    array(
489
                        'name' => 'pagantis_private_key',
490
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
491
                        'type' => 'text',
492
                        'size' => 60,
493
                        'label' => $this->l('Secret Key'),
494
                        'prefix' => '<i class="icon icon-key"></i>',
495
                        'col' => 6,
496
                        'required' => true,
497
                    ),
498
                    array(
499
                        'name' => 'pagantis_simulator_is_enabled',
500
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
501
                        'label' => $this->l('Simulator is enabled'),
502
                        'prefix' => '<i class="icon icon-key"></i>',
503
                        'class' => 't',
504
                        'required' => true,
505
                        'values'=> array(
506
                            array(
507
                                'id' => 'pagantis_simulator_is_enabled_on',
508
                                'value' => 1,
509
                                'label' => $this->l('Yes'),
510
                            ),
511
                            array(
512
                                'id' => 'pagantis_simulator_is_enabled_off',
513
                                'value' => 0,
514
                                'label' => $this->l('No'),
515
                            ),
516
                        )
517
                    ),
518
                ),
519
                'submit' => array(
520
                    'title' => $this->l('Save'),
521
                ),
522
            ),
523
        );
524
    }
525
526
    /**
527
     * Form configuration function
528
     *
529
     * @param array $settings
530
     *
531
     * @return string
532
     */
533
    private function renderForm(array $settings)
534
    {
535
        $helper = new HelperForm();
0 ignored issues
show
Bug introduced by
The type HelperForm 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...
536
        $helper->show_toolbar = false;
537
        $helper->table = $this->table;
538
        $helper->module = $this;
539
        $helper->default_form_language = $this->context->language->id;
540
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
541
        $helper->identifier = $this->identifier;
542
        $helper->submit_action = 'submit'.$this->name;
543
        $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
0 ignored issues
show
Bug introduced by
The type AdminController 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...
544
        $helper->token = Tools::getAdminTokenLite('AdminModules');
545
        $helper->tpl_vars = array(
546
            'fields_value' => $settings,
547
            'languages' => $this->context->controller->getLanguages(),
548
            'id_language' => $this->context->language->id,
549
        );
550
551
        $helper->fields_value['pagantis_url_ok'] = Configuration::get('pagantis_url_ok');
552
553
        return $helper->generateForm(array($this->getConfigForm()));
554
    }
555
556
    /**
557
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
558
     *
559
     * @return string
560
     * @throws SmartyException
561
     */
562
    public function getContent()
563
    {
564
        $error = '';
565
        $message = '';
566
        $settings = array();
567
        $settings['pagantis_public_key'] = Configuration::get('pagantis_public_key');
568
        $settings['pagantis_private_key'] = Configuration::get('pagantis_private_key');
569
        $settingsKeys = array(
570
            'pagantis_is_enabled',
571
            'pagantis_public_key',
572
            'pagantis_private_key',
573
            'pagantis_simulator_is_enabled',
574
        );
575
576
        //Different Behavior depending on 1.6 or earlier
577
        if (Tools::isSubmit('submit'.$this->name)) {
578
            foreach ($settingsKeys as $key) {
579
                switch ($key) {
580
                    case 'pagantis_public_key':
581
                        $value = Tools::getValue($key);
582
                        if (!$value) {
583
                            $error = $this->l('Please add a Pagantis API Public Key');
584
                            break;
585
                        }
586
                        Configuration::updateValue($key, $value);
587
                        $settings[$key] = $value;
588
                        break;
589
                    case 'pagantis_private_key':
590
                        $value = Tools::getValue($key);
591
                        if (!$value) {
592
                            $error = $this->l('Please add a Pagantis API Private Key');
593
                            break;
594
                        }
595
                        Configuration::updateValue($key, $value);
596
                        $settings[$key] = $value;
597
                        break;
598
                    default:
599
                        $value = Tools::getValue($key);
600
                        Configuration::updateValue($key, $value);
601
                        $settings[$key] = $value;
602
                        break;
603
                }
604
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
605
            }
606
        } else {
607
            foreach ($settingsKeys as $key) {
608
                    $settings[$key] = Configuration::get($key);
609
            }
610
        }
611
612
        if ($error) {
613
            $message = $this->displayError($error);
614
        }
615
616
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg.png';
617
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
618
        $this->context->smarty->assign(array(
619
            'logo' => $logo,
620
            'form' => $this->renderForm($settings),
621
            'message' => $message,
622
            'version' => 'v'.$this->version,
623
        ));
624
625
        return $this->context->smarty->fetch($tpl);
626
    }
627
628
    /**
629
     * Hook to show payment method, this only applies on prestashop <= 1.6
630
     *
631
     * @param $params
632
     * @return bool | string
633
     * @throws Exception
634
     */
635
    public function hookPayment($params)
636
    {
637
        /** @var Cart $cart */
638
        $cart = $this->context->cart;
639
        $this->shippingAddress = new Address($cart->id_address_delivery);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_delivery) of type Address is incompatible with the declared type null of property $shippingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
640
        $this->billingAddress = new Address($cart->id_address_invoice);
0 ignored issues
show
Documentation Bug introduced by
It seems like new Address($cart->id_address_invoice) of type Address is incompatible with the declared type null of property $billingAddress.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
641
        if (!$this->isPaymentMethodAvailable()) {
642
            return false;
643
        }
644
645
        /** @var Cart $cart */
646
647
        $cart                               = $params['cart'];
648
        $orderTotal                         = $cart->getOrderTotal();
649
        $promotedAmount                     = 0;
650
        $link                               = $this->context->link;
651
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
652
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
653
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
654
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
655
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
656
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
657
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
658
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
659
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
660
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
661
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
662
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
663
664
        $items = $cart->getProducts(true);
665
        foreach ($items as $item) {
666
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
667
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
668
                $productId = $item['id_product'];
669
                $promotedAmount += Product::getPriceStatic($productId);
670
            }
671
        }
672
673
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
674
        $this->context->smarty->assign(array(
675
            'amount'                             => $orderTotal,
676
            'promotedAmount'                     => $promotedAmount,
677
            'locale'                             => $this->language,
678
            'country'                            => $this->language,
679
            'logo'                               => 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png',
680
            'pagantisPublicKey'                  => $pagantisPublicKey,
681
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
682
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
683
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
684
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
685
            'pagantisSimulatorType'              => $pagantisSimulatorType,
686
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
687
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
688
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
689
            'pagantisTitle'                      => $pagantisTitle,
690
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
691
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
692
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
693
            'ps_version'                         => str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3)),
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...
694
        ));
695
696
        $supercheckout_enabled = Module::isEnabled('supercheckout');
697
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
698
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
699
700
        $return = true;
701
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
702
            $this->checkLogoExists();
703
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
704
        } elseif (_PS_VERSION_ < 1.7) {
705
            $return = $this->display(__FILE__, 'views/templates/hook/checkout.tpl');
706
        }
707
        return $return;
708
    }
709
710
    /**
711
     * @param string $functionName
712
     *:
713
     * @return string
714
     * @throws PrestaShopDatabaseException
715
     * @throws PrestaShopException
716
     */
717
    public function productPageSimulatorDisplay($functionName)
718
    {
719
        $productConfiguration = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
720
        $productId = Tools::getValue('id_product');
721
        if (!$productId) {
722
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
723
        }
724
        //Resolves bug of reference passtrow
725
        $amount = Product::getPriceStatic($productId);
726
727
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
728
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
729
730
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
731
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
732
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
733
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
734
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
735
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
736
        $pagantisSimulatorQuantitySelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
737
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
738
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
739
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
740
        $pagantisDisplayMinAmount           = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
741
        $pagantisPromotionExtra             = Pagantis::getExtraConfig('PAGANTIS_PROMOTION_EXTRA');
742
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
743
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
744
        $allowedCountries                   = unserialize(Pagantis::getExtraConfig('PAGANTIS_ALLOWED_COUNTRIES'));
745
746
        if ($functionName != $productConfiguration ||
747
            $amount <= 0 ||
748
            $amount < $pagantisDisplayMinAmount ||
749
            !$pagantisSimulatorType ||
750
            !in_array(Tools::strtolower($this->language), $allowedCountries)
751
        ) {
752
            return null;
753
        }
754
755
        $this->context->smarty->assign(array(
756
            'amount'                             => $amount,
757
            'locale'                             => $this->language,
758
            'country'                            => $this->language,
759
            'pagantisPublicKey'                  => $pagantisPublicKey,
760
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
761
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
762
            'pagantisQuantitySelector'           => $pagantisSimulatorQuantitySelector,
763
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
764
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
765
            'pagantisSimulatorType'              => $pagantisSimulatorType,
766
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
767
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
768
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
769
            'isPromotedProduct'                  => $isPromotedProduct,
770
            'pagantisPromotionExtra'             => Tools::htmlentitiesDecodeUTF8($this->l($pagantisPromotionExtra)),
771
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
772
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
773
            'ps_version'                         => str_replace('.', '-', Tools::substr(_PS_VERSION_, 0, 3)),
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...
774
            'pagantisSimPreposition'           => $this->l('or'),
775
        ));
776
777
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
778
    }
779
780
    /**
781
     * @return string
782
     * @throws PrestaShopDatabaseException
783
     * @throws PrestaShopException
784
     */
785
    public function hookDisplayRightColumn()
786
    {
787
788
        return $this->productPageSimulatorDisplay(__FUNCTION__);
789
    }
790
791
    /**
792
     * @return string
793
     * @throws PrestaShopDatabaseException
794
     * @throws PrestaShopException
795
     */
796
    public function hookDisplayLeftColumn()
797
    {
798
        return $this->productPageSimulatorDisplay(__FUNCTION__);
799
    }
800
801
    /**
802
     * @return string
803
     * @throws PrestaShopDatabaseException
804
     * @throws PrestaShopException
805
     */
806
    public function hookDisplayRightColumnProduct()
807
    {
808
        return $this->productPageSimulatorDisplay(__FUNCTION__);
809
    }
810
811
    /**
812
     * @return string
813
     * @throws PrestaShopDatabaseException
814
     * @throws PrestaShopException
815
     */
816
    public function hookDisplayLeftColumnProduct()
817
    {
818
        return $this->productPageSimulatorDisplay(__FUNCTION__);
819
    }
820
821
    /**
822
     * @return string
823
     * @throws PrestaShopDatabaseException
824
     * @throws PrestaShopException
825
     */
826
    public function hookDisplayProductButtons()
827
    {
828
        return $this->productPageSimulatorDisplay(__FUNCTION__);
829
    }
830
831
    /**
832
     * @param array $params
833
     *
834
     * @return string
835
     */
836
    public function hookDisplayOrderConfirmation($params)
837
    {
838
        $paymentMethod = (_PS_VERSION_ < 1.7) ? ($params["objOrder"]->payment) : ($params["order"]->payment);
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...
839
840
        if ($paymentMethod == $this->displayName) {
841
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
842
        }
843
844
        return null;
845
    }
846
847
    /**
848
     * checkPromotionCategory
849
     */
850
    public function checkPromotionCategory()
851
    {
852
        $categories = $this->arrayColumn(Category::getCategories(null, false, false), 'name');
0 ignored issues
show
Bug introduced by
The type Category 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...
853
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
854
            /** @var CategoryCore $category */
855
            $category = new Category();
856
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
857
            $category->is_root_category = false;
858
            $category->link_rewrite = $categoryArray;
859
            $category->meta_description = $categoryArray;
860
            $category->meta_keywords = $categoryArray;
861
            $category->meta_title = $categoryArray;
862
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
863
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
864
            $category->active=0;
865
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
866
                'Use it to promote your products or brands.';
867
            $category->description = $this->l($description);
868
            $category->save();
869
        }
870
    }
871
872
873
    public static function getExtraConfig($config = null, $default = '')
874
    {
875
        if (is_null($config)) {
876
            return '';
877
        }
878
879
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . pSQL($config) . '\' limit 1';
0 ignored issues
show
Bug introduced by
The function pSQL was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

879
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . /** @scrutinizer ignore-call */ pSQL($config) . '\' limit 1';
Loading history...
Bug introduced by
The constant _DB_PREFIX_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
880
        if ($results = Db::getInstance()->ExecuteS($sql)) {
881
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
882
                return $results[0]['value'];
883
            }
884
        }
885
886
        return $default;
887
    }
888
889
    /**
890
     * Check logo exists in OPC module
891
     */
892
    public function checkLogoExists()
893
    {
894
        $logoPg = _PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments/pagantis.png';
0 ignored issues
show
Bug introduced by
The constant _PS_MODULE_DIR_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
895
        if (!file_exists($logoPg) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
896
            copy(
897
                _PS_PAGANTIS_DIR . '/logo.png',
898
                $logoPg
899
            );
900
        }
901
    }
902
903
    /**
904
     * Get user language
905
     */
906
    private function getUserLanguage()
907
    {
908
        $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...
909
        $langArray = explode("-", $lang['language_code']);
910
        if (count($langArray) != 2 && isset($lang['locale'])) {
911
            $langArray = explode("-", $lang['locale']);
912
        }
913
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
914
        // Prevent null language detection
915
        if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
916
            return;
917
        }
918
        if ($this->shippingAddress) {
919
            $this->language = Country::getIsoById($this->shippingAddress->id_country);
0 ignored issues
show
Bug introduced by
The type Country 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...
920
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
921
                return;
922
            }
923
        }
924
        if ($this->billingAddress) {
925
            $this->language = Country::getIsoById($this->billingAddress->id_country);
926
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
927
                return;
928
            }
929
        }
930
        return $this->language;
931
    }
932
933
    /**
934
     * @param array $input
935
     * @param       $columnKey
936
     * @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...
937
     *
938
     * @return array|bool
939
     */
940
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
941
    {
942
        $array = array();
943
        foreach ($input as $value) {
944
            if (!array_key_exists($columnKey, $value)) {
945
                trigger_error("Key \"$columnKey\" does not exist in array");
946
                return false;
947
            }
948
            if (is_null($indexKey)) {
949
                $array[] = $value[$columnKey];
950
            } else {
951
                if (!array_key_exists($indexKey, $value)) {
952
                    trigger_error("Key \"$indexKey\" does not exist in array");
953
                    return false;
954
                }
955
                if (!is_scalar($value[$indexKey])) {
956
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
957
                    return false;
958
                }
959
                $array[$value[$indexKey]] = $value[$columnKey];
960
            }
961
        }
962
        return $array;
963
    }
964
}
965