Passed
Pull Request — master (#13)
by
unknown
02:24
created

WcPagantis::updateExtraConfig()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 50
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 38
c 1
b 0
f 0
nc 16
nop 1
dl 0
loc 50
rs 7.6666

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Plugin Name: Pagantis
4
 * Plugin URI: http://www.pagantis.com/
5
 * Description: Financiar con Pagantis
6
 * Version: 8.0.0
7
 * Author: Pagantis
8
 */
9
10
//namespace Gateways;
11
12
13
if (!defined('ABSPATH')) {
14
    exit;
15
}
16
17
class WcPagantis
18
{
19
    const GIT_HUB_URL = 'https://github.com/pagantis/woocommerce';
20
    const PAGANTIS_DOC_URL = 'https://developer.pagamastarde.com';
21
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
22
    /** Concurrency tablename */
23
    const LOGS_TABLE = 'pagantis_logs';
24
    /** Config tablename */
25
    const CONFIG_TABLE = 'pagantis_config';
26
27
    public $defaultConfigs = array('PAGANTIS_TITLE'=>'Instant Financing',
28
                            'PAGANTIS_SIMULATOR_DISPLAY_TYPE'=>'pmtSDK.simulator.types.SIMPLE',
29
                            'PAGANTIS_SIMULATOR_DISPLAY_SKIN'=>'pmtSDK.simulator.skins.BLUE',
30
                            'PAGANTIS_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
31
32
                            'PAGANTIS_SIMULATOR_START_INSTALLMENTS'=>3,
33
                            'PAGANTIS_SIMULATOR_MAX_INSTALLMENTS'=>12,
34
                            'PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
35
                            'PAGANTIS_SIMULATOR_DISPLAY_CSS_POSITION'=>'pmtSDK.simulator.positions.INNER',
36
                            'PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
37
                            'PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
38
                            'PAGANTIS_FORM_DISPLAY_TYPE'=>0,
39
                            'PAGANTIS_DISPLAY_MIN_AMOUNT'=>1,
40
                            'PAGANTIS_URL_OK'=>'',
41
                            'PAGANTIS_URL_KO'=>'',
42
                            'PAGANTIS_TITLE_EXTRA' => 'Pay up to 12 comfortable installments with Pagantis. Completely online and sympathetic request, and the answer is immediate!'
43
    );
44
45
    /**
46
     * WC_Pagantis constructor.
47
     */
48
    public function __construct()
49
    {
50
        require_once(plugin_dir_path(__FILE__).'/vendor/autoload.php');
0 ignored issues
show
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

50
        require_once(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__).'/vendor/autoload.php');
Loading history...
51
52
        $this->template_path = plugin_dir_path(__FILE__).'/templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
54
        $this->pagantisActivation();
55
56
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
0 ignored issues
show
Bug introduced by
The function load_plugin_textdomain was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

56
        /** @scrutinizer ignore-call */ 
57
        load_plugin_textdomain('pagantis', false, basename(dirname(__FILE__)).'/languages');
Loading history...
57
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

57
        /** @scrutinizer ignore-call */ 
58
        add_filter('woocommerce_payment_gateways', array($this, 'addPagantisGateway'));
Loading history...
58
        add_filter('woocommerce_available_payment_gateways', array($this, 'pagantisFilterGateways'), 9999);
59
        add_filter('plugin_row_meta', array($this, 'pagantisRowMeta'), 10, 2);
60
        add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
0 ignored issues
show
Bug introduced by
The function plugin_basename was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

60
        add_filter('plugin_action_links_'./** @scrutinizer ignore-call */ plugin_basename(__FILE__), array($this, 'pagantisActionLinks'));
Loading history...
61
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

61
        /** @scrutinizer ignore-call */ 
62
        add_action('woocommerce_after_add_to_cart_form', array($this, 'pagantisAddProductSimulator'));
Loading history...
62
        add_action('wp_enqueue_scripts', 'add_widget_js');
63
        add_action('rest_api_init', array($this, 'pagantisRegisterEndpoint')); //Endpoint
64
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
65
    }
66
67
    /*
68
     * Replace 'textdomain' with your plugin's textdomain. e.g. 'woocommerce'.
69
     * File to be named, for example, yourtranslationfile-en_GB.mo
70
     * File to be placed, for example, wp-content/lanaguages/textdomain/yourtranslationfile-en_GB.mo
71
     */
72
    public function loadPagantisTranslation($mofile, $domain)
73
    {
74
        if ('pagantis' === $domain) {
75
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

75
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
76
        }
77
        return $mofile;
78
    }
79
80
    /**
81
     * Sql table
82
     */
83
    public function pagantisActivation()
84
    {
85
        global $wpdb;
86
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
87
88
        //Check if table exists
89
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
90
        if ($tableExists) {
91
            $charset_collate = $wpdb->get_charset_collate();
92
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
93
                                id int NOT NULL AUTO_INCREMENT, 
94
                                config varchar(60) NOT NULL, 
95
                                value varchar(100) NOT NULL, 
96
                                UNIQUE KEY id(id)) $charset_collate";
97
98
            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
0 ignored issues
show
Bug introduced by
The constant ABSPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
99
            dbDelta($sql);
0 ignored issues
show
Bug introduced by
The function dbDelta was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

99
            /** @scrutinizer ignore-call */ 
100
            dbDelta($sql);
Loading history...
100
        }
101
102
        $dbConfigs = $wpdb->get_results("select * from $tableName", ARRAY_A);
0 ignored issues
show
Bug introduced by
The constant ARRAY_A was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
103
104
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
105
        $simpleDbConfigs = array();
106
        foreach ($dbConfigs as $config) {
107
            $simpleDbConfigs[$config['config']] = $config['value'];
108
        }
109
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
110
        if (!empty($newConfigs)) {
111
            foreach ($newConfigs as $key => $value) {
112
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
113
            }
114
        }
115
116
        foreach (array_merge($this->defaultConfigs, $simpleDbConfigs) as $key => $value) {
117
            putenv($key . '=' . $value);
118
        }
119
120
        //Current plugin config: pagantis_public_key => New field --- public_key => Old field
121
        $settings = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

121
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
122
123
        if (!isset($settings['pagantis_public_key']) && $settings['public_key']) {
124
            $settings['pagantis_public_key'] = $settings['public_key'];
125
            unset($settings['public_key']);
126
        }
127
128
        if (!isset($settings['pagantis_private_key']) && $settings['secret_key']) {
129
            $settings['pagantis_private_key'] = $settings['secret_key'];
130
            unset($settings['secret_key']);
131
        }
132
133
        update_option('woocommerce_pagantis_settings', $settings);
0 ignored issues
show
Bug introduced by
The function update_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

133
        /** @scrutinizer ignore-call */ 
134
        update_option('woocommerce_pagantis_settings', $settings);
Loading history...
134
    }
135
136
    /**
137
     * Product simulator
138
     */
139
    public function pagantisAddProductSimulator()
140
    {
141
        global $product;
142
143
        $cfg = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

143
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
144
        if ($cfg['enabled'] !== 'yes' || $cfg['pagantis_public_key'] == '' || $cfg['pagantis_private_key'] == '' ||
145
            $cfg['simulator'] !== 'yes' ||  $product->price < getenv('PAGANTIS_DISPLAY_MIN_AMOUNT') ) {
146
            return;
147
        }
148
149
        $template_fields = array(
150
            'total'    => is_numeric($product->price) ? $product->price : 0,
151
            'public_key' => $cfg['pagantis_public_key'],
152
            'simulator_type' => getenv('PAGANTIS_SIMULATOR_DISPLAY_TYPE'),
153
            'positionSelector' => getenv('PAGANTIS_SIMULATOR_CSS_POSITION_SELECTOR'),
154
            'quantitySelector' => getenv('PAGANTIS_SIMULATOR_CSS_QUANTITY_SELECTOR'),
155
            'priceSelector' => getenv('PAGANTIS_SIMULATOR_CSS_PRICE_SELECTOR'),
156
            'totalAmount' => is_numeric($product->price) ? $product->price : 0
157
        );
158
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

158
        /** @scrutinizer ignore-call */ 
159
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
159
    }
160
161
    /**
162
     * Add Pagantis to payments list.
163
     *
164
     * @param $methods
165
     *
166
     * @return array
167
     */
168
    public function addPagantisGateway($methods)
169
    {
170
        if (! class_exists('WC_Payment_Gateway')) {
171
            return $methods;
172
        }
173
174
        include_once('controllers/paymentController.php');
175
        $methods[] = 'WcPagantisGateway';
176
177
        return $methods;
178
    }
179
180
    /**
181
     * Initialize WC_Pagantis class
182
     *
183
     * @param $methods
184
     *
185
     * @return mixed
186
     */
187
    public function pagantisFilterGateways($methods)
188
    {
189
        global $woocommerce;
190
        $pagantis = new WcPagantisGateway();
0 ignored issues
show
Unused Code introduced by
The assignment to $pagantis is dead and can be removed.
Loading history...
191
192
        return $methods;
193
    }
194
195
    /**
196
     * Add links to Plugin description
197
     *
198
     * @param $links
199
     *
200
     * @return mixed
201
     */
202
    public function pagantisActionLinks($links)
203
    {
204
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'pagantis');
205
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
0 ignored issues
show
Bug introduced by
The function admin_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

205
        $setting_url  = esc_url(add_query_arg($params_array, /** @scrutinizer ignore-call */ admin_url('admin.php?')));
Loading history...
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

205
        $setting_url  = esc_url(/** @scrutinizer ignore-call */ add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
Bug introduced by
The function esc_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

205
        $setting_url  = /** @scrutinizer ignore-call */ esc_url(add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
206
        $setting_link = '<a href="'.$setting_url.'">'.__('Settings', 'pagantis').'</a>';
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

206
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'pagantis').'</a>';
Loading history...
207
208
        array_unshift($links, $setting_link);
209
210
        return $links;
211
    }
212
213
    /**
214
     * Add links to Plugin options
215
     *
216
     * @param $links
217
     * @param $file
218
     *
219
     * @return array
220
     */
221
    public function pagantisRowMeta($links, $file)
222
    {
223
        if ($file == plugin_basename(__FILE__)) {
0 ignored issues
show
Bug introduced by
The function plugin_basename was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

223
        if ($file == /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
224
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'.__('Documentation', 'pagantis').'</a>';
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

224
            $links[] = '<a href="'.WcPagantis::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'pagantis').'</a>';
Loading history...
225
            $links[] = '<a href="'.WcPagantis::PAGANTIS_DOC_URL.'" target="_blank">'.
226
            __('API documentation', 'pagantis').'</a>';
227
            $links[] = '<a href="'.WcPagantis::SUPPORT_EML.'">'.__('Support', 'pagantis').'</a>';
228
229
            return $links;
230
        }
231
232
        return $links;
233
    }
234
235
    /**
236
     * Read logs
237
     */
238
    public function readLogs($data)
239
    {
240
        global $wpdb;
241
        $filters   = ($data->get_params());
242
        $response  = array();
243
        $secretKey = $filters['secret'];
244
        $from = $filters['from'];
245
        $to   = $filters['to'];
246
        $cfg  = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

246
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
247
        $privateKey = isset($cfg['secret_key']) ? $cfg['secret_key'] : null;
248
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
249
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
250
        $results = $wpdb->get_results($query);
251
        if (isset($results) && $privateKey == $secretKey) {
252
            foreach ($results as $key => $result) {
253
                $response[$key]['timestamp'] = $result->createdAt;
254
                $response[$key]['log']       = json_decode($result->log);
255
            }
256
        } else {
257
            $response['result'] = 'Error';
258
        }
259
        $response = json_encode($response);
260
        header("HTTP/1.1 200", true, 200);
261
        header('Content-Type: application/json', true);
262
        header('Content-Length: '.strlen($response));
263
        echo($response);
264
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
265
    }
266
267
    /**
268
     * Update extra config
269
     */
270
    public function updateExtraConfig($data)
271
    {
272
        global $wpdb;
273
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
274
        $response = array('status'=>null);
275
276
        $filters   = ($data->get_params());
277
        $secretKey = $filters['secret'];
278
        $cfg  = get_option('woocommerce_pagantis_settings');
0 ignored issues
show
Bug introduced by
The function get_option was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

278
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_pagantis_settings');
Loading history...
279
        $privateKey = isset($cfg['pagantis_private_key']) ? $cfg['pagantis_private_key'] : null;
280
        if ($privateKey != $secretKey) {
281
            $response['status'] = 401;
282
            $response['result'] = 'Unauthorized';
283
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
284
            if (count($_POST)) {
285
                foreach ($_POST as $config => $value) {
286
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
287
                        $wpdb->update(
288
                            $tableName,
289
                            array('value' => $value),
290
                            array('config' => $config),
291
                            array('%s'),
292
                            array('%s')
293
                        );
294
                    } else {
295
                        $response['status'] = 400;
296
                        $response['result'] = 'Bad request';
297
                    }
298
                }
299
            } else {
300
                $response['status'] = 422;
301
                $response['result'] = 'Empty data';
302
            }
303
        }
304
305
        if ($response['status']==null) {
306
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
307
            $dbResult = $wpdb->get_results("select config, value from $tableName", ARRAY_A);
0 ignored issues
show
Bug introduced by
The constant ARRAY_A was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
308
            foreach ($dbResult as $value) {
309
                $formattedResult[$value['config']] = $value['value'];
310
            }
311
            $response['result'] = $formattedResult;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $formattedResult seems to be defined by a foreach iteration on line 308. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
312
        }
313
314
        $result = json_encode($response['result']);
315
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
316
        header('Content-Type: application/json', true);
317
        header('Content-Length: '.strlen($result));
318
        echo($result);
319
        exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
320
    }
321
322
    /**
323
     * ENDPOINT - Read logs -> Hook: rest_api_init
324
     * @return mixed
325
     */
326
    public function pagantisRegisterEndpoint()
327
    {
328
        register_rest_route(
0 ignored issues
show
Bug introduced by
The function register_rest_route was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

328
        /** @scrutinizer ignore-call */ 
329
        register_rest_route(
Loading history...
329
            'pagantis/v1',
330
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
331
            array(
332
            'methods'  => 'GET',
333
            'callback' => array(
334
                $this,
335
                'readLogs')
336
            ),
337
            true
338
        );
339
340
        register_rest_route(
341
            'pagantis/v1',
342
            '/configController/(?P<secret>\w+)',
343
            array(
344
                'methods'  => 'GET, POST',
345
                'callback' => array(
346
                    $this,
347
                    'updateExtraConfig')
348
            ),
349
            true
350
        );
351
    }
352
}
353
354
/**
355
 * Add widget Js
356
 **/
357
function add_widget_js()
358
{
359
    wp_enqueue_script('pmtSdk', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
0 ignored issues
show
Bug introduced by
The function wp_enqueue_script was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

359
    /** @scrutinizer ignore-call */ 
360
    wp_enqueue_script('pmtSdk', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
Loading history...
360
}
361
362
new WcPagantis();
363