Passed
Pull Request — master (#34)
by Raúl
02:07
created

Pagantis::getContent()   B

Complexity

Conditions 9
Paths 6

Size

Total Lines 64
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 48
nc 6
nop 0
dl 0
loc 64
rs 7.5789
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
16
require _PS_PAGANTIS_DIR.'/vendor/autoload.php';
17
18
/**
19
 * Class Pagantis
20
 */
21
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...
22
{
23
    /**
24
     * @var string
25
     */
26
    public $url = 'https://pagantis.com';
27
28
    /**
29
     * @var bool
30
     */
31
    public $bootstrap = true;
32
33
    /**
34
     * @var array
35
     */
36
    public $installErrors = array();
37
38
    /**
39
     * Default module advanced configuration values
40
     *
41
     * @var array
42
     */
43
    public $defaultConfigs = array(
44
        'PAGANTIS_TITLE' => 'Instant Financing',
45
        'PAGANTIS_SIMULATOR_DISPLAY_TYPE' => 'pgSDK.simulator.types.SIMPLE',
46
        'PAGANTIS_SIMULATOR_DISPLAY_SKIN' => 'pgSDK.simulator.skins.BLUE',
47
        'PAGANTIS_SIMULATOR_DISPLAY_POSITION' => 'hookDisplayProductButtons',
48
        'PAGANTIS_SIMULATOR_START_INSTALLMENTS' => '3',
49
        'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR' => 'default',
50
        'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION' => 'pgSDK.simulator.positions.INNER',
51
        'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR' => 'default',
52
        'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR' => 'default',
53
        'PAGANTIS_FORM_DISPLAY_TYPE' => '0',
54
        'PAGANTIS_DISPLAY_MIN_AMOUNT' => '1',
55
        'PAGANTIS_URL_OK' => '',
56
        'PAGANTIS_URL_KO' => '',
57
    );
58
59
    /**
60
     * Pagantis constructor.
61
     *
62
     * Define the module main properties so that prestashop understands what are the module requirements
63
     * and how to manage the module.
64
     *
65
     */
66
    public function __construct()
67
    {
68
        $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...
69
        $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...
70
        $this->version = '8.0.0';
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...
71
        $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...
72
        $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...
73
        $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...
74
        $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...
75
        $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...
76
        $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...
77
        $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...
78
            'Instant, easy and effective financial tool for your customers'
79
        );
80
81
        $sql_file = dirname(__FILE__).'/sql/install.sql';
82
        $this->loadSQLFile($sql_file);
83
84
        $this->checkEnvVariables();
85
86
        $this->migrate();
87
88
        $this->checkHooks();
89
90
        parent::__construct();
91
    }
92
93
    /**
94
     * Configure the variables for Pagantis payment method.
95
     *
96
     * @return bool
97
     */
98
    public function install()
99
    {
100
        if (!extension_loaded('curl')) {
101
            $this->installErrors[] =
102
                $this->l('You have to enable the cURL extension on your server to install this module');
103
            return false;
104
        }
105
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
106
            $this->installErrors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
107
            return false;
108
        }
109
        $curl_info = curl_version();
110
        $curl_version = $curl_info['version'];
111
        if (!version_compare($curl_version, '7.34.0', '>=')) {
112
            $this->installErrors[] = $this->l('Curl Version is lower than 7.34.0 and does not support TLS 1.2');
113
            return false;
114
        }
115
116
        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...
117
        Configuration::updateValue('pagantis_simulator_is_enabled', 1);
118
        Configuration::updateValue('pagantis_public_key', '');
119
        Configuration::updateValue('pagantis_private_key', '');
120
121
        return (parent::install()
122
            && $this->registerHook('displayShoppingCart')
123
            && $this->registerHook('payment')
124
            && $this->registerHook('paymentOptions')
125
            && $this->registerHook('displayRightColumn')
126
            && $this->registerHook('displayLeftColumn')
127
            && $this->registerHook('displayRightColumnProduct')
128
            && $this->registerHook('displayLeftColumnProduct')
129
            && $this->registerHook('displayProductButtons')
130
            && $this->registerHook('displayOrderConfirmation')
131
            && $this->registerHook('header')
132
        );
133
    }
134
135
    /**
136
     * Remove the production private api key and remove the files
137
     *
138
     * @return bool
139
     */
140
    public function uninstall()
141
    {
142
        Configuration::deleteByName('pagantis_public_key');
143
        Configuration::deleteByName('pagantis_private_key');
144
145
        return parent::uninstall();
146
    }
147
148
    /**
149
     * Migrate the configs of older versions < 7x to new configurations
150
     */
151
    public function migrate()
152
    {
153
        if (Configuration::get('PAYLATER_MIN_AMOUNT')) {
154
            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...
155
                'pagantis_config',
156
                array('value' => Configuration::get('PAYLATER_MIN_AMOUNT')),
157
                'config = \'PAGANTIS_DISPLAY_MIN_AMOUNT\''
158
            );
159
            Configuration::updateValue('PAYLATER_MIN_AMOUNT', false);
160
            Configuration::updateValue('pagantis_is_enabled', 1);
161
            Configuration::updateValue('pagantis_simulator_is_enabled', 1);
162
163
            // migrating pk/tk from previous version
164
            if (Configuration::get('pagantis_public_key') === false
165
                && Configuration::get('PAYLATER_PUBLIC_KEY_PROD')
166
            ) {
167
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_PROD'));
168
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_PROD', false);
169
            } elseif (Configuration::get('pagantis_public_key') === false
170
                && Configuration::get('PAYLATER_PUBLIC_KEY_TEST')
171
            ) {
172
                Configuration::updateValue('pagantis_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_TEST'));
173
                Configuration::updateValue('PAYLATER_PUBLIC_KEY_TEST', false);
174
            }
175
176
            if (Configuration::get('pagantis_private_key') === false
177
                && Configuration::get('PAYLATER_PRIVATE_KEY_PROD')
178
            ) {
179
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_PROD'));
180
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_PROD', false);
181
            } elseif (Configuration::get('pagantis_private_key') === false
182
                && Configuration::get('PAYLATER_PRIVATE_KEY_TEST')
183
            ) {
184
                Configuration::updateValue('pagantis_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_TEST'));
185
                Configuration::updateValue('PAYLATER_PRIVATE_KEY_TEST', false);
186
            }
187
        }
188
    }
189
190
    /**
191
     * Check if new hooks used in new 7x versions are enabled and activate them if needed
192
     *
193
     * @throws PrestaShopDatabaseException
194
     */
195
    public function checkHooks()
196
    {
197
        try {
198
            $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...
199
            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...
200
            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...
201
            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...
202
            $hook_exists = Db::getInstance()->ExecuteS($sql_content);
203
            if (empty($hook_exists)) {
204
                $sql_insert = 'insert into ' . _DB_PREFIX_.  'hook_module 
205
            (id_module, id_shop, id_hook, position)
206
            values
207
            (\''. Module::getModuleIdByName($this->name) . '\',
208
            \''. Shop::getContextShopID() . '\',
209
            \''. Hook::getIdByName('header') . '\',
210
            150)';
211
                Db::getInstance()->execute($sql_insert);
212
            }
213
        } catch (\Exception $exception) {
214
            // continue without errors
215
        }
216
    }
217
218
    /**
219
     * @throws PrestaShopDatabaseException
220
     */
221
    public function checkEnvVariables()
222
    {
223
        $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...
224
        $dbConfigs = Db::getInstance()->executeS($sql_content);
225
226
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
227
        $simpleDbConfigs = array();
228
        foreach ($dbConfigs as $config) {
229
            $simpleDbConfigs[$config['config']] = $config['value'];
230
        }
231
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
232
        if (!empty($newConfigs)) {
233
            $data = array();
234
            foreach ($newConfigs as $key => $value) {
235
                $data[] = array(
236
                    'config' => $key,
237
                    'value' => $value,
238
                );
239
            }
240
            Db::getInstance()->insert('pagantis_config', $data);
241
        }
242
    }
243
244
    /**
245
     * @param $sql_file
246
     * @return bool
247
     */
248
    public function loadSQLFile($sql_file)
249
    {
250
        $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...
251
        $sql_content = str_replace('PREFIX_', _DB_PREFIX_, $sql_content);
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...
252
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
253
254
        $result = true;
255
        foreach ($sql_requests as $request) {
256
            if (!empty($request)) {
257
                $result &= Db::getInstance()->execute(trim($request));
258
            }
259
        }
260
261
        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...
262
    }
263
264
    /**
265
     * Check amount of order > minAmount
266
     * Check valid currency
267
     * Check API variables are set
268
     *
269
     * @return bool
270
     * @throws PrestaShopDatabaseException
271
     * @throws PrestaShopException
272
     */
273
    public function isPaymentMethodAvailable()
274
    {
275
        $cart                      = $this->context->cart;
276
        $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...
277
        $availableCurrencies       = array('EUR');
278
        $pagantisDisplayMinAmount  = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
279
        $pagantisPublicKey         = Configuration::get('pagantis_public_key');
280
        $pagantisPrivateKey        = Configuration::get('pagantis_private_key');
281
        return (
282
            $cart->getOrderTotal() >= $pagantisDisplayMinAmount &&
283
            in_array($currency->iso_code, $availableCurrencies) &&
284
            $pagantisPublicKey &&
285
            $pagantisPrivateKey
286
        );
287
    }
288
289
    /**
290
     * @param Cart $cart
291
     *
292
     * @return array
293
     * @throws Exception
294
     */
295
    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...
296
    {
297
        $currency = new Currency(($cart->id_currency));
298
299
        return array(
300
            'pagantis_button' => '#pagantis_payment_button',
301
            'pagantis_currency_iso' => $currency->iso_code,
302
            'pagantis_cart_total' => $cart->getOrderTotal(),
303
        );
304
    }
305
306
    /**
307
     * Header hook
308
     */
309
    public function hookHeader()
310
    {
311
        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...
312
            $this->context->controller->registerJavascript(
313
                sha1(mt_rand(1, 90000)),
314
                'https://cdn.pagantis.com/js/pg-v2/sdk.js',
315
                array('server' => 'remote')
316
            );
317
        } else {
318
            $this->context->controller->addJS('https://cdn.pagantis.com/js/pg-v2/sdk.js');
319
        }
320
        $this->context->controller->addJS($this->getPathUri(). 'views/js/simulator.js');
321
    }
322
323
    /**
324
     * @return array
325
     * @throws Exception
326
     */
327
    public function hookPaymentOptions()
328
    {
329
        if (!$this->isPaymentMethodAvailable()) {
330
            return array();
331
        }
332
333
        /** @var Cart $cart */
334
        $cart                            = $this->context->cart;
335
        $orderTotal                      = $cart->getOrderTotal();
336
        $link                            = $this->context->link;
337
        $pagantisPublicKey               = Configuration::get('pagantis_public_key');
338
        $pagantisSimulatorIsEnabled      = Configuration::get('pagantis_simulator_is_enabled');
339
        $pagantisIsEnabled               = Configuration::get('pagantis_is_enabled');
340
        $pagantisSimulatorType           = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
341
        $pagantisSimulatorCSSSelector    = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
342
        $pagantisSimulatorPriceSelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
343
        $pagantisSimulatorQuotesStart    = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
344
        $pagantisSimulatorSkin           = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
345
        $pagantisSimulatorPosition       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
346
        $pagantisTitle                   = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
347
348
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
349
        $this->context->smarty->assign(array(
350
            'amount'                     => $orderTotal,
351
            'pagantisPublicKey'          => $pagantisPublicKey,
352
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
353
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
354
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
355
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
356
            'pagantisSimulatorType'      => $pagantisSimulatorType,
357
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
358
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
359
            'pagantisIsEnabled'          => $pagantisIsEnabled,
360
            'pagantisTitle'              => $pagantisTitle,
361
            'paymentUrl'                 => $link->getModuleLink('pagantis', 'payment'),
362
            '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...
363
        ));
364
365
        $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...
366
        $paymentOption
367
            ->setCallToActionText($pagantisTitle)
368
            ->setAction($link->getModuleLink('pagantis', 'payment'))
369
            ->setLogo($this->getPathUri(). 'logo.gif')
370
            ->setModuleName(__CLASS__)
371
        ;
372
373
374
        if (_PS_VERSION_ < 1.7) {
375
            $paymentOption->setAdditionalInformation(
376
                $this->fetch('module:pagantis/views/templates/hook/checkout-15.tpl')
377
            );
378
        }
379
380
        return array($paymentOption);
381
    }
382
383
    /**
384
     * Get the form for editing the BackOffice options of the module
385
     *
386
     * @return array
387
     */
388
    private function getConfigForm()
389
    {
390
        return array(
391
            'form' => array(
392
                'legend' => array(
393
                    'title' => $this->l('Basic Settings'),
394
                    'icon' => 'icon-cogs',
395
                ),
396
                'input' => array(
397
                    array(
398
                        'name' => 'pagantis_is_enabled',
399
                        '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...
400
                        'label' => $this->l('Module is enabled'),
401
                        'prefix' => '<i class="icon icon-key"></i>',
402
                        'class' => 't',
403
                        'required' => true,
404
                        'values'=> array(
405
                            array(
406
                                'id' => 'pagantis_is_enabled_true',
407
                                'value' => 1,
408
                                'label' => $this->l('Yes', get_class($this), null, false),
409
                            ),
410
                            array(
411
                                'id' => 'pagantis_is_enabled_false',
412
                                'value' => 0,
413
                                'label' => $this->l('No', get_class($this), null, false),
414
                            ),
415
                        )
416
                    ),
417
                    array(
418
                        'name' => 'pagantis_public_key',
419
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
420
                        'type' => 'text',
421
                        'size' => 60,
422
                        'label' => $this->l('Public Key'),
423
                        'prefix' => '<i class="icon icon-key"></i>',
424
                        'col' => 6,
425
                        'required' => true,
426
                    ),
427
                    array(
428
                        'name' => 'pagantis_private_key',
429
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
430
                        'type' => 'text',
431
                        'size' => 60,
432
                        'label' => $this->l('Secret Key'),
433
                        'prefix' => '<i class="icon icon-key"></i>',
434
                        'col' => 6,
435
                        'required' => true,
436
                    ),
437
                    array(
438
                        'name' => 'pagantis_simulator_is_enabled',
439
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
440
                        'label' => $this->l('Simulator is enabled'),
441
                        'prefix' => '<i class="icon icon-key"></i>',
442
                        'class' => 't',
443
                        'required' => true,
444
                        'values'=> array(
445
                            array(
446
                                'id' => 'pagantis_simulator_is_enabled_on',
447
                                'value' => 1,
448
                                'label' => $this->l('Yes'),
449
                            ),
450
                            array(
451
                                'id' => 'pagantis_simulator_is_enabled_off',
452
                                'value' => 0,
453
                                'label' => $this->l('No'),
454
                            ),
455
                        )
456
                    ),
457
                ),
458
                'submit' => array(
459
                    'title' => $this->l('Save'),
460
                ),
461
            ),
462
        );
463
    }
464
465
    /**
466
     * Form configuration function
467
     *
468
     * @param array $settings
469
     *
470
     * @return string
471
     */
472
    private function renderForm(array $settings)
473
    {
474
        $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...
475
        $helper->show_toolbar = false;
476
        $helper->table = $this->table;
477
        $helper->module = $this;
478
        $helper->default_form_language = $this->context->language->id;
479
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
480
        $helper->identifier = $this->identifier;
481
        $helper->submit_action = 'submit'.$this->name;
482
        $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...
483
        $helper->token = Tools::getAdminTokenLite('AdminModules');
484
        $helper->tpl_vars = array(
485
            'fields_value' => $settings,
486
            'languages' => $this->context->controller->getLanguages(),
487
            'id_language' => $this->context->language->id,
488
        );
489
490
        $helper->fields_value['pagantis_url_ok'] = Configuration::get('pagantis_url_ok');
491
492
        return $helper->generateForm(array($this->getConfigForm()));
493
    }
494
495
    /**
496
     * Function to update the variables of Pagantis Module in the backoffice of prestashop
497
     *
498
     * @return string
499
     * @throws SmartyException
500
     */
501
    public function getContent()
502
    {
503
        $error = '';
504
        $message = '';
505
        $settings = array();
506
        $settings['pagantis_public_key'] = Configuration::get('pagantis_public_key');
507
        $settings['pagantis_private_key'] = Configuration::get('pagantis_private_key');
508
        $settingsKeys = array(
509
            'pagantis_is_enabled',
510
            'pagantis_public_key',
511
            'pagantis_private_key',
512
            'pagantis_simulator_is_enabled',
513
        );
514
515
        //Different Behavior depending on 1.6 or earlier
516
        if (Tools::isSubmit('submit'.$this->name)) {
517
            foreach ($settingsKeys as $key) {
518
                switch ($key) {
519
                    case 'pagantis_public_key':
520
                        $value = Tools::getValue($key);
521
                        if (!$value) {
522
                            $error = $this->l('Please add a Pagantis API Public Key');
523
                            break;
524
                        }
525
                        Configuration::updateValue($key, $value);
526
                        $settings[$key] = $value;
527
                        break;
528
                    case 'pagantis_private_key':
529
                        $value = Tools::getValue($key);
530
                        if (!$value) {
531
                            $error = $this->l('Please add a Pagantis API Private Key');
532
                            break;
533
                        }
534
                        Configuration::updateValue($key, $value);
535
                        $settings[$key] = $value;
536
                        break;
537
                    default:
538
                        $value = Tools::getValue($key);
539
                        Configuration::updateValue($key, $value);
540
                        $settings[$key] = $value;
541
                        break;
542
                }
543
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
544
            }
545
        } else {
546
            foreach ($settingsKeys as $key) {
547
                    $settings[$key] = Configuration::get($key);
548
            }
549
        }
550
551
        if ($error) {
552
            $message = $this->displayError($error);
553
        }
554
555
        $logo = $this->getPathUri(). 'views/img/logo_pagantis.png';
556
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
557
        $this->context->smarty->assign(array(
558
            'logo' => $logo,
559
            'form' => $this->renderForm($settings),
560
            'message' => $message,
561
            'version' => 'v'.$this->version,
562
        ));
563
564
        return $this->context->smarty->fetch($tpl);
565
    }
566
567
    /**
568
     * Hook to show payment method, this only applies on prestashop <= 1.6
569
     *
570
     * @param $params
571
     * @return bool | string
572
     * @throws Exception
573
     */
574
    public function hookPayment($params)
575
    {
576
        if (!$this->isPaymentMethodAvailable()) {
577
            return false;
578
        }
579
580
        /** @var Cart $cart */
581
582
        $cart                            = $params['cart'];
583
        $orderTotal                      = $cart->getOrderTotal();
584
        $link                            = $this->context->link;
585
        $pagantisPublicKey               = Configuration::get('pagantis_public_key');
586
        $pagantisSimulatorIsEnabled      = Configuration::get('pagantis_simulator_is_enabled');
587
        $pagantisIsEnabled               = Configuration::get('pagantis_is_enabled');
588
        $pagantisSimulatorType           = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
589
        $pagantisSimulatorCSSSelector    = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
590
        $pagantisSimulatorPriceSelector  = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
591
        $pagantisSimulatorQuotesStart    = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
592
        $pagantisSimulatorSkin           = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
593
        $pagantisSimulatorPosition       = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
594
        $pagantisTitle                   = $this->l(Pagantis::getExtraConfig('PAGANTIS_TITLE'));
595
596
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
597
        $this->context->smarty->assign(array(
598
            'amount'                     => $orderTotal,
599
            'pagantisPublicKey'          => $pagantisPublicKey,
600
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
601
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
602
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
603
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
604
            'pagantisSimulatorType'      => $pagantisSimulatorType,
605
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
606
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
607
            'pagantisIsEnabled'          => $pagantisIsEnabled,
608
            'pagantisTitle'              => $pagantisTitle,
609
            'paymentUrl'                 => $link->getModuleLink('pagantis', 'payment'),
610
            '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...
611
        ));
612
613
        $supercheckout_enabled = Module::isEnabled('supercheckout');
614
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
615
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
616
617
        $return = true;
618
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
619
            $this->checkLogoExists();
620
            $return = $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
621
        } elseif (_PS_VERSION_ < 1.7) {
622
            $return = $this->display(__FILE__, 'views/templates/hook/checkout-15.tpl');
623
        }
624
        return $return;
625
    }
626
627
    /**
628
     * @param string $functionName
629
     *:
630
     * @return string
631
     * @throws PrestaShopDatabaseException
632
     * @throws PrestaShopException
633
     */
634
    public function productPageSimulatorDisplay($functionName)
635
    {
636
        $productConfiguration = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_POSITION');
637
        /** @var ProductCore $product */
638
        $product = new Product(Tools::getValue('id_product'));
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...
639
        $amount = $product->getPublicPrice();
640
641
        $pagantisPublicKey                 = Configuration::get('pagantis_public_key');
642
        $pagantisSimulatorIsEnabled        = Configuration::get('pagantis_simulator_is_enabled');
643
        $pagantisIsEnabled                 = Configuration::get('pagantis_is_enabled');
644
        $pagantisSimulatorType             = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_TYPE');
645
        $pagantisSimulatorCSSSelector      = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR');
646
        $pagantisSimulatorPriceSelector    = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR');
647
        $pagantisSimulatorQuantitySelector = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR');
648
        $pagantisSimulatorQuotesStart      = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_START_INSTALLMENTS');
649
        $pagantisSimulatorSkin             = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_SKIN');
650
        $pagantisSimulatorPosition         = Pagantis::getExtraConfig('PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION');
651
        $pagantisDisplayMinAmount          = Pagantis::getExtraConfig('PAGANTIS_DISPLAY_MIN_AMOUNT');
652
653
        if ($functionName != $productConfiguration ||
654
            $amount <= 0 ||
655
            $amount < $pagantisDisplayMinAmount ||
656
            !$pagantisSimulatorType
657
        ) {
658
            return null;
659
        }
660
661
        $this->context->smarty->assign(array(
662
            'amount'                     => $amount,
663
            'pagantisPublicKey'          => $pagantisPublicKey,
664
            'pagantisCSSSelector'        => $pagantisSimulatorCSSSelector,
665
            'pagantisPriceSelector'      => $pagantisSimulatorPriceSelector,
666
            'pagantisQuantitySelector'   => $pagantisSimulatorQuantitySelector,
667
            'pagantisSimulatorIsEnabled' => $pagantisSimulatorIsEnabled,
668
            'pagantisIsEnabled'          => $pagantisIsEnabled,
669
            'pagantisSimulatorType'      => $pagantisSimulatorType,
670
            'pagantisSimulatorSkin'      => $pagantisSimulatorSkin,
671
            'pagantisSimulatorPosition'  => $pagantisSimulatorPosition,
672
            'pagantisQuotesStart'        => $pagantisSimulatorQuotesStart,
673
        ));
674
675
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
676
    }
677
678
    /**
679
     * @return string
680
     * @throws PrestaShopDatabaseException
681
     * @throws PrestaShopException
682
     */
683
    public function hookDisplayRightColumn()
684
    {
685
686
        return $this->productPageSimulatorDisplay(__FUNCTION__);
687
    }
688
689
    /**
690
     * @return string
691
     * @throws PrestaShopDatabaseException
692
     * @throws PrestaShopException
693
     */
694
    public function hookDisplayLeftColumn()
695
    {
696
        return $this->productPageSimulatorDisplay(__FUNCTION__);
697
    }
698
699
    /**
700
     * @return string
701
     * @throws PrestaShopDatabaseException
702
     * @throws PrestaShopException
703
     */
704
    public function hookDisplayRightColumnProduct()
705
    {
706
        return $this->productPageSimulatorDisplay(__FUNCTION__);
707
    }
708
709
    /**
710
     * @return string
711
     * @throws PrestaShopDatabaseException
712
     * @throws PrestaShopException
713
     */
714
    public function hookDisplayLeftColumnProduct()
715
    {
716
        return $this->productPageSimulatorDisplay(__FUNCTION__);
717
    }
718
719
    /**
720
     * @return string
721
     * @throws PrestaShopDatabaseException
722
     * @throws PrestaShopException
723
     */
724
    public function hookDisplayProductButtons()
725
    {
726
        return $this->productPageSimulatorDisplay(__FUNCTION__);
727
    }
728
729
    /**
730
     * @param array $params
731
     *
732
     * @return string
733
     */
734
    public function hookDisplayOrderConfirmation($params)
735
    {
736
        $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...
737
738
        if ($paymentMethod == $this->displayName) {
739
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
740
        }
741
742
        return null;
743
    }
744
745
    /**
746
     * Check logo exists in OPC module
747
     */
748
    public function checkLogoExists()
749
    {
750
        $logo = _PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments/'. Tools::strtolower(__CLASS__). '.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...
751
        if (!file_exists($logo) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
752
            copy(
753
                _PS_PAGANTIS_DIR . '/views/img/logo-64x64.png',
754
                $logo
755
            );
756
        }
757
    }
758
759
    public static function getExtraConfig($config = null, $default = '')
760
    {
761
        if (is_null($config)) {
762
            return '';
763
        }
764
765
        $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

765
        $sql = 'SELECT value FROM '._DB_PREFIX_.'pagantis_config where config = \'' . /** @scrutinizer ignore-call */ pSQL($config) . '\' limit 1';
Loading history...
766
        if ($results = Db::getInstance()->ExecuteS($sql)) {
767
            if (is_array($results) && count($results) === 1 && isset($results[0]['value'])) {
768
                return $results[0]['value'];
769
            }
770
        }
771
772
        return $default;
773
    }
774
}
775