Passed
Pull Request — master (#9)
by
unknown
01:50
created

WcPaylater::updateExtraConfig()   B

Complexity

Conditions 10
Paths 16

Size

Total Lines 50
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

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

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: Pagamastarde
4
 * Plugin URI: http://www.pagamastarde.com/
5
 * Description: Financiar con Pagamastarde
6
 * Version: 7.0.0
7
 * Author: Pagamastarde
8
 */
9
10
//namespace Gateways;
11
12
13
if (!defined('ABSPATH')) {
14
    exit;
15
}
16
17
class WcPaylater
18
{
19
    const GIT_HUB_URL = 'https://github.com/PagaMasTarde/woocommerce';
20
    const PMT_DOC_URL = 'https://docs.pagamastarde.com';
21
    const SUPPORT_EML = 'mailto:[email protected]?Subject=woocommerce_plugin';
22
    /** Concurrency tablename */
23
    const LOGS_TABLE = 'pmt_logs';
24
    /** Config tablename */
25
    const CONFIG_TABLE = 'pmt_config';
26
27
    public $defaultConfigs = array('PMT_TITLE'=>'Instant Financing',
28
                            'PMT_SIMULATOR_DISPLAY_TYPE'=>'pmtSDK.simulator.types.SIMPLE',
29
                            'PMT_SIMULATOR_DISPLAY_SKIN'=>'pmtSDK.simulator.skins.BLUE',
30
                            'PMT_SIMULATOR_DISPLAY_POSITION'=>'hookDisplayProductButtons',
31
                            'PMT_SIMULATOR_START_INSTALLMENTS'=>3,
32
                            'PMT_SIMULATOR_MAX_INSTALLMENTS'=>12,
33
                            'PMT_SIMULATOR_CSS_POSITION_SELECTOR'=>'default',
34
                            'PMT_SIMULATOR_DISPLAY_CSS_POSITION'=>'pmtSDK.simulator.positions.INNER',
35
                            'PMT_SIMULATOR_CSS_PRICE_SELECTOR'=>'default',
36
                            'PMT_SIMULATOR_CSS_QUANTITY_SELECTOR'=>'default',
37
                            'PMT_FORM_DISPLAY_TYPE'=>0,
38
                            'PMT_DISPLAY_MIN_AMOUNT'=>1,
39
                            'PMT_URL_OK'=>'',
40
                            'PMT_URL_KO'=>'',
41
                            'PMT_TITLE_EXTRA' => 'Paga hasta en 12 cómodas cuotas con Paga+Tarde. Solicitud totalmente 
42
                            online y sin papeleos,¡y la respuesta es inmediata!'
43
    );
44
45
    /**
46
     * WC_Paylater 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->paylaterActivation();
55
56
        load_plugin_textdomain('paylater', 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('paylater', false, basename(dirname(__FILE__)).'/languages');
Loading history...
57
        add_filter('woocommerce_payment_gateways', array($this, 'addPaylaterGateway'));
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, 'addPaylaterGateway'));
Loading history...
58
        add_filter('woocommerce_available_payment_gateways', array($this, 'paylaterFilterGateways'), 9999);
59
        add_filter('plugin_row_meta', array($this, 'paylaterRowMeta'), 10, 2);
60
        add_filter('plugin_action_links_'.plugin_basename(__FILE__), array($this, 'paylaterActionLinks'));
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, 'paylaterActionLinks'));
Loading history...
61
        add_action('woocommerce_after_add_to_cart_form', array($this, 'paylaterAddProductSimulator'));
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, 'paylaterAddProductSimulator'));
Loading history...
62
        add_action('wp_enqueue_scripts', 'add_widget_js');
63
        add_action('rest_api_init', array($this, 'paylaterRegisterEndpoint')); //Endpoint
64
    }
65
66
    /**
67
     * Sql table
68
     */
69
    public function paylaterActivation()
70
    {
71
        global $wpdb;
72
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
73
74
        //Check if table exists
75
        $tableExists = $wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName;
76
        if ($tableExists) {
77
            $charset_collate = $wpdb->get_charset_collate();
78
            $sql = "CREATE TABLE IF NOT EXISTS $tableName (
79
                                id int NOT NULL AUTO_INCREMENT, 
80
                                config varchar(60) NOT NULL, 
81
                                value varchar(100) NOT NULL, 
82
                                UNIQUE KEY id(id)) $charset_collate";
83
84
            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...
85
            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

85
            /** @scrutinizer ignore-call */ 
86
            dbDelta($sql);
Loading history...
86
        }
87
88
        $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...
89
90
        // Convert a multimple dimension array for SQL insert statements into a simple key/value
91
        $simpleDbConfigs = array();
92
        foreach ($dbConfigs as $config) {
93
            $simpleDbConfigs[$config['config']] = $config['value'];
94
        }
95
        $newConfigs = array_diff_key($this->defaultConfigs, $simpleDbConfigs);
96
        if (!empty($newConfigs)) {
97
            foreach ($newConfigs as $key => $value) {
98
                $wpdb->insert($tableName, array('config' => $key, 'value'  => $value), array('%s', '%s'));
99
            }
100
        }
101
102
        foreach (array_merge($this->defaultConfigs, $simpleDbConfigs) as $key => $value) {
103
            putenv($key . '=' . $value);
104
        }
105
106
        //Current plugin config: pmt_public_key => New field --- public_key => Old field
107
        $settings = get_option('woocommerce_paylater_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

107
        $settings = /** @scrutinizer ignore-call */ get_option('woocommerce_paylater_settings');
Loading history...
108
109
        if (!isset($settings['pmt_public_key']) && $settings['public_key']) {
110
            $settings['pmt_public_key'] = $settings['public_key'];
111
            unset($settings['public_key']);
112
        }
113
114
        if (!isset($settings['pmt_private_key']) && $settings['secret_key']) {
115
            $settings['pmt_private_key'] = $settings['secret_key'];
116
            unset($settings['secret_key']);
117
        }
118
119
        update_option('woocommerce_paylater_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

119
        /** @scrutinizer ignore-call */ 
120
        update_option('woocommerce_paylater_settings', $settings);
Loading history...
120
    }
121
122
    /**
123
     * Product simulator
124
     */
125
    public function paylaterAddProductSimulator()
126
    {
127
        global $product;
128
129
        $cfg = get_option('woocommerce_paylater_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

129
        $cfg = /** @scrutinizer ignore-call */ get_option('woocommerce_paylater_settings');
Loading history...
130
        if ($cfg['enabled'] !== 'yes' || $cfg['pmt_public_key'] == '' || $cfg['pmt_private_key'] == '' ||
131
            $cfg['simulator'] !== 'yes') {
132
            return;
133
        }
134
135
        $template_fields = array(
136
            'total'    => is_numeric($product->price) ? $product->price : 0,
137
            'public_key' => $cfg['pmt_public_key'],
138
            'simulator_type' => getenv('PMT_SIMULATOR_DISPLAY_TYPE'),
139
            'positionSelector' => getenv('PMT_SIMULATOR_CSS_POSITION_SELECTOR'),
140
            'quantitySelector' => getenv('PMT_SIMULATOR_CSS_QUANTITY_SELECTOR'),
141
            'priceSelector' => getenv('PMT_SIMULATOR_CSS_PRICE_SELECTOR'),
142
            'totalAmount' => is_numeric($product->price) ? $product->price : 0
143
        );
144
        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

144
        /** @scrutinizer ignore-call */ 
145
        wc_get_template('product_simulator.php', $template_fields, '', $this->template_path);
Loading history...
145
    }
146
147
    /**
148
     * Add Paylater to payments list.
149
     *
150
     * @param $methods
151
     *
152
     * @return array
153
     */
154
    public function addPaylaterGateway($methods)
155
    {
156
        if (! class_exists('WC_Payment_Gateway')) {
157
            return $methods;
158
        }
159
160
        include_once('controllers/paymentController.php');
161
        $methods[] = 'WcPaylaterGateway';
162
163
        return $methods;
164
    }
165
166
    /**
167
     * Initialize WC_Paylater class
168
     *
169
     * @param $methods
170
     *
171
     * @return mixed
172
     */
173
    public function paylaterFilterGateways($methods)
174
    {
175
        global $woocommerce;
176
        $paylater = new WcPaylaterGateway();
0 ignored issues
show
Unused Code introduced by
The assignment to $paylater is dead and can be removed.
Loading history...
177
178
        return $methods;
179
    }
180
181
    /**
182
     * Add links to Plugin description
183
     *
184
     * @param $links
185
     *
186
     * @return mixed
187
     */
188
    public function paylaterActionLinks($links)
189
    {
190
        $params_array = array('page' => 'wc-settings', 'tab' => 'checkout', 'section' => 'paylater');
191
        $setting_url  = esc_url(add_query_arg($params_array, admin_url('admin.php?')));
0 ignored issues
show
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

191
        $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

191
        $setting_url  = /** @scrutinizer ignore-call */ esc_url(add_query_arg($params_array, admin_url('admin.php?')));
Loading history...
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

191
        $setting_url  = esc_url(add_query_arg($params_array, /** @scrutinizer ignore-call */ admin_url('admin.php?')));
Loading history...
192
        $setting_link = '<a href="'.$setting_url.'">'.__('Settings', 'paylater').'</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

192
        $setting_link = '<a href="'.$setting_url.'">'./** @scrutinizer ignore-call */ __('Settings', 'paylater').'</a>';
Loading history...
193
194
        array_unshift($links, $setting_link);
195
196
        return $links;
197
    }
198
199
    /**
200
     * Add links to Plugin options
201
     *
202
     * @param $links
203
     * @param $file
204
     *
205
     * @return array
206
     */
207
    public function paylaterRowMeta($links, $file)
208
    {
209
        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

209
        if ($file == /** @scrutinizer ignore-call */ plugin_basename(__FILE__)) {
Loading history...
210
            $links[] = '<a href="'.WcPaylater::GIT_HUB_URL.'" target="_blank">'.__('Documentation', 'paylater').'</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

210
            $links[] = '<a href="'.WcPaylater::GIT_HUB_URL.'" target="_blank">'./** @scrutinizer ignore-call */ __('Documentation', 'paylater').'</a>';
Loading history...
211
            $links[] = '<a href="'.WcPaylater::PMT_DOC_URL.'" target="_blank">'.
212
            __('API documentation', 'paylater').'</a>';
213
            $links[] = '<a href="'.WcPaylater::SUPPORT_EML.'">'.__('Support', 'paylater').'</a>';
214
215
            return $links;
216
        }
217
218
        return $links;
219
    }
220
221
    /**
222
     * Read logs
223
     */
224
    public function readLogs($data)
225
    {
226
        global $wpdb;
227
        $filters   = ($data->get_params());
228
        $response  = array();
229
        $secretKey = $filters['secret'];
230
        $from = $filters['from'];
231
        $to   = $filters['to'];
232
        $cfg  = get_option('woocommerce_paylater_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

232
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_paylater_settings');
Loading history...
233
        $privateKey = isset($cfg['secret_key']) ? $cfg['secret_key'] : null;
234
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
235
        $query = "select * from $tableName where createdAt>$from and createdAt<$to order by createdAt desc";
236
        $results = $wpdb->get_results($query);
237
        if (isset($results) && $privateKey == $secretKey) {
238
            foreach ($results as $key => $result) {
239
                $response[$key]['timestamp'] = $result->createdAt;
240
                $response[$key]['log']       = json_decode($result->log);
241
            }
242
        } else {
243
            $response['result'] = 'Error';
244
        }
245
        $response = json_encode($response);
246
        header("HTTP/1.1 200", true, 200);
247
        header('Content-Type: application/json', true);
248
        header('Content-Length: '.strlen($response));
249
        echo($response);
250
        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...
251
    }
252
253
    /**
254
     * Update extra config
255
     */
256
    public function updateExtraConfig($data)
257
    {
258
        global $wpdb;
259
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
260
        $response = array('status'=>null);
261
262
        $filters   = ($data->get_params());
263
        $secretKey = $filters['secret'];
264
        $cfg  = get_option('woocommerce_paylater_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

264
        $cfg  = /** @scrutinizer ignore-call */ get_option('woocommerce_paylater_settings');
Loading history...
265
        $privateKey = isset($cfg['pmt_private_key']) ? $cfg['pmt_private_key'] : null;
266
        if ($privateKey != $secretKey) {
267
            $response['status'] = 401;
268
            $response['result'] = 'Unauthorized';
269
        } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') {
270
            if (count($_POST)) {
271
                foreach ($_POST as $config => $value) {
272
                    if (isset($this->defaultConfigs[$config]) && $response['status']==null) {
273
                        $result = $wpdb->update(
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
274
                            $tableName,
275
                            array('value' => $value),
276
                            array('config' => $config),
277
                            array('%s'),
278
                            array('%s')
279
                        );
280
                    } else {
281
                        $response['status'] = 400;
282
                        $response['result'] = 'Bad request';
283
                    }
284
                }
285
            } else {
286
                $response['status'] = 422;
287
                $response['result'] = 'Empty data';
288
            }
289
        }
290
291
        if ($response['status']==null) {
292
            $tableName = $wpdb->prefix.self::CONFIG_TABLE;
293
            $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...
294
            foreach ($dbResult as $value) {
295
                $formattedResult[$value['config']] = $value['value'];
296
            }
297
            $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 294. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
298
        }
299
300
        $result = json_encode($response['result']);
301
        header("HTTP/1.1 ".$response['status'], true, $response['status']);
302
        header('Content-Type: application/json', true);
303
        header('Content-Length: '.strlen($result));
304
        echo($result);
305
        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...
306
    }
307
308
    /**
309
     * ENDPOINT - Read logs -> Hook: rest_api_init
310
     * @return mixed
311
     */
312
    public function paylaterRegisterEndpoint()
313
    {
314
        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

314
        /** @scrutinizer ignore-call */ 
315
        register_rest_route(
Loading history...
315
            'paylater/v1',
316
            '/logs/(?P<secret>\w+)/(?P<from>\d+)/(?P<to>\d+)',
317
            array(
318
            'methods'  => 'GET',
319
            'callback' => array(
320
                $this,
321
                'readLogs')
322
            ),
323
            true
324
        );
325
326
        register_rest_route(
327
            'paylater/v1',
328
            '/configController/(?P<secret>\w+)',
329
            array(
330
                'methods'  => 'GET, POST',
331
                'callback' => array(
332
                    $this,
333
                    'updateExtraConfig')
334
            ),
335
            true
336
        );
337
    }
338
}
339
340
/**
341
 * Add widget Js
342
 **/
343
function add_widget_js()
344
{
345
    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

345
    /** @scrutinizer ignore-call */ 
346
    wp_enqueue_script('pmtSdk', 'https://cdn.pagamastarde.com/js/pmt-v2/sdk.js', '', '', true);
Loading history...
346
}
347
348
new WcPaylater();
349