Passed
Pull Request — master (#24)
by Raúl
02:11
created

Paylater   F

Complexity

Total Complexity 86

Size/Duplication

Total Lines 690
Duplicated Lines 0 %

Importance

Changes 39
Bugs 2 Features 3
Metric Value
eloc 364
c 39
b 2
f 3
dl 0
loc 690
rs 2
wmc 86

22 Methods

Rating   Name   Duplication   Size   Complexity  
A hookDisplayLeftColumnProduct() 0 3 1
A renderForm() 0 21 1
B __construct() 0 52 5
A hookDisplayOrderConfirmation() 0 9 3
A uninstall() 0 5 1
A isPaymentMethodAvailable() 0 14 4
A hookDisplayRightColumn() 0 4 1
A hookDisplayRightColumnProduct() 0 3 1
A hookPaymentOptions() 0 50 3
B upgrade() 0 29 11
A hookDisplayProductButtons() 0 3 1
A productPageSimulatorDisplay() 0 33 5
A getButtonTemplateVars() 0 8 1
C install() 0 36 13
A hookDisplayLeftColumn() 0 3 1
B getContent() 0 67 10
A loadSQLFile() 0 17 3
B getConfigForm() 0 72 3
A replaceEnvFileValues() 0 12 3
B hookPayment() 0 41 6
A checkLogoExists() 0 7 3
A readEnvFileAsArray() 0 20 6

How to fix   Complexity   

Complex Class

Complex classes like Paylater 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 Paylater, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * This file is part of the official Paylater module for PrestaShop.
4
 *
5
 * @author    Paga+Tarde <[email protected]>
6
 * @copyright 2015-2016 Paga+Tarde
7
 * @license   proprietary
8
 */
9
10
if (!defined('_PS_VERSION_')) {
11
    exit;
12
}
13
14
define('_PS_PAYLATER_DIR', _PS_MODULE_DIR_. '/paylater');
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_PAYLATER_DIR.'/vendor/autoload.php';
17
18
/**
19
 * Class Paylater
20
 */
21
class Paylater 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://pagamastarde.com';
27
28
    /**
29
     * @var bool
30
     */
31
    public $bootstrap = true;
32
33
    /**
34
     * @var installErrors
0 ignored issues
show
Bug introduced by
The type installErrors 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...
35
     */
36
    public $installErrors = array();
37
38
    /**
39
     * Paylater constructor.
40
     *
41
     * Define the module main properties so that prestashop understands what are the module requirements
42
     * and how to manage the module.
43
     *
44
     */
45
    public function __construct()
46
    {
47
        $this->dotEnvError = null;
0 ignored issues
show
Bug Best Practice introduced by
The property dotEnvError does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
48
        $this->name = 'paylater';
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...
49
        $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...
50
        $this->version = '7.1.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...
51
        $this->author = 'Paga+Tarde';
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...
52
        $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...
53
        $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...
54
        $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...
55
        $this->ps_versions_compliancy = array('min' => '1.5', 'max' => _PS_VERSION_);
0 ignored issues
show
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...
Bug introduced by
The constant _PS_VERSION_ was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
56
        $this->displayName = $this->l('Paga+Tarde');
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...
57
        $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...
58
            'Instant, easy and effective financial tool for your customers'
59
        );
60
61
62
        $continue = true;
63
        if (Module::isInstalled($this->name)) {
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...
64
            if (!$this->upgrade()) {
65
                $this->context->controller->errors[] = $this->l('Unable to write file') .
66
                    ' ' . _PS_PAYLATER_DIR . '/.env ' .
67
                    $this->l('Ensure that the file exists and have the correct permissions');
68
                $this->dotEnvError = $this->l('Unable to write file') .
69
                    ' ' . _PS_PAYLATER_DIR . '/.env ' .
70
                    $this->l('Ensure that the file exists and have the correct permissions');
71
                $continue = false;
72
            }
73
        } else {
74
            copy(
75
                _PS_PAYLATER_DIR . '/.env.dist',
76
                _PS_PAYLATER_DIR . '/.env'
77
            );
78
        }
79
80
        if ($continue) {
81
            $sql_file = dirname(_PS_PAYLATER_DIR).'/sql/install.sql';
82
            $this->loadSQLFile($sql_file);
83
84
            try {
85
                $envFile = new Dotenv\Dotenv(_PS_PAYLATER_DIR);
86
                $envFile->load();
87
            } catch (\Exception $exception) {
88
                $this->context->controller->errors[] = $this->l('Unable to read file') .
89
                    ' ' . _PS_PAYLATER_DIR . '/.env ' .
90
                    $this->l('Ensure that the file exists and have the correct permissions');
91
                $this->dotEnvError = $this->l('Unable to read file') .
92
                    ' ' . _PS_PAYLATER_DIR . '/.env ' .
93
                    $this->l('Ensure that the file exists and have the correct permissions');
94
            }
95
        }
96
        parent::__construct();
97
    }
98
99
    /**
100
     * Configure the variables for paga+tarde payment method.
101
     *
102
     * @return bool
103
     */
104
    public function install()
105
    {
106
        if (!extension_loaded('curl')) {
107
            $this->installErrors[] =
108
                $this->l('You have to enable the cURL extension on your server to install this module');
109
            return false;
110
        }
111
        if (!version_compare(phpversion(), '5.3.0', '>=')) {
112
            $this->installErrors[] = $this->l('The PHP version bellow 5.3.0 is not supported');
113
            return false;
114
        }
115
        $curl_info = curl_version();
116
        $curl_version = $curl_info['version'];
117
        if (!version_compare($curl_version, '7.34.0', '>=')) {
118
            $this->installErrors[] = $this->l('Curl Version is lower than 7.34.0 and does not support TLS 1.2');
119
            return false;
120
        }
121
122
        $sql_file = dirname(__FILE__).'/sql/install.sql';
123
        $this->loadSQLFile($sql_file);
124
125
        Configuration::updateValue('pmt_is_enabled', 0);
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...
126
        Configuration::updateValue('pmt_simulator_is_enabled', 1);
127
        Configuration::updateValue('pmt_public_key', '');
128
        Configuration::updateValue('pmt_private_key', '');
129
130
        return (parent::install()
131
                && $this->registerHook('displayShoppingCart')
132
                && $this->registerHook('payment')
133
                && $this->registerHook('paymentOptions')
134
                && $this->registerHook('displayRightColumn')
135
                && $this->registerHook('displayLeftColumn')
136
                && $this->registerHook('displayRightColumnProduct')
137
                && $this->registerHook('displayLeftColumnProduct')
138
                && $this->registerHook('displayProductButtons')
139
                && $this->registerHook('displayOrderConfirmation')
140
        );
141
    }
142
143
    /**
144
     * Remove the production private api key and remove the files
145
     *
146
     * @return bool
147
     */
148
    public function uninstall()
149
    {
150
        Configuration::deleteByName('PAYLATER_PRIVATE_KEY_PROD');
151
152
        return parent::uninstall();
153
    }
154
155
    /**
156
     * Upgrade module and generate/update .env file if needed
157
     */
158
    public function upgrade()
159
    {
160
161
        if (file_exists(_PS_PAYLATER_DIR . '/.env') && !is_writable(_PS_PAYLATER_DIR . '/.env')) {
162
            return false;
163
        }
164
        $envFileVariables = $this->readEnvFileAsArray(_PS_PAYLATER_DIR . '/.env');
165
        $distFileVariables = $this->readEnvFileAsArray(_PS_PAYLATER_DIR . '/.env.dist');
166
        $distFile = Tools::file_get_contents(_PS_PAYLATER_DIR . '/.env.dist');
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...
167
168
        $newEnvFileArr = array_merge($distFileVariables, $envFileVariables);
169
        $newEnvFile = $this->replaceEnvFileValues($distFile, $newEnvFileArr);
170
        file_put_contents(_PS_PAYLATER_DIR . '/.env', $newEnvFile);
171
172
        // migrating pk/tk from previous version
173
        if (Configuration::get('pmt_public_key') === false && Configuration::get('PAYLATER_PUBLIC_KEY_PROD')) {
174
            Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_PROD'));
175
        } elseif (Configuration::get('pmt_public_key') === false && Configuration::get('PAYLATER_PUBLIC_KEY_TEST')) {
176
            Configuration::updateValue('pmt_public_key', Configuration::get('PAYLATER_PUBLIC_KEY_TEST'));
177
        }
178
179
        if (Configuration::get('pmt_private_key') === false && Configuration::get('PAYLATER_PRIVATE_KEY_PROD')) {
180
            Configuration::updateValue('pmt_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_PROD'));
181
        } elseif (Configuration::get('pmt_private_key') === false && Configuration::get('PAYLATER_PRIVATE_KEY_TEST')) {
182
            Configuration::updateValue('pmt_private_key', Configuration::get('PAYLATER_PRIVATE_KEY_TEST'));
183
        }
184
        Configuration::updateValue('pmt_is_enabled', 1);
185
186
        return true;
187
    }
188
189
    /**
190
     * readEnvFileAsArray and return it as a key=>value array
191
     *
192
     * @param $filePath
193
     * @return array
194
     */
195
    protected function readEnvFileAsArray($filePath)
196
    {
197
        $envFileVariables = array();
198
199
        if (file_exists($filePath)) {
200
            // Read file into an array of lines with auto-detected line endings
201
            $autodetect = ini_get('auto_detect_line_endings');
202
            ini_set('auto_detect_line_endings', '1');
203
            $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
204
            ini_set('auto_detect_line_endings', $autodetect);
205
206
            foreach ($lines as $line) {
207
                // Is a variable line ?
208
                if (!(isset($line[0]) && $line[0] === '#') && strpos($line, '=') !== false) {
209
                    list($name, $value) = array_map('trim', explode('=', $line, 2));
210
                    $envFileVariables[$name] = $value;
211
                }
212
            }
213
        }
214
        return $envFileVariables;
215
    }
216
217
    /**
218
     * @param $envFile
219
     * @param $replacements
220
     * @return mixed
221
     */
222
    protected function replaceEnvFileValues($envFile, $replacements)
223
    {
224
        foreach ($replacements as $key => $value) {
225
            $from = strpos($envFile, $key);
226
            if ($from !== false) {
227
                $to = strpos($envFile, '#', $from);
228
                $fromReplace = Tools::substr($envFile, $from, (($to - $from)-1));
229
                $toReplace = $key . '=' . $value;
230
                $envFile = str_replace($fromReplace, $toReplace, $envFile);
231
            }
232
        }
233
        return $envFile;
234
    }
235
236
    /**
237
     * @param $sql_file
238
     * @return bool
239
     */
240
    public function loadSQLFile($sql_file)
241
    {
242
        $sql_content = Tools::file_get_contents($sql_file);
243
244
        // Replace prefix and store SQL command in array
245
        $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...
246
        $sql_requests = preg_split("/;\s*[\r\n]+/", $sql_content);
247
248
        $result = true;
249
        foreach ($sql_requests as $request) {
250
            if (!empty($request)) {
251
                $result &= Db::getInstance()->execute(trim($request));
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...
252
            }
253
        }
254
255
        // Return result
256
        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...
257
    }
258
259
    /**
260
     * Check amount of order > minAmount
261
     * Check valid currency
262
     * Check API variables are set
263
     *
264
     * @return bool
265
     */
266
    public function isPaymentMethodAvailable()
267
    {
268
        $cart                       = $this->context->cart;
269
        $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...
270
        $availableCurrencies        = array('EUR');
271
        $pmtDisplayMinAmount        = getenv('PMT_DISPLAY_MIN_AMOUNT');
272
        $pmtPublicKey               = Configuration::get('pmt_public_key');
273
        $pmtPrivateKey              = Configuration::get('pmt_private_key');
274
275
        return (
276
            $cart->getOrderTotal() >= $pmtDisplayMinAmount &&
277
            in_array($currency->iso_code, $availableCurrencies) &&
278
            $pmtPublicKey &&
279
            $pmtPrivateKey
280
        );
281
    }
282
283
    /**
284
     * @param Cart $cart
285
     *
286
     * @return array
287
     */
288
    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...
289
    {
290
        $currency = new Currency(($cart->id_currency));
291
292
        return array(
293
            'paylater_button' => '#paylater_payment_button',
294
            'paylater_currency_iso' => $currency->iso_code,
295
            'paylater_cart_total' => $cart->getOrderTotal(),
296
        );
297
    }
298
299
    /**
300
     * @return array
301
     */
302
    public function hookPaymentOptions()
303
    {
304
        if (!$this->isPaymentMethodAvailable()) {
305
            return array();
306
        }
307
308
        /** @var Cart $cart */
309
        $cart                       = $this->context->cart;
310
        $orderTotal                 = $cart->getOrderTotal();
311
        $link                       = $this->context->link;
312
        $pmtPublicKey               = Configuration::get('pmt_public_key');
313
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
314
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
315
        $pmtSimulatorQuotesStart    = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
316
        $pmtSimulatorQuotesMax      = getenv('PMT_SIMULATOR_MAX_INSTALLMENTS');
317
        $pmtTitle                   = $this->l(getenv('PMT_TITLE'));
318
319
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
320
        $this->context->smarty->assign(array(
321
            'amount'                => $orderTotal,
322
            'pmtPublicKey'          => $pmtPublicKey,
323
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
324
            'pmtQuotesMax'          => $pmtSimulatorQuotesMax,
325
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
326
            'pmtIsEnabled'          => $pmtIsEnabled,
327
            'pmtTitle'              => $pmtTitle,
328
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
329
            '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...
330
        ));
331
332
        $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...
333
        $paymentOption
334
            ->setCallToActionText($pmtTitle)
335
            ->setAction($link->getModuleLink('paylater', 'payment'))
336
            ->setLogo($this->getPathUri(). 'logo.gif')
337
            ->setModuleName(__CLASS__)
338
        ;
339
340
341
        if (_PS_VERSION_ >= 1.7) {
342
            $paymentOption->setAdditionalInformation(
343
                $this->fetch('module:paylater/views/templates/hook/checkout-17.tpl')
344
            );
345
        } else {
346
            $paymentOption->setAdditionalInformation(
347
                $this->fetch('module:paylater/views/templates/hook/checkout-15.tpl')
348
            );
349
        }
350
351
        return array($paymentOption);
352
    }
353
354
    /**
355
     * Get the form for editing the BackOffice options of the module
356
     *
357
     * @return array
358
     */
359
    private function getConfigForm()
360
    {
361
        return array(
362
            'form' => array(
363
                'legend' => array(
364
                    'title' => $this->l('Basic Settings'),
365
                    'icon' => 'icon-cogs',
366
                ),
367
                'input' => array(
368
                    array(
369
                        'name' => 'pmt_is_enabled',
370
                        '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...
371
                        'label' => $this->l('Module is enabled'),
372
                        'prefix' => '<i class="icon icon-key"></i>',
373
                        'class' => 't',
374
                        'required' => true,
375
                        'values'=> array(
376
                            array(
377
                                'id' => 'pmt_is_enabled_true',
378
                                'value' => 1,
379
                                'label' => $this->l('Yes', get_class($this), null, false),
380
                            ),
381
                            array(
382
                                'id' => 'pmt_is_enabled_false',
383
                                'value' => 0,
384
                                'label' => $this->l('No', get_class($this), null, false),
385
                            ),
386
                        )
387
                    ),
388
                    array(
389
                        'name' => 'pmt_public_key',
390
                        'suffix' => $this->l('ex: pk_fd53cd467ba49022e4gf215e'),
391
                        'type' => 'text',
392
                        'size' => 60,
393
                        'label' => $this->l('Public Key'),
394
                        'prefix' => '<i class="icon icon-key"></i>',
395
                        'col' => 6,
396
                        'required' => true,
397
                    ),
398
                    array(
399
                        'name' => 'pmt_private_key',
400
                        'suffix' => $this->l('ex: 21e5723a97459f6a'),
401
                        'type' => 'text',
402
                        'size' => 60,
403
                        'label' => $this->l('Secret Key'),
404
                        'prefix' => '<i class="icon icon-key"></i>',
405
                        'col' => 6,
406
                        'required' => true,
407
                    ),
408
                    array(
409
                        'name' => 'pmt_simulator_is_enabled',
410
                        'type' => (version_compare(_PS_VERSION_, '1.6')<0) ?'radio' :'switch',
411
                        'label' => $this->l('Simulator is enabled'),
412
                        'prefix' => '<i class="icon icon-key"></i>',
413
                        'class' => 't',
414
                        'required' => true,
415
                        'values'=> array(
416
                            array(
417
                                'id' => 'pmt_simulator_is_enabled_on',
418
                                'value' => 1,
419
                                'label' => $this->l('Yes'),
420
                            ),
421
                            array(
422
                                'id' => 'pmt_simulator_is_enabled_off',
423
                                'value' => 0,
424
                                'label' => $this->l('No'),
425
                            ),
426
                        )
427
                    ),
428
                ),
429
                'submit' => array(
430
                    'title' => $this->l('Save'),
431
                ),
432
            ),
433
        );
434
    }
435
436
    /**
437
     * Form configuration function
438
     *
439
     * @param array $settings
440
     *
441
     * @return string
442
     */
443
    private function renderForm(array $settings)
444
    {
445
        $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...
446
        $helper->show_toolbar = false;
447
        $helper->table = $this->table;
448
        $helper->module = $this;
449
        $helper->default_form_language = $this->context->language->id;
450
        $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
451
        $helper->identifier = $this->identifier;
452
        $helper->submit_action = 'submit'.$this->name;
453
        $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...
454
        $helper->token = Tools::getAdminTokenLite('AdminModules');
455
        $helper->tpl_vars = array(
456
            'fields_value' => $settings,
457
            'languages' => $this->context->controller->getLanguages(),
458
            'id_language' => $this->context->language->id,
459
        );
460
461
        $helper->fields_value['pmt_url_ok'] = Configuration::get('pmt_url_ok');
462
463
        return $helper->generateForm(array($this->getConfigForm()));
464
    }
465
466
    /**
467
     * Function to update the variables of Paga+Tarde Module in the backoffice of prestashop
468
     *
469
     * @return string
470
     * @throws SmartyException
471
     */
472
    public function getContent()
473
    {
474
        $error = '';
475
        $message = '';
476
        $settings = array();
477
        $settings['pmt_public_key'] = Configuration::get('pmt_public_key');
478
        $settings['pmt_private_key'] = Configuration::get('pmt_private_key');
479
        $settingsKeys = array(
480
            'pmt_is_enabled',
481
            'pmt_public_key',
482
            'pmt_private_key',
483
            'pmt_simulator_is_enabled',
484
        );
485
486
        //Different Behavior depending on 1.6 or earlier
487
        if (Tools::isSubmit('submit'.$this->name)) {
488
            foreach ($settingsKeys as $key) {
489
                switch ($key) {
490
                    case 'pmt_public_key':
491
                        $value = Tools::getValue($key);
492
                        if (!$value) {
493
                            $error = $this->l('Please add a Paga+Tarde API Public Key');
494
                            break;
495
                        }
496
                        Configuration::updateValue($key, $value);
497
                        $settings[$key] = $value;
498
                        break;
499
                    case 'pmt_private_key':
500
                        $value = Tools::getValue($key);
501
                        if (!$value) {
502
                            $error = $this->l('Please add a Paga+Tarde API Private Key');
503
                            break;
504
                        }
505
                        Configuration::updateValue($key, $value);
506
                        $settings[$key] = $value;
507
                        break;
508
                    default:
509
                        $value = Tools::getValue($key);
510
                        Configuration::updateValue($key, $value);
511
                        $settings[$key] = $value;
512
                        break;
513
                }
514
                $message = $this->displayConfirmation($this->l('All changes have been saved'));
515
            }
516
        } else {
517
            foreach ($settingsKeys as $key) {
518
                    $settings[$key] = Configuration::get($key);
519
            }
520
        }
521
522
        if ($error) {
523
            $message = $this->displayError($error);
524
        }
525
        if ($this->dotEnvError) {
526
            $message = $this->displayError($this->dotEnvError);
527
        }
528
529
        $logo = $this->getPathUri(). 'views/img/logo_pagamastarde.png';
530
        $tpl = $this->local_path.'views/templates/admin/config-info.tpl';
531
        $this->context->smarty->assign(array(
532
            'logo' => $logo,
533
            'form' => $this->renderForm($settings),
534
            'message' => $message,
535
            'version' => 'v'.$this->version,
536
        ));
537
538
        return $this->context->smarty->fetch($tpl);
539
    }
540
541
    /**
542
     * Hook to show payment method, this only applies on prestashop <= 1.6
543
     *
544
     * @param mixed $params
545
     *
546
     * @return string
547
     */
548
    public function hookPayment($params)
549
    {
550
        if (!$this->isPaymentMethodAvailable()) {
551
            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...
552
        }
553
554
        /** @var Cart $cart */
555
        $cart                       = $params['cart'];
556
        $orderTotal                 = $cart->getOrderTotal();
557
        $link                       = $this->context->link;
558
        $pmtPublicKey               = Configuration::get('pmt_public_key');
559
        $pmtSimulatorIsEnabled      = Configuration::get('pmt_simulator_is_enabled');
560
        $pmtIsEnabled               = Configuration::get('pmt_is_enabled');
561
        $pmtSimulatorQuotesStart    = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
562
        $pmtSimulatorQuotesMax      = getenv('PMT_SIMULATOR_MAX_INSTALLMENTS');
563
        $pmtTitle                   = $this->l(getenv('PMT_TITLE'));
564
        $this->context->smarty->assign($this->getButtonTemplateVars($cart));
565
        $this->context->smarty->assign(array(
566
            'amount'                => $orderTotal,
567
            'pmtPublicKey'          => $pmtPublicKey,
568
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
569
            'pmtQuotesMax'          => $pmtSimulatorQuotesMax,
570
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
571
            'pmtIsEnabled'          => $pmtIsEnabled,
572
            'pmtTitle'              => $pmtTitle,
573
            'paymentUrl'            => $link->getModuleLink('paylater', 'payment'),
574
            '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...
575
        ));
576
577
        $supercheckout_enabled = Module::isEnabled('supercheckout');
578
        $onepagecheckoutps_enabled = Module::isEnabled('onepagecheckoutps');
579
        $onepagecheckout_enabled = Module::isEnabled('onepagecheckout');
580
581
582
        if ($supercheckout_enabled || $onepagecheckout_enabled || $onepagecheckoutps_enabled) {
583
            $this->checkLogoExists();
584
            return $this->display(__FILE__, 'views/templates/hook/onepagecheckout.tpl');
585
        } elseif (_PS_VERSION_ > 1.7) {
586
            return $this->display(__FILE__, 'views/templates/hook/checkout-17.tpl');
587
        } else {
588
            return $this->display(__FILE__, 'views/templates/hook/checkout-15.tpl');
589
        }
590
    }
591
592
    /**
593
     * @param string $functionName
594
     *
595
     * @return string
596
     * @throws PrestaShopDatabaseException
597
     * @throws PrestaShopException
598
     */
599
    public function productPageSimulatorDisplay($functionName)
600
    {
601
        $productConfiguration = getenv('PMT_SIMULATOR_DISPLAY_POSITION');
602
        /** @var ProductCore $product */
603
        $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...
604
        $amount = $product->getPublicPrice();
605
        $pmtPublicKey             = Configuration::get('pmt_public_key');
606
        $pmtSimulatorIsEnabled    = Configuration::get('pmt_simulator_is_enabled');
607
        $pmtIsEnabled             = Configuration::get('pmt_is_enabled');
608
        $pmtSimulatorProduct      = getenv('PMT_SIMULATOR_DISPLAY_TYPE');
609
        $pmtSimulatorQuotesStart  = getenv('PMT_SIMULATOR_START_INSTALLMENTS');
610
        $pmtSimulatorQuotesMax    = getenv('PMT_SIMULATOR_MAX_INSTALLMENTS');
611
        $pmtDisplayMinAmount      = getenv('PMT_DISPLAY_MIN_AMOUNT');
612
613
        if ($functionName != $productConfiguration ||
614
            $amount <= 0 ||
615
            $amount < $pmtDisplayMinAmount ||
616
            !$pmtSimulatorProduct
617
        ) {
618
            return null;
619
        }
620
621
        $this->context->smarty->assign(array(
622
            'amount'                => $amount,
623
            'pmtPublicKey'          => $pmtPublicKey,
624
            'pmtSimulatorIsEnabled' => $pmtSimulatorIsEnabled,
625
            'pmtIsEnabled'          => $pmtIsEnabled,
626
            'pmtSimulatorProduct'   => $pmtSimulatorProduct,
627
            'pmtQuotesStart'        => $pmtSimulatorQuotesStart,
628
            'pmtQuotesMax'          => $pmtSimulatorQuotesMax,
629
        ));
630
631
        return $this->display(__FILE__, 'views/templates/hook/product-simulator.tpl');
632
    }
633
634
    /**
635
     * @return string
636
     * @throws PrestaShopDatabaseException
637
     * @throws PrestaShopException
638
     */
639
    public function hookDisplayRightColumn()
640
    {
641
642
        return $this->productPageSimulatorDisplay(__FUNCTION__);
643
    }
644
645
    /**
646
     * @return string
647
     * @throws PrestaShopDatabaseException
648
     * @throws PrestaShopException
649
     */
650
    public function hookDisplayLeftColumn()
651
    {
652
        return $this->productPageSimulatorDisplay(__FUNCTION__);
653
    }
654
655
    /**
656
     * @return string
657
     * @throws PrestaShopDatabaseException
658
     * @throws PrestaShopException
659
     */
660
    public function hookDisplayRightColumnProduct()
661
    {
662
        return $this->productPageSimulatorDisplay(__FUNCTION__);
663
    }
664
665
    /**
666
     * @return string
667
     * @throws PrestaShopDatabaseException
668
     * @throws PrestaShopException
669
     */
670
    public function hookDisplayLeftColumnProduct()
671
    {
672
        return $this->productPageSimulatorDisplay(__FUNCTION__);
673
    }
674
675
    /**
676
     * @return string
677
     * @throws PrestaShopDatabaseException
678
     * @throws PrestaShopException
679
     */
680
    public function hookDisplayProductButtons()
681
    {
682
        return $this->productPageSimulatorDisplay(__FUNCTION__);
683
    }
684
685
    /**
686
     * @param array $params
687
     *
688
     * @return string
689
     */
690
    public function hookDisplayOrderConfirmation($params)
691
    {
692
        $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...
693
694
        if ($paymentMethod == $this->displayName) {
695
            return $this->display(__FILE__, 'views/templates/hook/payment-return.tpl');
696
        }
697
698
        return null;
699
    }
700
701
    /**
702
     * Check logo exists in OPC module
703
     */
704
    public function checkLogoExists()
705
    {
706
        $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...
707
        if (!file_exists($logo) && is_dir(_PS_MODULE_DIR_ . '/onepagecheckoutps/views/img/payments')) {
708
            copy(
709
                _PS_PAYLATER_DIR . '/views/img/logo-64x64.png',
710
                $logo
711
            );
712
        }
713
    }
714
}
715