Completed
Push — master ( 7cc2c2...10410a )
by Cesar
11s
created

Paylater::renderForm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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