Completed
Push — master ( ebe6e6...69cc20 )
by Raúl
18s queued 12s
created

Pagantis   F

Complexity

Total Complexity 118

Size/Duplication

Total Lines 945
Duplicated Lines 0 %

Importance

Changes 10
Bugs 1 Features 0
Metric Value
eloc 530
dl 0
loc 945
rs 2
c 10
b 1
f 0
wmc 118

27 Methods

Rating   Name   Duplication   Size   Complexity  
A checkLogoExists() 0 7 3
B getUserLanguage() 0 25 8
B isPaymentMethodAvailable() 0 18 7
B getConfigForm() 0 72 3
A hookDisplayRightColumnProduct() 0 3 1
A renderForm() 0 21 1
A hookDisplayLeftColumn() 0 3 1
A uninstall() 0 6 1
B productPageSimulatorDisplay() 0 63 9
B migrate() 0 35 10
A hookDisplayProductButtons() 0 3 1
B getContent() 0 64 9
A checkEnvVariables() 0 20 4
A hookHeader() 0 13 2
A arrayColumn() 0 23 6
A hookDisplayLeftColumnProduct() 0 3 1
A getExtraConfig() 0 14 6
A __construct() 0 29 1
A hookDisplayOrderConfirmation() 0 9 3
B loadSQLFile() 0 32 8
B hookPayment() 0 73 8
A checkHooks() 0 19 3
A checkPromotionCategory() 0 19 2
A getButtonTemplateVars() 0 8 1
B hookPaymentOptions() 0 73 4
C install() 0 34 14
A hookDisplayRightColumn() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like Pagantis often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Pagantis, and based on these observations, apply Extract Interface, too.

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 = array();
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_DISPLAY_MAX_AMOUNT' => '0',
69
        'PAGANTIS_URL_OK' => '',
70
        'PAGANTIS_URL_KO' => '',
71
        'PAGANTIS_ALLOWED_COUNTRIES' => 'a:3:{i:0;s:2:"es";i:1;s:2:"it";i:2;s:2:"fr";}',
72
        'PAGANTIS_PROMOTION_EXTRA' => 'Finance this product <span class="pg-no-interest">without interest!</span>',
73
        'PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR' => '.',
74
        'PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR' => ',',
75
    );
76
77
    /**
78
     * Pagantis constructor.
79
     *
80
     * Define the module main properties so that prestashop understands what are the module requirements
81
     * and how to manage the module.
82
     *
83
     */
84
    public function __construct()
85
    {
86
        $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...
87
        $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...
88
        $this->version = '8.3.2';
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...
89
        $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...
90
        $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...
91
        $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...
92
        $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...
93
        $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...
94
        $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...
95
        $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...
96
            'Instant, easy and effective financial tool for your customers'
97
        );
98
99
        $sql_file = dirname(__FILE__).'/sql/install.sql';
100
        $this->loadSQLFile($sql_file);
101
102
        $this->checkEnvVariables();
103
104
        $this->migrate();
105
106
        $this->checkHooks();
107
108
        $this->checkPromotionCategory();
109
110
        parent::__construct();
111
112
        $this->getUserLanguage();
113
    }
114
115
    /**
116
     * Configure the variables for Pagantis payment method.
117
     *
118
     * @return bool
119
     */
120
    public function install()
121
    {
122
        if (!extension_loaded('curl')) {
123
            $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...
124
                $this->l('You have to enable the cURL extension on your server to install this module');
125
            return false;
126
        }
127
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
128
            $this->_errors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
129
            return false;
130
        }
131
132
        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...
133
        Configuration::updateValue('pagantis_simulator_is_enabled', 1);
134
        Configuration::updateValue('pagantis_public_key', '');
135
        Configuration::updateValue('pagantis_private_key', '');
136
137
        $return =  (parent::install()
138
            && $this->registerHook('displayShoppingCart')
139
            && $this->registerHook('paymentOptions')
140
            && $this->registerHook('displayRightColumn')
141
            && $this->registerHook('displayLeftColumn')
142
            && $this->registerHook('displayRightColumnProduct')
143
            && $this->registerHook('displayLeftColumnProduct')
144
            && $this->registerHook('displayProductButtons')
145
            && $this->registerHook('displayOrderConfirmation')
146
            && $this->registerHook('header')
147
        );
148
149
        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...
150
            $this->registerHook('payment');
151
        }
152
153
        return $return;
154
    }
155
156
    /**
157
     * Remove the production private api key and remove the files
158
     *
159
     * @return bool
160
     */
161
    public function uninstall()
162
    {
163
        Configuration::deleteByName('pagantis_public_key');
164
        Configuration::deleteByName('pagantis_private_key');
165
166
        return parent::uninstall();
167
    }
168
169
    /**
170
     * Migrate the configs of older versions < 7x to new configurations
171
     */
172
    public function migrate()
173
    {
174
        if (Configuration::get('PAGANTIS_MIN_AMOUNT')) {
175
            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...
176
                'pagantis_config',
177
                array('value' => Configuration::get('PAGANTIS_MIN_AMOUNT')),
178
                'config = \'PAGANTIS_DISPLAY_MIN_AMOUNT\''
179
            );
180
            Configuration::updateValue('PAGANTIS_MIN_AMOUNT', false);
181
            Configuration::updateValue('pagantis_is_enabled', 1);
182
            Configuration::updateValue('pagantis_simulator_is_enabled', 1);
183
184
            // migrating pk/tk from previous version
185
            if (Configuration::get('pagantis_public_key') === false
186
                && Configuration::get('PAGANTIS_PUBLIC_KEY_PROD')
187
            ) {
188
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAGANTIS_PUBLIC_KEY_PROD'));
189
                Configuration::updateValue('PAGANTIS_PUBLIC_KEY_PROD', false);
190
            } elseif (Configuration::get('pagantis_public_key') === false
191
                && Configuration::get('PAGANTIS_PUBLIC_KEY_TEST')
192
            ) {
193
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAGANTIS_PUBLIC_KEY_TEST'));
194
                Configuration::updateValue('PAGANTIS_PUBLIC_KEY_TEST', false);
195
            }
196
197
            if (Configuration::get('pagantis_private_key') === false
198
                && Configuration::get('PAGANTIS_PRIVATE_KEY_PROD')
199
            ) {
200
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAGANTIS_PRIVATE_KEY_PROD'));
201
                Configuration::updateValue('PAGANTIS_PRIVATE_KEY_PROD', false);
202
            } elseif (Configuration::get('pagantis_private_key') === false
203
                && Configuration::get('PAGANTIS_PRIVATE_KEY_TEST')
204
            ) {
205
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAGANTIS_PRIVATE_KEY_TEST'));
206
                Configuration::updateValue('PAGANTIS_PRIVATE_KEY_TEST', false);
207
            }
208
        }
209
    }
210
211
    /**
212
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
213
     *
214
     * @throws PrestaShopDatabaseException
215
     */
216
    public function checkHooks()
217
    {
218
        try {
219
            $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...
220
            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...
221
            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...
222
            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...
223
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
224
            if (empty($hook_exists)) {
225
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
226
            (id_module, id_shop, id_hook, position)
227
            values
228
            (\''. Module::getModuleIdByName($this->name) . '\',
229
            \''. Shop::getContextShopID() . '\',
230
            \''. Hook::getIdByName('header') . '\',
231
            150)';
232
                Db::getInstance()->execute($sql_insert);
233
            }
234
        } catch (\Exception $exception) {
235
            // continue without errors
236
        }
237
    }
238
239
    /**
240
     * @throws PrestaShopDatabaseException
241
     */
242
    public function checkEnvVariables()
243
    {
244
        $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...
245
        $dbConfigs = Db::getInstance()->executeS($sql_content);
246
247
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
248
        $simpleDbConfigs = array();
249
        foreach ($dbConfigs as $config) {
250
            $simpleDbConfigs[$config['config']] = $config['value'];
251
        }
252
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
253
        if (!empty($newConfigs)) {
254
            $data = array();
255
            foreach ($newConfigs as $key => $value) {
256
                $data[] = array(
257
                    'config' => $key,
258
                    'value' => $value,
259
                );
260
            }
261
            Db::getInstance()->insert('pagantis_config', $data);
262
        }
263
    }
264
265
    /**
266
     * @param $sql_file
267
     * @return bool
268
     */
269
    public function loadSQLFile($sql_file)
270
    {
271
        try {
272
            $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...
273
            $sql = ("SHOW TABLES LIKE '$tableName'");
274
            $results = Db::getInstance()->ExecuteS($sql);
275
            if (is_array($results) && count($results) === 1) {
276
                $query = "select COLUMN_TYPE FROM information_schema.COLUMNS where 
277
                          TABLE_NAME='$tableName' AND COLUMN_NAME='ps_order_id'";
278
                $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...
279
                if (is_array($results) && count($results) === 0) {
280
                    $sql = "ALTER TABLE $tableName ADD COLUMN ps_order_id VARCHAR(60) AFTER order_id";
281
                    Db::getInstance()->Execute($sql);
282
                }
283
                return false;
284
            }
285
        } catch (\Exception $exception) {
286
            // do nothing
287
        }
288
289
        $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...
290
        $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
291
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
292
293
        $result = true;
294
        foreach ($sql_requests as $request) {
295
            if (!empty($request)) {
296
                $result &= Db::getInstance()->execute(trim($request));
297
            }
298
        }
299
300
        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...
301
    }
302
303
    /**
304
     * Check amount of order > minAmount
305
     * Check valid currency
306
     * Check API variables are set
307
     *
308
     * @return bool
309
     * @throws PrestaShopDatabaseException
310
     * @throws PrestaShopException
311
     */
312
    public function isPaymentMethodAvailable()
313
    {
314
        $cart                      = $this->context->cart;
315
        $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...
316
        $availableCurrencies       = array('EUR');
317
        $pagantisDisplayMinAmount  = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
318
        $pagantisDisplayMaxAmount  = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MAX_AMOUNT');
319
        $pagantisPublicKey         = Configuration::get('pagantis_public_key');
320
        $pagantisPrivateKey        = Configuration::get('pagantis_private_key');
321
        $this->allowedCountries    = unserialize(Pagantis::getExtraConfig('PAGANTIS_ALLOWED_COUNTRIES'));
322
        $this->getUserLanguage();
323
        return (
324
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
325
            ($cart->getOrderTotal() <= $pagantisDisplayMaxAmount || $pagantisDisplayMaxAmount == '0') &&
326
            in_array($currency->iso_code, $availableCurrencies) &&
327
            in_array(Tools::strtolower($this->language), $this->allowedCountries) &&
328
            $pagantisPublicKey &&
329
            $pagantisPrivateKey
330
        );
331
    }
332
333
    /**
334
     * @param Cart $cart
335
     *
336
     * @return array
337
     * @throws Exception
338
     */
339
    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...
340
    {
341
        $currency = new Currency(($cart->id_currency));
342
343
        return array(
344
            'pagantis_button' => '#pagantis_payment_button',
345
            'pagantis_currency_iso' => $currency->iso_code,
346
            'pagantis_cart_total' => $cart->getOrderTotal(),
347
        );
348
    }
349
350
    /**
351
     * Header hook
352
     */
353
    public function hookHeader()
354
    {
355
        $url = 'https://cdn.pagantis.com/js/pg-v2/sdk.js';
356
        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...
357
            $this->context->controller->registerJavascript(
358
                sha1(mt_rand(1, 90000)),
359
                $url,
360
                array('server' => 'remote')
361
            );
362
        } else {
363
            $this->context->controller->addJS($url);
364
        }
365
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
366
    }
367
368
    /**
369
     * @return array
370
     * @throws Exception
371
     */
372
    public function hookPaymentOptions()
373
    {
374
        /** @var Cart $cart */
375
        $cart = $this->context->cart;
376
        $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...
377
        $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...
378
        if (!$this->isPaymentMethodAvailable()) {
379
            return array();
380
        }
381
382
        /** @var Cart $cart */
383
        $cart                               = $this->context->cart;
384
        $orderTotal                         = $cart->getOrderTotal();
385
        $promotedAmount                     = 0;
386
        $link                               = $this->context->link;
387
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
388
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
389
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
390
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
391
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
392
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
393
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
394
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
395
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
396
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
397
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
398
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
399
400
        $items = $cart->getProducts(true);
401
        foreach ($items as $item) {
402
            $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...
403
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
404
                $productId = $item['id_product'];
405
                $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...
406
            }
407
        }
408
409
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
410
        $this->context->smarty->assign(array(
411
            'amount'                             => $orderTotal,
412
            'locale'                             => $this->language,
413
            'country'                            => $this->language,
414
            'pagantisPublicKey'                  => $pagantisPublicKey,
415
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
416
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
417
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
418
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
419
            'pagantisSimulatorType'              => $pagantisSimulatorType,
420
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
421
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
422
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
423
            'pagantisTitle'                      => $pagantisTitle,
424
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
425
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
426
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
427
            'promotedAmount'                     => $promotedAmount,
428
            '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...
429
        ));
430
431
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png';
432
        $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...
433
        $paymentOption
434
            ->setCallToActionText($pagantisTitle)
435
            ->setAction($link->getModuleLink('pagantis', 'payment'))
436
            ->setLogo($logo)
437
            ->setModuleName(__CLASS__)
438
        ;
439
440
        $paymentOption->setAdditionalInformation(
441
            $this->fetch('module:pagantis/views/templates/hook/checkout.tpl')
442
        );
443
444
        return array($paymentOption);
445
    }
446
447
    /**
448
     * Get the form for editing the BackOffice options of the module
449
     *
450
     * @return array
451
     */
452
    private function getConfigForm()
453
    {
454
        return array(
455
            'form' => array(
456
                'legend' => array(
457
                    'title' => $this->l('Basic Settings'),
458
                    'icon' => 'icon-cogs',
459
                ),
460
                'input' => array(
461
                    array(
462
                        'name' => 'pagantis_is_enabled',
463
                        '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...
464
                        'label' => $this->l('Module is enabled'),
465
                        'prefix' => '<i class="icon icon-key"></i>',
466
                        'class' => 't',
467
                        'required' => true,
468
                        'values'=> array(
469
                            array(
470
                                'id' => 'pagantis_is_enabled_true',
471
                                'value' => 1,
472
                                'label' => $this->l('Yes', get_class($this), null, false),
473
                            ),
474
                            array(
475
                                'id' => 'pagantis_is_enabled_false',
476
                                'value' => 0,
477
                                'label' => $this->l('No', get_class($this), null, false),
478
                            ),
479
                        )
480
                    ),
481
                    array(
482
                        'name' => 'pagantis_public_key',
483
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
484
                        'type' => 'text',
485
                        'size' => 60,
486
                        'label' => $this->l('Public Key'),
487
                        'prefix' => '<i class="icon icon-key"></i>',
488
                        'col' => 6,
489
                        'required' => true,
490
                    ),
491
                    array(
492
                        'name' => 'pagantis_private_key',
493
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
494
                        'type' => 'text',
495
                        'size' => 60,
496
                        'label' => $this->l('Secret Key'),
497
                        'prefix' => '<i class="icon icon-key"></i>',
498
                        'col' => 6,
499
                        'required' => true,
500
                    ),
501
                    array(
502
                        'name' => 'pagantis_simulator_is_enabled',
503
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
504
                        'label' => $this->l('Simulator is enabled'),
505
                        'prefix' => '<i class="icon icon-key"></i>',
506
                        'class' => 't',
507
                        'required' => true,
508
                        'values'=> array(
509
                            array(
510
                                'id' => 'pagantis_simulator_is_enabled_on',
511
                                'value' => 1,
512
                                'label' => $this->l('Yes'),
513
                            ),
514
                            array(
515
                                'id' => 'pagantis_simulator_is_enabled_off',
516
                                'value' => 0,
517
                                'label' => $this->l('No'),
518
                            ),
519
                        )
520
                    ),
521
                ),
522
                'submit' => array(
523
                    'title' => $this->l('Save'),
524
                ),
525
            ),
526
        );
527
    }
528
529
    /**
530
     * Form configuration function
531
     *
532
     * @param array $settings
533
     *
534
     * @return string
535
     */
536
    private function renderForm(array $settings)
537
    {
538
        $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...
539
        $helper->show_toolbar = false;
540
        $helper->table = $this->table;
541
        $helper->module = $this;
542
        $helper->default_form_language = $this->context->language->id;
543
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
544
        $helper->identifier = $this->identifier;
545
        $helper->submit_action = 'submit'.$this->name;
546
        $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...
547
        $helper->token = Tools::getAdminTokenLite('AdminModules');
548
        $helper->tpl_vars = array(
549
            'fields_value' => $settings,
550
            'languages' => $this->context->controller->getLanguages(),
551
            'id_language' => $this->context->language->id,
552
        );
553
554
        $helper->fields_value['pagantis_url_ok'] = Configuration::get('pagantis_url_ok');
555
556
        return $helper->generateForm(array($this->getConfigForm()));
557
    }
558
559
    /**
560
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
561
     *
562
     * @return string
563
     * @throws SmartyException
564
     */
565
    public function getContent()
566
    {
567
        $error = '';
568
        $message = '';
569
        $settings = array();
570
        $settings['pagantis_public_key'] = Configuration::get('pagantis_public_key');
571
        $settings['pagantis_private_key'] = Configuration::get('pagantis_private_key');
572
        $settingsKeys = array(
573
            'pagantis_is_enabled',
574
            'pagantis_public_key',
575
            'pagantis_private_key',
576
            'pagantis_simulator_is_enabled',
577
        );
578
579
        //Different Behavior depending on 1.6 or earlier
580
        if (Tools::isSubmit('submit'.$this->name)) {
581
            foreach ($settingsKeys as $key) {
582
                switch ($key) {
583
                    case 'pagantis_public_key':
584
                        $value = Tools::getValue($key);
585
                        if (!$value) {
586
                            $error = $this->l('Please add a Pagantis API Public Key');
587
                            break;
588
                        }
589
                        Configuration::updateValue($key, $value);
590
                        $settings[$key] = $value;
591
                        break;
592
                    case 'pagantis_private_key':
593
                        $value = Tools::getValue($key);
594
                        if (!$value) {
595
                            $error = $this->l('Please add a Pagantis API Private Key');
596
                            break;
597
                        }
598
                        Configuration::updateValue($key, $value);
599
                        $settings[$key] = $value;
600
                        break;
601
                    default:
602
                        $value = Tools::getValue($key);
603
                        Configuration::updateValue($key, $value);
604
                        $settings[$key] = $value;
605
                        break;
606
                }
607
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
608
            }
609
        } else {
610
            foreach ($settingsKeys as $key) {
611
                    $settings[$key] = Configuration::get($key);
612
            }
613
        }
614
615
        if ($error) {
616
            $message = $this->displayError($error);
617
        }
618
619
        $logo = 'https://cdn.digitalorigin.com/assets/master/logos/pg.png';
620
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
621
        $this->context->smarty->assign(array(
622
            'logo' => $logo,
623
            'form' => $this->renderForm($settings),
624
            'message' => $message,
625
            'version' => 'v'.$this->version,
626
        ));
627
628
        return $this->context->smarty->fetch($tpl);
629
    }
630
631
    /**
632
     * Hook to show payment method, this only applies on prestashop <= 1.6
633
     *
634
     * @param $params
635
     * @return bool | string
636
     * @throws Exception
637
     */
638
    public function hookPayment($params)
639
    {
640
        /** @var Cart $cart */
641
        $cart = $this->context->cart;
642
        $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...
643
        $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...
644
        if (!$this->isPaymentMethodAvailable()) {
645
            return false;
646
        }
647
648
        /** @var Cart $cart */
649
650
        $cart                               = $params['cart'];
651
        $orderTotal                         = $cart->getOrderTotal();
652
        $promotedAmount                     = 0;
653
        $link                               = $this->context->link;
654
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
655
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
656
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
657
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
658
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
659
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
660
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
661
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
662
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
663
        $pagantisTitle                      = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
664
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
665
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
666
667
        $items = $cart->getProducts(true);
668
        foreach ($items as $item) {
669
            $itemCategories = ProductCore::getProductCategoriesFull($item['id_product']);
670
            if (in_array(PROMOTIONS_CATEGORY_NAME, $this->arrayColumn($itemCategories, 'name')) !== false) {
671
                $productId = $item['id_product'];
672
                $promotedAmount += Product::getPriceStatic($productId);
673
            }
674
        }
675
676
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
677
        $this->context->smarty->assign(array(
678
            'amount'                             => $orderTotal,
679
            'promotedAmount'                     => $promotedAmount,
680
            'locale'                             => $this->language,
681
            'country'                            => $this->language,
682
            'logo'                               => 'https://cdn.digitalorigin.com/assets/master/logos/pg-favicon.png',
683
            'pagantisPublicKey'                  => $pagantisPublicKey,
684
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
685
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
686
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
687
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
688
            'pagantisSimulatorType'              => $pagantisSimulatorType,
689
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
690
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
691
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
692
            'pagantisTitle'                      => $pagantisTitle,
693
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
694
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
695
            'paymentUrl'                         => $link->getModuleLink('pagantis', 'payment'),
696
            '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...
697
        ));
698
699
        $supercheckout_enabled = Module::isEnabled('supercheckout');
700
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
701
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
702
703
        $return = true;
704
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
705
            $this->checkLogoExists();
706
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
707
        } elseif (_PS_VERSION_ < 1.7) {
708
            $return = $this->display(__FILE__, 'views/templates/hook/checkout.tpl');
709
        }
710
        return $return;
711
    }
712
713
    /**
714
     * @param string $functionName
715
     *:
716
     * @return string
717
     * @throws PrestaShopDatabaseException
718
     * @throws PrestaShopException
719
     */
720
    public function productPageSimulatorDisplay($functionName)
721
    {
722
        $productConfiguration = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
723
        $productId = Tools::getValue('id_product');
724
        if (!$productId) {
725
            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...
726
        }
727
        //Resolves bug of reference passtrow
728
        $amount = Product::getPriceStatic($productId);
729
730
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
731
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
732
733
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
734
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
735
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
736
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
737
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
738
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
739
        $pagantisSimulatorQuantitySelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
740
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
741
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
742
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
743
        $pagantisDisplayMinAmount           = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
744
        $pagantisDisplayMaxAmount           = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MAX_AMOUNT');
745
        $pagantisPromotionExtra             = Pagantis::getExtraConfig('PAGANTIS_PROMOTION_EXTRA');
746
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
747
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
748
        $allowedCountries                   = unserialize(Pagantis::getExtraConfig('PAGANTIS_ALLOWED_COUNTRIES'));
749
750
        if ($functionName != $productConfiguration ||
751
            $amount <= 0 ||
752
            $amount <= $pagantisDisplayMinAmount ||
753
            ($amount >= $pagantisDisplayMaxAmount && $pagantisDisplayMaxAmount != '0') ||
754
            !$pagantisSimulatorType ||
755
            !in_array(Tools::strtolower($this->language), $allowedCountries)
756
        ) {
757
            return null;
758
        }
759
760
        $this->context->smarty->assign(array(
761
            'amount'                             => $amount,
762
            'locale'                             => $this->language,
763
            'country'                            => $this->language,
764
            'pagantisPublicKey'                  => $pagantisPublicKey,
765
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
766
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
767
            'pagantisQuantitySelector'           => $pagantisSimulatorQuantitySelector,
768
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
769
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
770
            'pagantisSimulatorType'              => $pagantisSimulatorType,
771
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
772
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
773
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
774
            'isPromotedProduct'                  => $isPromotedProduct,
775
            'pagantisPromotionExtra'             => Tools::htmlentitiesDecodeUTF8($this->l($pagantisPromotionExtra)),
776
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
777
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
778
            '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...
779
            'pagantisSimPreposition'           => $this->l('or'),
780
        ));
781
782
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
783
    }
784
785
    /**
786
     * @return string
787
     * @throws PrestaShopDatabaseException
788
     * @throws PrestaShopException
789
     */
790
    public function hookDisplayRightColumn()
791
    {
792
793
        return $this->productPageSimulatorDisplay(__FUNCTION__);
794
    }
795
796
    /**
797
     * @return string
798
     * @throws PrestaShopDatabaseException
799
     * @throws PrestaShopException
800
     */
801
    public function hookDisplayLeftColumn()
802
    {
803
        return $this->productPageSimulatorDisplay(__FUNCTION__);
804
    }
805
806
    /**
807
     * @return string
808
     * @throws PrestaShopDatabaseException
809
     * @throws PrestaShopException
810
     */
811
    public function hookDisplayRightColumnProduct()
812
    {
813
        return $this->productPageSimulatorDisplay(__FUNCTION__);
814
    }
815
816
    /**
817
     * @return string
818
     * @throws PrestaShopDatabaseException
819
     * @throws PrestaShopException
820
     */
821
    public function hookDisplayLeftColumnProduct()
822
    {
823
        return $this->productPageSimulatorDisplay(__FUNCTION__);
824
    }
825
826
    /**
827
     * @return string
828
     * @throws PrestaShopDatabaseException
829
     * @throws PrestaShopException
830
     */
831
    public function hookDisplayProductButtons()
832
    {
833
        return $this->productPageSimulatorDisplay(__FUNCTION__);
834
    }
835
836
    /**
837
     * @param array $params
838
     *
839
     * @return string
840
     */
841
    public function hookDisplayOrderConfirmation($params)
842
    {
843
        $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...
844
845
        if ($paymentMethod == $this->displayName) {
846
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
847
        }
848
849
        return null;
850
    }
851
852
    /**
853
     * checkPromotionCategory
854
     */
855
    public function checkPromotionCategory()
856
    {
857
        $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...
858
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
859
            /** @var CategoryCore $category */
860
            $category = new Category();
861
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
862
            $category->is_root_category = false;
863
            $category->link_rewrite = $categoryArray;
864
            $category->meta_description = $categoryArray;
865
            $category->meta_keywords = $categoryArray;
866
            $category->meta_title = $categoryArray;
867
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
868
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
869
            $category->active=0;
870
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
871
                'Use it to promote your products or brands.';
872
            $category->description = $this->l($description);
873
            $category->save();
874
        }
875
    }
876
877
878
    public static function getExtraConfig($config = null, $default = '')
879
    {
880
        if (is_null($config)) {
881
            return '';
882
        }
883
884
        $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

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