Passed
Pull Request — master (#48)
by
unknown
02:31
created

WC_Pagantis_Gateway   F

Complexity

Total Complexity 107

Size/Duplication

Total Lines 903
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 428
c 0
b 0
f 0
dl 0
loc 903
rs 2
wmc 107

33 Methods

Rating   Name   Duplication   Size   Complexity  
A checkDbLogTable() 0 3 1
A payment_fields() 0 27 2
F get_wc_order_received_page() 0 180 19
A getKeysUrl() 0 21 3
A getKeysParametersUrl() 0 12 2
A admin_options() 0 10 1
A getNationalId() 0 10 3
B is_available() 0 17 8
A insert_row_in_wc_orders_table() 0 18 2
A getKoUrl() 0 3 1
A init_form_fields() 0 3 1
A generateOkUrl() 0 3 1
A __construct() 0 42 2
A generateUrl() 0 17 5
A get_unparsed_url() 0 10 6
A pagantisNotification() 0 33 5
A isPromoted() 0 6 3
A getOrders() 0 37 5
A getTaxId() 0 6 3
A get_title() 0 3 1
A insertLog() 0 8 2
A getKeysPathUrl() 0 12 3
A process_payment() 0 18 3
A enqueue_ajax_scripts() 0 27 5
A generateKoUrl() 0 3 1
A getPromotedAmount() 0 13 3
A check_if_wc_orders_db_table_exist() 0 12 2
A pagantisCheckFields() 0 3 1
A pagantisCompleteStatus() 0 11 5
A set_payment_urls() 0 10 4
A getOkUrl() 0 3 1
A loadPagantisTranslation() 0 7 2
A check_deprecated_arguments() 0 16 1

How to fix   Complexity   

Complex Class

Complex classes like WC_Pagantis_Gateway often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WC_Pagantis_Gateway, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
use Pagantis\ModuleUtils\Model\Log\LogEntry;
18
19
if (! defined('ABSPATH')) {
20
    exit;
21
}
22
23
define('__ROOT__', dirname(dirname(__FILE__)));
24
25
class WC_Pagantis_Gateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway 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...
26
{
27
    const METHOD_ID = 'pagantis';
28
29
    /**
30
     * Customizable configuration options
31
     *
32
     * @var array $extraConfig
33
     */
34
    private $extraConfig;
35
36
    /**
37
     * Language to facilitate localization
38
     *
39
     * @var string $language
40
     */
41
    public $language;
42
43
44
    /**
45
     * Array of allowed currencies with Pagantis
46
     *
47
     * @var array $allowed_currencies
48
     */
49
    private $allowed_currencies;
50
51
52
    /**
53
     * WcPagantisGateway constructor.
54
     */
55
    public function __construct()
56
    {
57
        require_once dirname(__FILE__) . '/../includes/class-wc-pagantis-config.php';
58
        require_once dirname(__FILE__) . '/../includes/class-wc-pagantis-logger.php';
59
        require_once dirname(__FILE__) . '/../includes/functions.php';
60
        //Mandatory vars for plugin
61
        $this->id           = PAGANTIS_PLUGIN_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
62
        $this->has_fields   = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
63
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        //Useful vars
65
        $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...
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

65
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
66
67
        $this->allowed_currencies = array('EUR');
68
        $this->language           = strstr(get_locale(), '_', true);
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

68
        $this->language           = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
69
        if ($this->language === '') {
70
            $this->language = 'ES';
71
        }
72
        $this->icon = 'https://cdn.digitalorigin.com/assets/master/logos/pg-130x30.svg';
0 ignored issues
show
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
73
74
        //Panel form fields
75
        $this->init_form_fields();
76
        $this->init_settings();
77
78
        $this->extraConfig = WC_Pagantis_Config::getExtraConfig();
79
        $this->title       = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug Best Practice introduced by
The property title 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 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

79
        $this->title       = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
80
81
        $this->method_description =
0 ignored issues
show
Bug Best Practice introduced by
The property method_description does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
82
            __('Give the flexibility to your clients to pay in installments with Pagantis!', 'pagantis');
83
        $this->check_deprecated_arguments();
84
        $this->set_payment_urls();
85
        //Hooks
86
        add_action(
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

86
        /** @scrutinizer ignore-call */ 
87
        add_action(
Loading history...
87
            'woocommerce_update_options_payment_gateways_' . $this->id,
88
            array($this, 'process_admin_options')
89
        ); //Save plugin options
90
        add_action(
91
            'woocommerce_receipt_' . $this->id,
92
            array($this, 'get_wc_order_received_page')
93
        );          //Pagantis form
94
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
95
        add_filter('woocommerce_payment_complete_order_status', array($this, 'pagantisCompleteStatus'), 10, 3);
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

95
        /** @scrutinizer ignore-call */ 
96
        add_filter('woocommerce_payment_complete_order_status', array($this, 'pagantisCompleteStatus'), 10, 3);
Loading history...
96
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
97
        //add_action('wp_enqueue_scripts', array($this, 'enqueue_ajax_scripts'));
98
    }
99
100
    public function enqueue_ajax_scripts()
101
    {
102
        if ($this->enabled !== 'yes' || ! is_checkout() || is_order_received_page()
0 ignored issues
show
Bug introduced by
The function is_order_received_page 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

102
        if ($this->enabled !== 'yes' || ! is_checkout() || /** @scrutinizer ignore-call */ is_order_received_page()
Loading history...
Bug introduced by
The function is_checkout 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

102
        if ($this->enabled !== 'yes' || ! /** @scrutinizer ignore-call */ is_checkout() || is_order_received_page()
Loading history...
103
            || is_wc_endpoint_url('order-pay')
0 ignored issues
show
Bug introduced by
The function is_wc_endpoint_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

103
            || /** @scrutinizer ignore-call */ is_wc_endpoint_url('order-pay')
Loading history...
104
        ) {
105
            return;
106
        }
107
108
        wp_register_script(
0 ignored issues
show
Bug introduced by
The function wp_register_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

108
        /** @scrutinizer ignore-call */ 
109
        wp_register_script(
Loading history...
109
            'pagantis-checkout',
110
            plugins_url('../assets/js/pagantis-checkout.js', __FILE__),
0 ignored issues
show
Bug introduced by
The function plugins_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

110
            /** @scrutinizer ignore-call */ 
111
            plugins_url('../assets/js/pagantis-checkout.js', __FILE__),
Loading history...
111
            array('jquery', 'woocommerce', 'wc-checkout', 'wc-country-select', 'wc-address-i18n'),
112
            PAGANTIS_VERSION,
113
            true
114
        );
115
        wp_enqueue_script('pagantis-checkout');
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

115
        /** @scrutinizer ignore-call */ 
116
        wp_enqueue_script('pagantis-checkout');
Loading history...
116
117
        $checkout_localize_params                        = array();
118
        $checkout_localize_params['place_order_url']     = WC_AJAX::get_endpoint('pagantis_checkout');
0 ignored issues
show
Bug introduced by
The type WC_AJAX 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...
119
        $checkout_localize_params['place_order_nonce']   = wp_create_nonce('pagantis_checkout');
0 ignored issues
show
Bug introduced by
The function wp_create_nonce 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
        $checkout_localize_params['place_order_nonce']   = /** @scrutinizer ignore-call */ wp_create_nonce('pagantis_checkout');
Loading history...
120
        $checkout_localize_params['wc_ajax_url']         = WC_AJAX::get_endpoint('%%endpoint%%');
121
        $checkout_localize_params['i18n_checkout_error'] =
122
            esc_attr__('Error processing pagantis checkout. Please try again.', 'pagantis');
0 ignored issues
show
Bug introduced by
The function esc_attr__ 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

122
            /** @scrutinizer ignore-call */ 
123
            esc_attr__('Error processing pagantis checkout. Please try again.', 'pagantis');
Loading history...
123
124
        wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params);
0 ignored issues
show
Bug introduced by
The function wp_localize_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

124
        /** @scrutinizer ignore-call */ 
125
        wp_localize_script('pagantis-checkout', 'pagantis_params', $checkout_localize_params);
Loading history...
125
126
        wp_enqueue_script('pagantis_params');
127
    }
128
129
    /**
130
     * @param $mofile
131
     * @param $domain
132
     *
133
     * @return string
134
     */
135
    public function loadPagantisTranslation($mofile, $domain)
136
    {
137
        if ('pagantis' === $domain) {
138
            $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

138
            $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...
139
        }
140
141
        return $mofile;
142
    }
143
144
    /**
145
     * Initialise Gateway Settings Form Fields.
146
     *
147
     * @see WC_Settings_API
148
     */
149
    public function init_form_fields()
150
    {
151
        $this->form_fields = include(plugin_dir_path(__FILE__) . '../includes/settings-pagantis.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

151
        $this->form_fields = include(/** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../includes/settings-pagantis.php');
Loading history...
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
152
    }
153
154
    /***********
155
     * HOOKS
156
     ***********/
157
158
159
    /**
160
     * PANEL - Display admin setting panel
161
     *
162
     * @hook woocommerce_update_options_payment_gateways_pagantis
163
     */
164
    public function admin_options()
165
    {
166
        $template_fields = array(
167
            'panel_description' => $this->method_description,
168
            'button1_label'     => __('Login to your panel', 'pagantis'),
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

168
            'button1_label'     => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
169
            'button2_label'     => __('Documentation', 'pagantis'),
170
            'logo'              => $this->icon,
171
            'settings'          => $this->generate_settings_html($this->form_fields, false),
172
        );
173
        wc_get_template('admin_header.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

173
        /** @scrutinizer ignore-call */ 
174
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
174
    }
175
176
177
    /**
178
     * PANEL - Check admin panel fields -> Hook: admin_notices
179
     *
180
     * @deprecated since 8.3.7
181
     */
182
    public function pagantisCheckFields()
183
    {
184
        _deprecated_function(__METHOD__, '8.3.7', 'check_dependencies');
0 ignored issues
show
Bug introduced by
The function _deprecated_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

184
        /** @scrutinizer ignore-call */ 
185
        _deprecated_function(__METHOD__, '8.3.7', 'check_dependencies');
Loading history...
185
    }
186
187
    private function check_deprecated_arguments()
188
    {
189
        _deprecated_argument(
0 ignored issues
show
Bug introduced by
The function _deprecated_argument 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

189
        /** @scrutinizer ignore-call */ 
190
        _deprecated_argument(
Loading history...
190
            $this->mainFileLocation,
191
            '8.3.7',
192
            '$this->mainFileLocation has been deprecated please use PAGANTIS_VERSION'
193
        );
194
        _deprecated_argument(
195
            $this->plugin_info,
196
            '8.3.7',
197
            ' $this->plugin_info has been deprecated please use PAGANTIS_VERSION'
198
        );
199
        _deprecated_argument(
200
            PAGANTIS_PLUGIN_ID,
201
            '8.3.7',
202
            ' METHOD_ID has been deprecated please use PAGANTIS_PLUGIN_ID'
203
        );
204
    }
205
206
    /**
207
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
208
     *
209
     * @param $order_id
210
     *
211
     * @hook woocommerce_receipt_pagantis
212
     * @throws Exception
213
     */
214
    public function get_wc_order_received_page($order_id)
215
    {
216
        try {
217
            require_once(__ROOT__ . '/vendor/autoload.php');
218
            global $woocommerce;
219
            $order = wc_get_order($order_id);
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

219
            $order = /** @scrutinizer ignore-call */ wc_get_order($order_id);
Loading history...
220
            $order->set_payment_method(ucfirst($this->id));
221
            $order->save();
222
223
            if (! isset($order)) {
224
                throw new Exception(__('Order not found', 'pagantis'));
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
                throw new Exception(/** @scrutinizer ignore-call */ __('Order not found', 'pagantis'));
Loading history...
225
            }
226
227
            $shippingAddress = $order->get_address('shipping');
228
            $billingAddress  = $order->get_address('billing');
229
            if ($shippingAddress['address_1'] === '') {
230
                $shippingAddress = $billingAddress;
231
            }
232
233
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WC_Pagantis_Gateway::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
234
            $tax_id      = $this->getTaxId($order);
235
236
            $userAddress = new Address();
237
            $userAddress->setZipCode($shippingAddress['postcode'])->setFullName($shippingAddress['first_name'] . ' '
238
            . $shippingAddress['last_name'])
239
                        ->setCountryCode($shippingAddress['country'] !== '' ? strtoupper($shippingAddress['country'])
240
                        : strtoupper($this->language))->setCity($shippingAddress['city'])
241
                        ->setAddress($shippingAddress['address_1'] . ' ' . $shippingAddress['address_2']);
242
            $orderShippingAddress = new Address();
243
            $orderShippingAddress->setZipCode($shippingAddress['postcode'])->setFullName($shippingAddress['first_name']
244
                                                                                         . ' '
245
            . $shippingAddress['last_name'])
246
                                ->setCountryCode($shippingAddress['country'] !== ''
247
                                ? strtoupper($shippingAddress['country']) : strtoupper($this->language))
248
                                ->setCity($shippingAddress['city'])->setAddress($shippingAddress['address_1'] . ' '
249
                                . $shippingAddress['address_2'])
250
                                 ->setFixPhone($shippingAddress['phone'])->setMobilePhone($shippingAddress['phone'])
251
                                 ->setNationalId($national_id)->setTaxId($tax_id);
252
            $orderBillingAddress = new Address();
253
            $orderBillingAddress->setZipCode($billingAddress['postcode'])->setFullName($billingAddress['first_name']
254
                                                                                       . ' '
255
            . $billingAddress['last_name'])
256
                                ->setCountryCode($billingAddress['country'] !== ''
257
                                ? strtoupper($billingAddress['country']) : strtoupper($this->language))
258
                                ->setCity($billingAddress['city'])->setAddress($billingAddress['address_1'] . ' '
259
                                . $billingAddress['address_2'])
260
                                ->setFixPhone($billingAddress['phone'])->setMobilePhone($billingAddress['phone'])
261
                                ->setNationalId($national_id)->setTaxId($tax_id);
262
            $orderUser = new User();
263
            $orderUser->setAddress($userAddress)->setFullName($billingAddress['first_name'] . ' '
264
            . $billingAddress['last_name'])
265
                      ->setBillingAddress($orderBillingAddress)->setEmail($billingAddress['email'])
266
                      ->setFixPhone($billingAddress['phone'])->setMobilePhone($billingAddress['phone'])
267
                      ->setShippingAddress($orderShippingAddress)->setNationalId($national_id)->setTaxId($tax_id);
268
269
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
270
            foreach ($previousOrders as $previousOrder) {
271
                $orderHistory = new OrderHistory();
272
                $orderElement = wc_get_order($previousOrder);
273
                $orderCreated = $orderElement->get_date_created();
274
                $orderHistory->setAmount(intval(100 * $orderElement->get_total()))
275
                             ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')));
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

275
                             ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')));
Loading history...
276
                $orderUser->addOrderHistory($orderHistory);
277
            }
278
279
            $metadataOrder = new Metadata();
280
            $metadata      = array(
281
                'pg_module'  => 'woocommerce',
282
                'pg_version' => PAGANTIS_VERSION,
283
                'ec_module'  => 'woocommerce',
284
                'ec_version' => WC()->version,
0 ignored issues
show
Bug introduced by
The function WC 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

284
                'ec_version' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
285
            );
286
287
            foreach ($metadata as $key => $metadatum) {
288
                $metadataOrder->addMetadata($key, $metadatum);
289
            }
290
291
            $details      = new Details();
292
            $shippingCost = $order->shipping_total;
293
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
294
            $items          = $order->get_items();
295
            $promotedAmount = 0;
296
            foreach ($items as $key => $item) {
297
                $wcProduct          = $item->get_product();
298
                $product            = new Product();
299
                $productDescription = sprintf(
300
                    '%s %s %s',
301
                    $wcProduct->get_name(),
302
                    $wcProduct->get_description(),
303
                    $wcProduct->get_short_description()
304
                );
305
                $productDescription = substr($productDescription, 0, 9999);
306
307
                $product->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
308
                        ->setQuantity($item->get_quantity())->setDescription($productDescription);
309
                $details->addProduct($product);
310
311
                $promotedProduct = $this->isPromoted($item->get_product_id());
312
                if ($promotedProduct === 'true') {
313
                    $promotedAmount += $product->getAmount();
314
                    $promotedMessage =
315
                        'Promoted Item: ' . $wcProduct->get_name() . ' - Price: ' . $item->get_total() . ' - Qty: '
316
                        . $product->getQuantity() . ' - Item ID: ' . $item['id_product'];
317
                    $promotedMessage = substr($promotedMessage, 0, 999);
318
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
319
                }
320
            }
321
322
            $orderShoppingCart = new ShoppingCart();
323
            $orderShoppingCart->setDetails($details)->setOrderReference($order->get_id())
324
                              ->setPromotedAmount($promotedAmount)->setTotalAmount(intval(strval(100 * $order->total)));
325
            $orderConfigurationUrls = new Urls();
326
            $cancelUrl              = $this->getKoUrl($order);
327
            $callback_arg           = array(
328
                'wc-api'         => 'wcpagantisgateway',
329
                'key'            => $order->get_order_key(),
330
                'order-received' => $order->get_id(),
331
                'origin'         => '',
332
            );
333
334
            $callback_arg_user           = $callback_arg;
335
            $callback_arg_user['origin'] = 'redirect';
336
            $callback_url_user           = add_query_arg($callback_arg_user, home_url('/'));
0 ignored issues
show
Bug introduced by
The function home_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

336
            $callback_url_user           = add_query_arg($callback_arg_user, /** @scrutinizer ignore-call */ home_url('/'));
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

336
            $callback_url_user           = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
337
338
            $callback_arg_notif           = $callback_arg;
339
            $callback_arg_notif['origin'] = 'notification';
340
            $callback_url_notif           = add_query_arg($callback_arg_notif, home_url('/'));
341
342
            $orderConfigurationUrls->setCancel($cancelUrl)->setKo($callback_url_user)
343
                                   ->setAuthorizedNotificationCallback($callback_url_notif)
344
                                   ->setRejectedNotificationCallback(null)->setOk($callback_url_user);
345
            $orderChannel = new Channel();
346
            $orderChannel->setAssistedSale(false)->setType(Channel::ONLINE);
347
348
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
349
            $purchaseCountry  = in_array(strtolower($this->language), $allowedCountries, true)
350
                ? $this->language
351
                : in_array(strtolower($shippingAddress['country']), $allowedCountries, true)
352
                    ? $shippingAddress['country']
353
                    : in_array(strtolower($billingAddress['country']), $allowedCountries, true)
354
                        ? $billingAddress['country'] : null;
355
356
            $orderConfiguration = new Configuration();
357
            $orderConfiguration->setChannel($orderChannel)->setUrls($orderConfigurationUrls)
358
                               ->setPurchaseCountry($purchaseCountry);
359
360
            $orderApiClient = new Order();
361
            $orderApiClient->setConfiguration($orderConfiguration)->setMetadata($metadataOrder)
362
                           ->setShoppingCart($orderShoppingCart)->setUser($orderUser);
363
364
            if ($this->pagantis_public_key === '' || $this->pagantis_private_key === '') {
365
                throw new \Exception('Public and Secret Key not found');
366
            }
367
            $orderClient   = new Client($this->pagantis_public_key, $this->pagantis_private_key);
368
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
369
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
370
                $url = $pagantisOrder->getActionUrls()->getForm();
371
                $this->insert_row_in_wc_orders_table($order->get_id(), $pagantisOrder->getId());
372
            } else {
373
                throw new OrderNotFoundException();
374
            }
375
376
            if ($url === '') {
377
                throw new Exception(__('No ha sido posible obtener una respuesta de Pagantis', 'pagantis'));
378
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE'] === '0') {
379
                wp_redirect($url);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

379
                /** @scrutinizer ignore-call */ 
380
                wp_redirect($url);
Loading history...
380
                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...
381
            } else {
382
                $template_fields = array(
383
                    'url'         => $url,
384
                    'checkoutUrl' => $cancelUrl,
385
                );
386
                wc_get_template('iframe.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

386
                /** @scrutinizer ignore-call */ 
387
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
387
            }
388
        } catch (\Exception $exception) {
389
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

389
            /** @scrutinizer ignore-call */ 
390
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
390
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($exception);
391
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id 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

391
            $checkout_url = get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout'));
Loading history...
Bug introduced by
The function get_permalink 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

391
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
392
            wp_redirect($checkout_url);
393
            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...
394
        }
395
    }
396
397
    /**
398
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
399
     */
400
    public function pagantisNotification()
401
    {
402
        try {
403
            $origin = ($_SERVER['REQUEST_METHOD'] === 'POST') ? 'Notify' : 'Order';
404
405
            include_once('class-pg-notification-handler.php');
406
            $notify = new WC_PG_Notification_Handler();
407
408
            $notify->setOrigin($origin);
409
            /**
410
             * @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result
411
             */
412
            $result = $notify->processInformation();
413
        } catch (Exception $exception) {
414
            $result['notification_message'] = $exception->getMessage();
415
            $result['notification_error']   = true;
416
        }
417
418
        $paymentOrder = wc_get_order($result->getMerchantOrderId());
0 ignored issues
show
Bug introduced by
The function wc_get_order 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

418
        $paymentOrder = /** @scrutinizer ignore-call */ wc_get_order($result->getMerchantOrderId());
Loading history...
419
        if ($paymentOrder instanceof WC_Order) {
0 ignored issues
show
Bug introduced by
The type WC_Order 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...
420
            $orderStatus = strtolower($paymentOrder->get_status());
421
        } else {
422
            $orderStatus = 'cancelled';
423
        }
424
        $acceptedStatus = array('processing', 'completed');
425
        if (in_array($orderStatus, $acceptedStatus, true)) {
426
            $returnUrl = $this->getOkUrl($paymentOrder);
427
        } else {
428
            $returnUrl = $this->getKoUrl($paymentOrder);
429
        }
430
431
        wp_redirect($returnUrl);
0 ignored issues
show
Bug introduced by
The function wp_redirect 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

431
        /** @scrutinizer ignore-call */ 
432
        wp_redirect($returnUrl);
Loading history...
432
        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...
433
    }
434
435
    /**
436
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
437
     *
438
     * @param $status
439
     * @param $order_id
440
     * @param $order
441
     *
442
     * @return string
443
     */
444
    public function pagantisCompleteStatus($status, $order_id, $order)
445
    {
446
        if ($order->get_payment_method() === PAGANTIS_PLUGIN_ID) {
447
            if ($order->get_status() === 'failed') {
448
                $status = 'processing';
449
            } elseif ($order->get_status() === 'pending' && $status === 'completed') {
450
                $status = 'processing';
451
            }
452
        }
453
454
        return $status;
455
    }
456
457
    /***********
458
     * REDEFINED FUNCTIONS
459
     ***********/
460
461
    /**
462
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply camel caps)
463
     *
464
     * @return bool
465
     */
466
    public function is_available()
467
    {
468
        $locale           = strtolower(strstr(get_locale(), '_', true));
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

468
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
469
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
470
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries, true));
471
        $minAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
472
        $maxAmount        = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
473
        $totalPrice       = (int) $this->get_order_total();
474
        $validAmount      = ($totalPrice >= $minAmount && ($totalPrice <= $maxAmount || $maxAmount === '0'));
475
        if ($this->enabled === 'yes' && $this->pagantis_public_key !== '' && $this->pagantis_private_key !== ''
476
            && $validAmount
477
            && $allowedCountry
478
        ) {
479
            return true;
480
        }
481
482
        return false;
483
    }
484
485
    /**
486
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply camel caps)
487
     *
488
     * @return string
489
     */
490
    public function get_title()
491
    {
492
        return __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
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

492
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
493
    }
494
495
    /**
496
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply camel caps
497
     *
498
     * @param $order_id
499
     *
500
     * @return array
501
     */
502
    public function process_payment($order_id)
503
    {
504
        try {
505
            $order = new WC_Order($order_id);
506
507
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
508
            if (strpos($redirectUrl, 'order-pay=') === false) {
509
                $redirectUrl .= '&order-pay=' . $order_id;
510
            }
511
512
            return array(
513
                'result'   => 'success',
514
                'redirect' => $redirectUrl,
515
            );
516
        } catch (Exception $e) {
517
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice 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

517
            /** @scrutinizer ignore-call */ 
518
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
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

517
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
518
519
            return array();
520
        }
521
    }
522
523
    /**
524
     * CHECKOUT - simulator (called by woocommerce, can't apply camel caps)
525
     */
526
    public function payment_fields()
527
    {
528
        $locale           = strtolower(strstr(get_locale(), '_', true));
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

528
        $locale           = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
529
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
530
        $allowedCountry   = (in_array(strtolower($locale), $allowedCountries, true));
531
        $promotedAmount   = $this->getPromotedAmount();
532
533
        $template_fields = array(
534
            'public_key'            => $this->pagantis_public_key,
535
            'total'                 => WC()->cart->get_total(),
0 ignored issues
show
Bug introduced by
The function WC 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

535
            'total'                 => /** @scrutinizer ignore-call */ WC()->cart->get_total(),
Loading history...
536
            'enabled'               => $this->settings['enabled'],
537
            'min_installments'      => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
538
            'max_installments'      => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'],
539
            'simulator_enabled'     => $this->settings['simulator'],
540
            'locale'                => $locale,
541
            'country'               => $locale,
542
            'allowed_country'       => $allowedCountry,
543
            'simulator_type'        => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE_CHECKOUT'],
544
            'promoted_amount'       => $promotedAmount,
545
            'thousandSeparator'     => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
546
            'decimalSeparator'      => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR'],
547
            'pagantisSimulatorSkin' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_SKIN'],
548
        );
549
        try {
550
            wc_get_template('checkout_description.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

550
            /** @scrutinizer ignore-call */ 
551
            wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
551
        } catch (Exception $exception) {
552
            $exception->getMessage();
553
        }
554
    }
555
556
557
    /***********
558
     * UTILS FUNCTIONS
559
     ***********/
560
561
    /**
562
     * set payment module callback urls
563
     */
564
    private function set_payment_urls()
565
    {
566
        $this->settings['ok_url'] =
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
567
            ($this->extraConfig['PAGANTIS_URL_OK'] !== '') ? $this->extraConfig['PAGANTIS_URL_OK']
568
                : $this->generateOkUrl();
569
        $this->settings['ko_url'] =
570
            ($this->extraConfig['PAGANTIS_URL_KO'] !== '') ? $this->extraConfig['PAGANTIS_URL_KO']
571
                : $this->generateKoUrl();
572
        foreach ($this->settings as $setting_key => $setting_value) {
573
            $this->$setting_key = $setting_value;
574
        }
575
    }
576
577
    /**
578
     * PANEL KO_URL FIELD
579
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
580
     */
581
    private function generateOkUrl()
582
    {
583
        return $this->generateUrl($this->get_return_url());
584
    }
585
586
    /**
587
     * PANEL OK_URL FIELD
588
     */
589
    private function generateKoUrl()
590
    {
591
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id 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

591
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function get_permalink 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

591
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
592
    }
593
594
    /**
595
     * Replace empty space by {{var}}
596
     *
597
     * @param $url
598
     *
599
     * @return string
600
     */
601
    private function generateUrl($url)
602
    {
603
        $parsed_url = parse_url($url);
604
        if ($parsed_url !== false) {
605
            $parsed_url['query'] = ! isset($parsed_url['query']) ? '' : $parsed_url['query'];
606
            parse_str($parsed_url['query'], $arrayParams);
607
            foreach ($arrayParams as $keyParam => $valueParam) {
608
                if ($valueParam === '') {
609
                    $arrayParams[$keyParam] = '{{' . $keyParam . '}}';
610
                }
611
            }
612
            $parsed_url['query'] = http_build_query($arrayParams);
613
            $return_url          = $this->get_unparsed_url($parsed_url);
614
615
            return urldecode($return_url);
616
        } else {
617
            return $url;
618
        }
619
    }
620
621
    /**
622
     * Replace {{}} by vars values inside ok_url
623
     *
624
     * @param $order
625
     *
626
     * @return string
627
     */
628
    private function getOkUrl($order)
629
    {
630
        return $this->getKeysUrl($order, $this->ok_url);
631
    }
632
633
    /**
634
     * Replace {{}} by vars values inside ko_url
635
     *
636
     * @param $order
637
     *
638
     * @return string
639
     */
640
    private function getKoUrl($order)
641
    {
642
        return $this->getKeysUrl($order, $this->ko_url);
643
    }
644
645
    /**
646
     * Replace {{}} by vars values
647
     *
648
     * @param $order
649
     * @param $url
650
     *
651
     * @return string
652
     */
653
    private function getKeysUrl($order, $url)
654
    {
655
        $defaultFields = (get_class($order) === 'WC_Order') ? array(
656
            'order-received' => $order->get_id(),
657
            'key'            => $order->get_order_key()
658
        ) : array();
659
660
        $parsedUrl = parse_url($url);
661
        if ($parsedUrl !== false) {
662
            //Replace parameters from url
663
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
664
665
            //Replace path from url
666
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
667
668
            $returnUrl = $this->get_unparsed_url($parsedUrl);
669
670
            return $returnUrl;
671
        }
672
673
        return $url;
674
    }
675
676
    /**
677
     * Replace {{}} by vars values inside parameters
678
     *
679
     * @param $queryString
680
     * @param $defaultFields
681
     *
682
     * @return string
683
     */
684
    private function getKeysParametersUrl($queryString, $defaultFields)
685
    {
686
        parse_str(html_entity_decode($queryString), $arrayParams);
687
        var_export($queryString);
688
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
689
        if (count($commonKeys)) {
690
            $arrayResult = array_merge($arrayParams, $defaultFields);
691
        } else {
692
            $arrayResult = $arrayParams;
693
        }
694
695
        return urldecode(http_build_query($arrayResult));
696
    }
697
698
    /**
699
     * Replace {{}} by vars values inside path
700
     *
701
     * @param $pathString
702
     * @param $defaultFields
703
     *
704
     * @return string
705
     */
706
    private function getKeysPathUrl($pathString, $defaultFields)
707
    {
708
        $arrayParams = explode('/', $pathString);
709
        foreach ($arrayParams as $keyParam => $valueParam) {
710
            preg_match('#\{{.*?}\}#', $valueParam, $match);
711
            if (count($match)) {
712
                $key                    = str_replace(array('{{', '}}'), array('', ''), $match[0]);
713
                $arrayParams[$keyParam] = $defaultFields[$key];
714
            }
715
        }
716
717
        return implode('/', $arrayParams);
718
    }
719
720
    /**
721
     * Replace {{var}} by empty space
722
     *
723
     * @param $parsed_url
724
     *
725
     * @return string
726
     */
727
    private function get_unparsed_url($parsed_url)
728
    {
729
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
730
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
731
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
732
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
733
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
734
        $path     = $parsed_url['path'];
735
736
        return $scheme . $host . $port . $path . $query . $fragment;
737
    }
738
739
    /**
740
     * Get the orders of a customer
741
     *
742
     * @param $current_user
743
     * @param $billingEmail
744
     *
745
     * @return mixed
746
     */
747
    private function getOrders($current_user, $billingEmail)
748
    {
749
        $sign_up         = '';
750
        $total_orders    = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
751
        $total_amt       = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
752
        $refund_amt      = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
753
        $total_refunds   = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
754
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
755
        if ($current_user->user_login) {
756
            $is_guest        = 'false';
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
757
            $sign_up         = substr($current_user->user_registered, 0, 10);
0 ignored issues
show
Unused Code introduced by
The assignment to $sign_up is dead and can be removed.
Loading history...
758
            $customer_orders = get_posts(array(
0 ignored issues
show
Bug introduced by
The function get_posts 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

758
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
759
                'numberposts' => -1,
760
                'meta_key'    => '_customer_user',
761
                'meta_value'  => $current_user->ID,
762
                'post_type'   => array('shop_order'),
763
                'post_status' => array('wc-completed', 'wc-processing', 'wc-refunded'),
764
            ));
765
        } else {
766
            $is_guest        = 'true';
767
            $customer_orders = get_posts(array(
768
                'numberposts' => -1,
769
                'meta_key'    => '_billing_email',
770
                'meta_value'  => $billingEmail,
771
                'post_type'   => array('shop_order'),
772
                'post_status' => array('wc-completed', 'wc-processing', 'wc-refunded'),
773
            ));
774
            foreach ($customer_orders as $customer_order) {
775
                if (trim($sign_up) === ''
776
                    || strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)
777
                ) {
778
                    $sign_up = substr($customer_order->post_date, 0, 10);
779
                }
780
            }
781
        }
782
783
        return $customer_orders;
784
    }
785
786
787
    /**
788
     *
789
     * @param       $wc_order_id
790
     * @param       $pg_order_id
791
     *
792
     * @throws Exception
793
     * @global wpdb $wpdb WordPress database abstraction object.
794
     */
795
    private function insert_row_in_wc_orders_table($wc_order_id, $pg_order_id)
796
    {
797
        global $wpdb;
798
        $this->check_if_wc_orders_db_table_exist();
799
        $tableName = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
800
801
        //Check if id exists
802
        $resultsSelect = $wpdb->get_results("SELECT * FROM $tableName WHERE id='$wc_order_id'");
803
        $countResults  = count($resultsSelect);
804
        if ($countResults === 0) {
805
            $wpdb->insert($tableName, array('id' => $wc_order_id, 'order_id' => $pg_order_id), array('%d', '%s'));
806
        } else {
807
            $wpdb->update(
808
                $tableName,
809
                array('order_id' => $pg_order_id),
810
                array('id' => $wc_order_id),
811
                array('%s'),
812
                array('%d')
813
            );
814
        }
815
    }
816
817
    /**
818
     * Check if orders table exists
819
     *
820
     * @global wpdb $wpdb WordPress database abstraction object.
821
     */
822
    private function check_if_wc_orders_db_table_exist()
823
    {
824
        global $wpdb;
825
        $tableName = $wpdb->prefix . PAGANTIS_WC_ORDERS_TABLE;
826
827
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") !== $tableName) {
828
            $charset_collate = $wpdb->get_charset_collate();
829
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
830
                  UNIQUE KEY id (id)) $charset_collate";
831
832
            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...
833
            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

833
            /** @scrutinizer ignore-call */ 
834
            dbDelta($sql);
Loading history...
834
        }
835
    }
836
837
838
    /**
839
     * @param $order
840
     *
841
     * @return null
842
     */
843
    private function getNationalId($order)
844
    {
845
        foreach ((array) $order->get_meta_data() as $mdObject) {
846
            $data = $mdObject->get_data();
847
            if ($data['key'] === 'vat_number') {
848
                return $data['value'];
849
            }
850
        }
851
852
        return null;
853
    }
854
855
    /**
856
     * @param $order
857
     *
858
     * @return mixed
859
     */
860
    private function getTaxId($order)
861
    {
862
        foreach ((array) $order->get_meta_data() as $mdObject) {
863
            $data = $mdObject->get_data();
864
            if ($data['key'] === 'billing_cfpiva') {
865
                return $data['value'];
866
            }
867
        }
868
    }
869
870
    /**
871
     * @param null  $exception
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $exception is correct as it would always require null to be passed?
Loading history...
872
     * @param null  $message
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $message is correct as it would always require null to be passed?
Loading history...
873
     *
874
     * @deprecated 8.3.7
875
     */
876
    private function insertLog($exception = null, $message = null)
0 ignored issues
show
Unused Code introduced by
The method insertLog() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
877
    {
878
        wc_deprecated_function('insertLog', '8.3.7', 'WC_Pagantis_Logger::insert_log_entry_in_wpdb');
0 ignored issues
show
Bug introduced by
The function wc_deprecated_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

878
        /** @scrutinizer ignore-call */ 
879
        wc_deprecated_function('insertLog', '8.3.7', 'WC_Pagantis_Logger::insert_log_entry_in_wpdb');
Loading history...
879
880
        if ($exception instanceof \Exception) {
881
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($exception);
882
        } else {
883
            WC_Pagantis_Logger::insert_log_entry_in_wpdb($message);
884
        }
885
    }
886
887
888
889
    /**
890
     * Check if logs table exists
891
     *
892
     * @deprecated 8.3.7
893
     */
894
    private function checkDbLogTable()
0 ignored issues
show
Unused Code introduced by
The method checkDbLogTable() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
895
    {
896
        wc_deprecated_function('checkDbLogTable', '8.3.7', 'pg_wc_check_db_log_table');
0 ignored issues
show
Bug introduced by
The function wc_deprecated_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

896
        /** @scrutinizer ignore-call */ 
897
        wc_deprecated_function('checkDbLogTable', '8.3.7', 'pg_wc_check_db_log_table');
Loading history...
897
    }
898
899
    /**
900
     * @param $product_id
901
     *
902
     * @return string
903
     */
904
    private function isPromoted($product_id)
905
    {
906
        $metaProduct = get_post_meta($product_id);
0 ignored issues
show
Bug introduced by
The function get_post_meta 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

906
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
907
908
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct)
909
                && $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
910
    }
911
912
    /**
913
     * @return int
914
     */
915
    private function getPromotedAmount()
916
    {
917
        //https://wordpress.stackexchange.com/questions/275905/whats-the-difference-between-wc-and-woocommerce
918
        $items          = WC()->cart->get_cart();
0 ignored issues
show
Bug introduced by
The function WC 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

918
        $items          = /** @scrutinizer ignore-call */ WC()->cart->get_cart();
Loading history...
919
        $promotedAmount = 0;
920
        foreach ($items as $key => $item) {
921
            $promotedProduct = $this->isPromoted($item['product_id']);
922
            if ($promotedProduct === 'true') {
923
                $promotedAmount += $item['line_total'] + $item['line_tax'];
924
            }
925
        }
926
927
        return $promotedAmount;
928
    }
929
}
930