Passed
Pull Request — master (#23)
by Cesar
02:46
created

Paylater::__construct()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 38
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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