Passed
Pull Request — master (#64)
by Raúl
04:30
created

Pagantis   F

Complexity

Total Complexity 113

Size/Duplication

Total Lines 937
Duplicated Lines 0 %

Importance

Changes 10
Bugs 1 Features 0
Metric Value
eloc 522
c 10
b 1
f 0
dl 0
loc 937
rs 2
wmc 113

27 Methods

Rating   Name   Duplication   Size   Complexity  
A isPaymentMethodAvailable() 0 16 5
B getConfigForm() 0 72 3
A renderForm() 0 21 1
A uninstall() 0 6 1
B migrate() 0 35 10
B getContent() 0 64 9
A checkEnvVariables() 0 20 4
A hookHeader() 0 13 2
A __construct() 0 29 1
B loadSQLFile() 0 31 8
A checkHooks() 0 19 3
A getButtonTemplateVars() 0 8 1
B hookPaymentOptions() 0 73 4
C install() 0 34 14
A checkLogoExists() 0 7 3
B getUserLanguage() 0 25 8
A hookDisplayRightColumnProduct() 0 3 1
A hookDisplayLeftColumn() 0 3 1
B productPageSimulatorDisplay() 0 59 6
A hookDisplayProductButtons() 0 3 1
A arrayColumn() 0 23 6
A hookDisplayLeftColumnProduct() 0 3 1
A getExtraConfig() 0 14 6
A hookDisplayOrderConfirmation() 0 9 3
B hookPayment() 0 73 8
A checkPromotionCategory() 0 19 2
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 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
            $this->checkLogoExists();
702
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
703
        } elseif (_PS_VERSION_ < 1.7) {
704
            $return = $this->display(__FILE__, 'views/templates/hook/checkout.tpl');
705
        }
706
        return $return;
707
    }
708
709
    /**
710
     * @param string $functionName
711
     *:
712
     * @return string
713
     * @throws PrestaShopDatabaseException
714
     * @throws PrestaShopException
715
     */
716
    public function productPageSimulatorDisplay($functionName)
717
    {
718
        $productConfiguration = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
719
        $productId = Tools::getValue('id_product');
720
        if (!$productId) {
721
            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...
722
        }
723
        //Resolves bug of reference passtrow
724
        $amount = Product::getPriceStatic($productId);
725
726
        $itemCategoriesNames = $this->arrayColumn(Product::getProductCategoriesFull($productId), 'name');
727
        $isPromotedProduct = in_array(PROMOTIONS_CATEGORY_NAME, $itemCategoriesNames);
728
729
        $pagantisPublicKey                  = Configuration::get('pagantis_public_key');
730
        $pagantisSimulatorIsEnabled         = Configuration::get('pagantis_simulator_is_enabled');
731
        $pagantisIsEnabled                  = Configuration::get('pagantis_is_enabled');
732
        $pagantisSimulatorType              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
733
        $pagantisSimulatorCSSSelector       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
734
        $pagantisSimulatorPriceSelector     = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
735
        $pagantisSimulatorQuantitySelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
736
        $pagantisSimulatorQuotesStart       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
737
        $pagantisSimulatorSkin              = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
738
        $pagantisSimulatorPosition          = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
739
        $pagantisDisplayMinAmount           = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
740
        $pagantisPromotionExtra             = Pagantis::getExtraConfig('PAGANTIS_PROMOTION_EXTRA');
741
        $pagantisSimulatorThousandSeparator = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_THOUSAND_SEPARATOR');
742
        $pagantisSimulatorDecimalSeparator  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR');
743
744
        if ($functionName != $productConfiguration ||
745
            $amount <= 0 ||
746
            $amount < $pagantisDisplayMinAmount ||
747
            !$pagantisSimulatorType
748
        ) {
749
            return null;
750
        }
751
752
        $this->context->smarty->assign(array(
753
            'amount'                             => $amount,
754
            'locale'                             => $this->language,
755
            'country'                            => $this->language,
756
            'pagantisPublicKey'                  => $pagantisPublicKey,
757
            'pagantisCSSSelector'                => $pagantisSimulatorCSSSelector,
758
            'pagantisPriceSelector'              => $pagantisSimulatorPriceSelector,
759
            'pagantisQuantitySelector'           => $pagantisSimulatorQuantitySelector,
760
            'pagantisSimulatorIsEnabled'         => $pagantisSimulatorIsEnabled,
761
            'pagantisIsEnabled'                  => $pagantisIsEnabled,
762
            'pagantisSimulatorType'              => $pagantisSimulatorType,
763
            'pagantisSimulatorSkin'              => $pagantisSimulatorSkin,
764
            'pagantisSimulatorPosition'          => $pagantisSimulatorPosition,
765
            'pagantisQuotesStart'                => $pagantisSimulatorQuotesStart,
766
            'isPromotedProduct'                  => $isPromotedProduct,
767
            'pagantisPromotionExtra'             => Tools::htmlentitiesDecodeUTF8($this->l($pagantisPromotionExtra)),
768
            'pagantisSimulatorThousandSeparator' => $pagantisSimulatorThousandSeparator,
769
            'pagantisSimulatorDecimalSeparator'  => $pagantisSimulatorDecimalSeparator,
770
            '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...
771
            'pagantisSimPreposition'           => $this->l('or'),
772
        ));
773
774
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
775
    }
776
777
    /**
778
     * @return string
779
     * @throws PrestaShopDatabaseException
780
     * @throws PrestaShopException
781
     */
782
    public function hookDisplayRightColumn()
783
    {
784
785
        return $this->productPageSimulatorDisplay(__FUNCTION__);
786
    }
787
788
    /**
789
     * @return string
790
     * @throws PrestaShopDatabaseException
791
     * @throws PrestaShopException
792
     */
793
    public function hookDisplayLeftColumn()
794
    {
795
        return $this->productPageSimulatorDisplay(__FUNCTION__);
796
    }
797
798
    /**
799
     * @return string
800
     * @throws PrestaShopDatabaseException
801
     * @throws PrestaShopException
802
     */
803
    public function hookDisplayRightColumnProduct()
804
    {
805
        return $this->productPageSimulatorDisplay(__FUNCTION__);
806
    }
807
808
    /**
809
     * @return string
810
     * @throws PrestaShopDatabaseException
811
     * @throws PrestaShopException
812
     */
813
    public function hookDisplayLeftColumnProduct()
814
    {
815
        return $this->productPageSimulatorDisplay(__FUNCTION__);
816
    }
817
818
    /**
819
     * @return string
820
     * @throws PrestaShopDatabaseException
821
     * @throws PrestaShopException
822
     */
823
    public function hookDisplayProductButtons()
824
    {
825
        return $this->productPageSimulatorDisplay(__FUNCTION__);
826
    }
827
828
    /**
829
     * @param array $params
830
     *
831
     * @return string
832
     */
833
    public function hookDisplayOrderConfirmation($params)
834
    {
835
        $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...
836
837
        if ($paymentMethod == $this->displayName) {
838
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
839
        }
840
841
        return null;
842
    }
843
844
    /**
845
     * checkPromotionCategory
846
     */
847
    public function checkPromotionCategory()
848
    {
849
        $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...
850
        if (!in_array(PROMOTIONS_CATEGORY_NAME, $categories)) {
851
            /** @var CategoryCore $category */
852
            $category = new Category();
853
            $categoryArray = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY );
854
            $category->is_root_category = false;
855
            $category->link_rewrite = $categoryArray;
856
            $category->meta_description = $categoryArray;
857
            $category->meta_keywords = $categoryArray;
858
            $category->meta_title = $categoryArray;
859
            $category->name = array((int)Configuration::get('PS_LANG_DEFAULT')=> PROMOTIONS_CATEGORY_NAME);
860
            $category->id_parent = Configuration::get('PS_HOME_CATEGORY');
861
            $category->active=0;
862
            $description = 'Pagantis: Products with this category have free financing assumed by the merchant. ' .
863
                'Use it to promote your products or brands.';
864
            $category->description = $this->l($description);
865
            $category->save();
866
        }
867
    }
868
869
870
    public static function getExtraConfig($config = null, $default = '')
871
    {
872
        if (is_null($config)) {
873
            return '';
874
        }
875
876
        $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

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