Passed
Pull Request — master (#64)
by Raúl
03:39
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 2015-2016 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 TABLE_NAME='$tableName' AND COLUMN_NAME='ps_order_id'";
276
                $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...
277
                if (is_array($results) && count($results) === 0) {
278
                    $sql = "ALTER TABLE $tableName ADD COLUMN ps_order_id VARCHAR(60) AFTER order_id";
279
                    Db::getInstance()->Execute($sql);
280
                }
281
                return false;
282
            }
283
        } catch (\Exception $exception) {
284
            // do nothing
285
        }
286
287
        $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...
288
        $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
289
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
290
291
        $result = true;
292
        foreach ($sql_requests as $request) {
293
            if (!empty($request)) {
294
                $result &= Db::getInstance()->execute(trim($request));
295
            }
296
        }
297
298
        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...
299
    }
300
301
    /**
302
     * Check amount of order > minAmount
303
     * Check valid currency
304
     * Check API variables are set
305
     *
306
     * @return bool
307
     * @throws PrestaShopDatabaseException
308
     * @throws PrestaShopException
309
     */
310
    public function isPaymentMethodAvailable()
311
    {
312
        $cart                      = $this->context->cart;
313
        $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...
314
        $availableCurrencies       = array('EUR');
315
        $pagantisDisplayMinAmount  = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
316
        $pagantisPublicKey         = Configuration::get('pagantis_public_key');
317
        $pagantisPrivateKey        = Configuration::get('pagantis_private_key');
318
        $this->allowedCountries    = unserialize(Pagantis::getExtraConfig('PAGANTIS_ALLOWED_COUNTRIES'));
319
        $this->getUserLanguage();
320
        return (
321
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
322
            in_array($currency->iso_code, $availableCurrencies) &&
323
            in_array(Tools::strtolower($this->language), $this->allowedCountries) &&
324
            $pagantisPublicKey &&
325
            $pagantisPrivateKey
326
        );
327
    }
328
329
    /**
330
     * @param Cart $cart
331
     *
332
     * @return array
333
     * @throws Exception
334
     */
335
    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...
336
    {
337
        $currency = new Currency(($cart->id_currency));
338
339
        return array(
340
            'pagantis_button' => '#pagantis_payment_button',
341
            'pagantis_currency_iso' => $currency->iso_code,
342
            'pagantis_cart_total' => $cart->getOrderTotal(),
343
        );
344
    }
345
346
    /**
347
     * Header hook
348
     */
349
    public function hookHeader()
350
    {
351
        $url = 'https://cdn.pagantis.com/js/pg-v2/sdk.js';
352
        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...
353
            $this->context->controller->registerJavascript(
354
                sha1(mt_rand(1, 90000)),
355
                $url,
356
                array('server' => 'remote')
357
            );
358
        } else {
359
            $this->context->controller->addJS($url);
360
        }
361
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
362
    }
363
364
    /**
365
     * @return array
366
     * @throws Exception
367
     */
368
    public function hookPaymentOptions()
369
    {
370
        /** @var Cart $cart */
371
        $cart = $this->context->cart;
372
        $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...
373
        $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...
374
        if (!$this->isPaymentMethodAvailable()) {
375
            return array();
376
        }
377
378
        /** @var Cart $cart */
379
        $cart                               = $this->context->cart;
380
        $orderTotal                         = $cart->getOrderTotal();
381
        $promotedAmount                     = 0;
382
        $link                               = $this->context->link;
383
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
384
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
385
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
386
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
387
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
388
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
389
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
390
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
391
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
392
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
393
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
394
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
395
396
        $items = $cart->getProducts(true);
397
        foreach ($items as $key => $item) {
398
            $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...
399
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
400
                $productId = $item['id_product'];
401
                $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...
402
            }
403
        }
404
405
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
406
        $this->context->smarty->assign(array(
407
            'amount'                             => $orderTotal,
408
            'locale'                             => $this->language,
409
            'country'                            => $this->language,
410
            'pagantisPublicKey'                  => $pagantisPublicKey,
411
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
412
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
413
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
414
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
415
            'pagantisSimulatorType'              => $pagantisSimulatorType,
416
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
417
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
418
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
419
            'pagantisTitle'                      => $pagantisTitle,
420
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
421
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
422
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
423
            'promotedAmount'                     => $promotedAmount,
424
            '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...
425
        ));
426
427
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
428
        $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...
429
        $paymentOption
430
            ->setCallToActionText($pagantisTitle)
431
            ->setAction($link->getModuleLink('pagantis', 'payment'))
432
            ->setLogo($logo)
433
            ->setModuleName(__CLASS__)
434
        ;
435
436
        $paymentOption->setAdditionalInformation(
437
            $this->fetch('module:pagantis/views/templates/hook/checkout.tpl')
438
        );
439
440
        return array($paymentOption);
441
    }
442
443
    /**
444
     * Get the form for editing the BackOffice options of the module
445
     *
446
     * @return array
447
     */
448
    private function getConfigForm()
449
    {
450
        return array(
451
            'form' => array(
452
                'legend' => array(
453
                    'title' => $this->l('Basic Settings'),
454
                    'icon' => 'icon-cogs',
455
                ),
456
                'input' => array(
457
                    array(
458
                        'name' => 'pagantis_is_enabled',
459
                        '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...
460
                        'label' => $this->l('Module is enabled'),
461
                        'prefix' => '<i class="icon icon-key"></i>',
462
                        'class' => 't',
463
                        'required' => true,
464
                        'values'=> array(
465
                            array(
466
                                'id' => 'pagantis_is_enabled_true',
467
                                'value' => 1,
468
                                'label' => $this->l('Yes', get_class($this), null, false),
469
                            ),
470
                            array(
471
                                'id' => 'pagantis_is_enabled_false',
472
                                'value' => 0,
473
                                'label' => $this->l('No', get_class($this), null, false),
474
                            ),
475
                        )
476
                    ),
477
                    array(
478
                        'name' => 'pagantis_public_key',
479
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
480
                        'type' => 'text',
481
                        'size' => 60,
482
                        'label' => $this->l('Public Key'),
483
                        'prefix' => '<i class="icon icon-key"></i>',
484
                        'col' => 6,
485
                        'required' => true,
486
                    ),
487
                    array(
488
                        'name' => 'pagantis_private_key',
489
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
490
                        'type' => 'text',
491
                        'size' => 60,
492
                        'label' => $this->l('Secret Key'),
493
                        'prefix' => '<i class="icon icon-key"></i>',
494
                        'col' => 6,
495
                        'required' => true,
496
                    ),
497
                    array(
498
                        'name' => 'pagantis_simulator_is_enabled',
499
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
500
                        'label' => $this->l('Simulator is enabled'),
501
                        'prefix' => '<i class="icon icon-key"></i>',
502
                        'class' => 't',
503
                        'required' => true,
504
                        'values'=> array(
505
                            array(
506
                                'id' => 'pagantis_simulator_is_enabled_on',
507
                                'value' => 1,
508
                                'label' => $this->l('Yes'),
509
                            ),
510
                            array(
511
                                'id' => 'pagantis_simulator_is_enabled_off',
512
                                'value' => 0,
513
                                'label' => $this->l('No'),
514
                            ),
515
                        )
516
                    ),
517
                ),
518
                'submit' => array(
519
                    'title' => $this->l('Save'),
520
                ),
521
            ),
522
        );
523
    }
524
525
    /**
526
     * Form configuration function
527
     *
528
     * @param array $settings
529
     *
530
     * @return string
531
     */
532
    private function renderForm(array $settings)
533
    {
534
        $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...
535
        $helper->show_toolbar = false;
536
        $helper->table = $this->table;
537
        $helper->module = $this;
538
        $helper->default_form_language = $this->context->language->id;
539
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
540
        $helper->identifier = $this->identifier;
541
        $helper->submit_action = 'submit'.$this->name;
542
        $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...
543
        $helper->token = Tools::getAdminTokenLite('AdminModules');
544
        $helper->tpl_vars = array(
545
            'fields_value' => $settings,
546
            'languages' => $this->context->controller->getLanguages(),
547
            'id_language' => $this->context->language->id,
548
        );
549
550
        $helper->fields_value['pagantis_url_ok'] = Configuration::get('pagantis_url_ok');
551
552
        return $helper->generateForm(array($this->getConfigForm()));
553
    }
554
555
    /**
556
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
557
     *
558
     * @return string
559
     * @throws SmartyException
560
     */
561
    public function getContent()
562
    {
563
        $error = '';
564
        $message = '';
565
        $settings = array();
566
        $settings['pagantis_public_key'] = Configuration::get('pagantis_public_key');
567
        $settings['pagantis_private_key'] = Configuration::get('pagantis_private_key');
568
        $settingsKeys = array(
569
            'pagantis_is_enabled',
570
            'pagantis_public_key',
571
            'pagantis_private_key',
572
            'pagantis_simulator_is_enabled',
573
        );
574
575
        //Different Behavior depending on 1.6 or earlier
576
        if (Tools::isSubmit('submit'.$this->name)) {
577
            foreach ($settingsKeys as $key) {
578
                switch ($key) {
579
                    case 'pagantis_public_key':
580
                        $value = Tools::getValue($key);
581
                        if (!$value) {
582
                            $error = $this->l('Please add a Pagantis API Public Key');
583
                            break;
584
                        }
585
                        Configuration::updateValue($key, $value);
586
                        $settings[$key] = $value;
587
                        break;
588
                    case 'pagantis_private_key':
589
                        $value = Tools::getValue($key);
590
                        if (!$value) {
591
                            $error = $this->l('Please add a Pagantis API Private Key');
592
                            break;
593
                        }
594
                        Configuration::updateValue($key, $value);
595
                        $settings[$key] = $value;
596
                        break;
597
                    default:
598
                        $value = Tools::getValue($key);
599
                        Configuration::updateValue($key, $value);
600
                        $settings[$key] = $value;
601
                        break;
602
                }
603
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
604
            }
605
        } else {
606
            foreach ($settingsKeys as $key) {
607
                    $settings[$key] = Configuration::get($key);
608
            }
609
        }
610
611
        if ($error) {
612
            $message = $this->displayError($error);
613
        }
614
615
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg.png';
616
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
617
        $this->context->smarty->assign(array(
618
            'logo' => $logo,
619
            'form' => $this->renderForm($settings),
620
            'message' => $message,
621
            'version' => 'v'.$this->version,
622
        ));
623
624
        return $this->context->smarty->fetch($tpl);
625
    }
626
627
    /**
628
     * Hook to show payment method, this only applies on prestashop <= 1.6
629
     *
630
     * @param $params
631
     * @return bool | string
632
     * @throws Exception
633
     */
634
    public function hookPayment($params)
635
    {
636
        /** @var Cart $cart */
637
        $cart = $this->context->cart;
638
        $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...
639
        $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...
640
        if (!$this->isPaymentMethodAvailable()) {
641
            return false;
642
        }
643
644
        /** @var Cart $cart */
645
646
        $cart                               = $params['cart'];
647
        $orderTotal                         = $cart->getOrderTotal();
648
        $promotedAmount                     = 0;
649
        $link                               = $this->context->link;
650
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
651
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
652
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
653
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
654
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
655
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
656
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
657
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
658
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
659
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
660
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
661
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
662
663
        $items = $cart->getProducts(true);
664
        foreach ($items as $key => $item) {
665
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
666
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
667
                $productId = $item['id_product'];
668
                $promotedAmount += Product::getPriceStatic($productId);
669
            }
670
        }
671
672
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
673
        $this->context->smarty->assign(array(
674
            'amount'                             => $orderTotal,
675
            'promotedAmount'                     => $promotedAmount,
676
            'locale'                             => $this->language,
677
            'country'                            => $this->language,
678
            'logo'                               => 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png',
679
            'pagantisPublicKey'                  => $pagantisPublicKey,
680
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
681
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
682
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
683
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
684
            'pagantisSimulatorType'              => $pagantisSimulatorType,
685
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
686
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
687
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
688
            'pagantisTitle'                      => $pagantisTitle,
689
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
690
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
691
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
692
            '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...
693
        ));
694
695
        $supercheckout_enabled = Module::isEnabled('supercheckout');
696
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
697
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
698
699
        $return = true;
700
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
701
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
702
        } elseif (_PS_VERSION_ < 1.7) {
703
            $return = $this->display(__FILE__, 'views/templates/hook/checkout.tpl');
704
        }
705
        return $return;
706
    }
707
708
    /**
709
     * @param string $functionName
710
     *:
711
     * @return string
712
     * @throws PrestaShopDatabaseException
713
     * @throws PrestaShopException
714
     */
715
    public function productPageSimulatorDisplay($functionName)
716
    {
717
        $productConfiguration = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
718
        $productId = Tools::getValue('id_product');
719
        if (!$productId) {
720
            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...
721
        }
722
        //Resolves bug of reference passtrow
723
        $amount = Product::getPriceStatic($productId);
724
725
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
726
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
727
728
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
729
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
730
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
731
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
732
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
733
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
734
        $pagantisSimulatorQuantitySelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
735
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
736
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
737
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
738
        $pagantisDisplayMinAmount           = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
739
        $pagantisPromotionExtra             = Pagantis::getExtraConfig('PAGANTIS_PROMOTION_EXTRA');
740
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
741
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
742
743
        if ($functionName != $productConfiguration ||
744
            $amount <= 0 ||
745
            $amount < $pagantisDisplayMinAmount ||
746
            !$pagantisSimulatorType
747
        ) {
748
            return null;
749
        }
750
751
        $this->context->smarty->assign(array(
752
            'amount'                             => $amount,
753
            'locale'                             => $this->language,
754
            'country'                            => $this->language,
755
            'pagantisPublicKey'                  => $pagantisPublicKey,
756
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
757
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
758
            'pagantisQuantitySelector'           => $pagantisSimulatorQuantitySelector,
759
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
760
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
761
            'pagantisSimulatorType'              => $pagantisSimulatorType,
762
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
763
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
764
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
765
            'isPromotedProduct'                  => $isPromotedProduct,
766
            'pagantisPromotionExtra'             => Tools::htmlentitiesDecodeUTF8($this->l($pagantisPromotionExtra)),
767
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
768
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
769
            '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...
770
            'pagantisSimPreposition'           => $this->l('or'),
771
        ));
772
773
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
774
    }
775
776
    /**
777
     * @return string
778
     * @throws PrestaShopDatabaseException
779
     * @throws PrestaShopException
780
     */
781
    public function hookDisplayRightColumn()
782
    {
783
784
        return $this->productPageSimulatorDisplay(__FUNCTION__);
785
    }
786
787
    /**
788
     * @return string
789
     * @throws PrestaShopDatabaseException
790
     * @throws PrestaShopException
791
     */
792
    public function hookDisplayLeftColumn()
793
    {
794
        return $this->productPageSimulatorDisplay(__FUNCTION__);
795
    }
796
797
    /**
798
     * @return string
799
     * @throws PrestaShopDatabaseException
800
     * @throws PrestaShopException
801
     */
802
    public function hookDisplayRightColumnProduct()
803
    {
804
        return $this->productPageSimulatorDisplay(__FUNCTION__);
805
    }
806
807
    /**
808
     * @return string
809
     * @throws PrestaShopDatabaseException
810
     * @throws PrestaShopException
811
     */
812
    public function hookDisplayLeftColumnProduct()
813
    {
814
        return $this->productPageSimulatorDisplay(__FUNCTION__);
815
    }
816
817
    /**
818
     * @return string
819
     * @throws PrestaShopDatabaseException
820
     * @throws PrestaShopException
821
     */
822
    public function hookDisplayProductButtons()
823
    {
824
        return $this->productPageSimulatorDisplay(__FUNCTION__);
825
    }
826
827
    /**
828
     * @param array $params
829
     *
830
     * @return string
831
     */
832
    public function hookDisplayOrderConfirmation($params)
833
    {
834
        $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...
835
836
        if ($paymentMethod == $this->displayName) {
837
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
838
        }
839
840
        return null;
841
    }
842
843
    /**
844
     * checkPromotionCategory
845
     */
846
    public function checkPromotionCategory()
847
    {
848
        $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...
849
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
850
            /** @var CategoryCore $category */
851
            $category = new Category();
852
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
853
            $category->is_root_category = false;
854
            $category->link_rewrite = $categoryArray;
855
            $category->meta_description = $categoryArray;
856
            $category->meta_keywords = $categoryArray;
857
            $category->meta_title = $categoryArray;
858
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
859
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
860
            $category->active=0;
861
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
862
                'Use it to promote your products or brands.';
863
            $category->description = $this->l($description);
864
            $category->save();
865
        }
866
    }
867
868
869
    public static function getExtraConfig($config = null, $default = '')
870
    {
871
        if (is_null($config)) {
872
            return '';
873
        }
874
875
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . pSQL($config) . '\' limit 1';
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...
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

875
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . /** @scrutinizer ignore-call */ pSQL($config) . '\' limit 1';
Loading history...
876
        if ($results = Db::getInstance()->ExecuteS($sql)) {
877
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
878
                return $results[0]['value'];
879
            }
880
        }
881
882
        return $default;
883
    }
884
885
    /**
886
     * Get user language
887
     */
888
    private function getUserLanguage()
889
    {
890
        $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...
891
        $langArray = explode("-", $lang['language_code']);
892
        if (count($langArray) != 2 && isset($lang['locale'])) {
893
            $langArray = explode("-", $lang['locale']);
894
        }
895
        $this->language = Tools::strtoupper($langArray[count($langArray)-1]);
896
        // Prevent null language detection
897
        if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
898
            return;
899
        }
900
        if ($this->shippingAddress) {
901
            $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...
902
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
903
                return;
904
            }
905
        }
906
        if ($this->billingAddress) {
907
            $this->language = Country::getIsoById($this->billingAddress->id_country);
908
            if (in_array(Tools::strtolower($this->language), $this->allowedCountries)) {
909
                return;
910
            }
911
        }
912
        return $this->language;
913
    }
914
915
    /**
916
     * @param array $input
917
     * @param       $columnKey
918
     * @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...
919
     *
920
     * @return array|bool
921
     */
922
    private function arrayColumn(array $input, $columnKey, $indexKey = null)
923
    {
924
        $array = array();
925
        foreach ($input as $value) {
926
            if (!array_key_exists($columnKey, $value)) {
927
                trigger_error("Key \"$columnKey\" does not exist in array");
928
                return false;
929
            }
930
            if (is_null($indexKey)) {
931
                $array[] = $value[$columnKey];
932
            } else {
933
                if (!array_key_exists($indexKey, $value)) {
934
                    trigger_error("Key \"$indexKey\" does not exist in array");
935
                    return false;
936
                }
937
                if (!is_scalar($value[$indexKey])) {
938
                    trigger_error("Key \"$indexKey\" does not contain scalar value");
939
                    return false;
940
                }
941
                $array[$value[$indexKey]] = $value[$columnKey];
942
            }
943
        }
944
        return $array;
945
    }
946
}
947