Passed
Pull Request — master (#27)
by Raúl
01:58
created

Paylater::readEnvFileAsArray()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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