Completed
Push — master ( 7a2686...3cd1d2 )
by pablo
15s queued 14s
created

WcPagantisGateway::pagantisCheckFields()   C

Complexity

Conditions 12
Paths 15

Size

Total Lines 29
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 24
c 0
b 0
f 0
nc 15
nop 0
dl 0
loc 29
rs 6.9666

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
//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
26
class WcPagantisGateway 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...
27
{
28
    const METHOD_ID = "pagantis";
29
30
    /** Orders tablename */
31
    const ORDERS_TABLE = 'cart_process';
32
33
    /** Concurrency tablename */
34
    const LOGS_TABLE = 'pagantis_logs';
35
36
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
37
38
    const CONFIG_TABLE = 'pagantis_config';
39
40
    /** @var Array $extraConfig */
41
    public $extraConfig;
42
43
    /** @var string $language */
44
    public $language;
45
46
    /**
47
     * WcPagantisGateway constructor.
48
     */
49
    public function __construct()
50
    {
51
        //Mandatory vars for plugin
52
        $this->id = WcPagantisGateway::METHOD_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...
53
        $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...
54
        $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...
55
56
        //Useful vars
57
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
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

57
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
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...
58
        $this->allowed_currencies = array("EUR");
0 ignored issues
show
Bug Best Practice introduced by
The property allowed_currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
59
        $this->mainFileLocation = dirname(plugin_dir_path(__FILE__)) . '/WC_Pagantis.php';
0 ignored issues
show
Bug Best Practice introduced by
The property mainFileLocation does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
60
        $this->plugin_info = get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
0 ignored issues
show
Bug introduced by
The function get_file_data 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
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
61
        $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

61
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
62
        $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...
63
64
        //Panel form fields
65
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
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...
66
        $this->init_settings();
67
68
        $this->extraConfig = $this->getExtraConfig();
69
        $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

69
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
70
        $this->method_description = "Financial Payment Gateway. Enable the possibility for your customers to pay their order in confortable installments with Pagantis.";
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...
71
72
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
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...
73
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
74
        foreach ($this->settings as $setting_key => $setting_value) {
75
            $this->$setting_key = $setting_value;
76
        }
77
78
        //Hooks
79
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
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

79
        /** @scrutinizer ignore-call */ add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
80
        add_action('admin_notices', array($this, 'pagantisCheckFields'));                          //Check config fields
81
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
82
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
83
        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

83
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
84
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
85
    }
86
87
    /**
88
     * @param $mofile
89
     * @param $domain
90
     *
91
     * @return string
92
     */
93
    public function loadPagantisTranslation($mofile, $domain)
94
    {
95
        if ('pagantis' === $domain) {
96
            $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

96
            $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...
97
        }
98
        return $mofile;
99
    }
100
101
    /***********
102
     *
103
     * HOOKS
104
     *
105
     ***********/
106
107
    /**
108
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
109
     */
110
    public function admin_options()
111
    {
112
        $template_fields = array(
113
            'panel_description' => $this->method_description,
114
            '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

114
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
115
            'button2_label' => __('Documentation', 'pagantis'),
116
            'logo' => $this->icon,
117
            'settings' => $this->generate_settings_html($this->form_fields, false)
118
        );
119
        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

119
        /** @scrutinizer ignore-call */ 
120
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
120
    }
121
122
    /**
123
     * PANEL - Check admin panel fields -> Hook: admin_notices
124
     */
125
    public function pagantisCheckFields()
126
    {
127
        $error_string = '';
128
        if ($this->settings['enabled'] !== 'yes') {
129
            return;
130
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
131
            $error_string =  __(' is not compatible with your php and/or curl version', '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

131
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
132
            $this->settings['enabled'] = 'no';
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...
133
        } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") {
134
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
135
            $this->settings['enabled'] = 'no';
136
        } elseif (!in_array(get_woocommerce_currency(), $this->allowed_currencies)) {
0 ignored issues
show
Bug introduced by
The function get_woocommerce_currency 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

136
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
137
            $error_string =  __(' only can be used in Euros', 'pagantis');
138
            $this->settings['enabled'] = 'no';
139
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
140
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
141
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
142
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
143
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
144
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
145
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
146
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
147
        }
148
149
        if ($error_string!='') {
150
            $template_fields = array(
151
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
152
            );
153
            wc_get_template('error_msg.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

153
            /** @scrutinizer ignore-call */ wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
154
        }
155
    }
156
157
158
    /**
159
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
160
     * @param $order_id
161
     *
162
     * @throws Exception
163
     */
164
    public function pagantisReceiptPage($order_id)
165
    {
166
        try {
167
            require_once(__ROOT__.'/vendor/autoload.php');
168
            global $woocommerce;
169
            $order = new WC_Order($order_id);
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...
170
            $order->set_payment_method(ucfirst($this->id));
171
            $order->save();
172
173
            if (!isset($order)) {
174
                throw new Exception(_("Order not found"));
175
            }
176
177
            $shippingAddress = $order->get_address('shipping');
178
            $billingAddress = $order->get_address('billing');
179
            if ($shippingAddress['address_1'] == '') {
180
                $shippingAddress = $billingAddress;
181
            }
182
183
            $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 WcPagantisGateway::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...
184
            $tax_id = $this->getTaxId($order);
185
186
            $userAddress = new Address();
187
            $userAddress
188
                ->setZipCode($shippingAddress['postcode'])
189
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
190
                ->setCountryCode($shippingAddress['country'])
191
                ->setCity($shippingAddress['city'])
192
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
193
            ;
194
            $orderShippingAddress = new Address();
195
            $orderShippingAddress
196
                ->setZipCode($shippingAddress['postcode'])
197
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
198
                ->setCountryCode($shippingAddress['country'])
199
                ->setCity($shippingAddress['city'])
200
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
201
                ->setFixPhone($shippingAddress['phone'])
202
                ->setMobilePhone($shippingAddress['phone'])
203
                ->setNationalId($national_id)
204
                ->setTaxId($tax_id)
205
            ;
206
            $orderBillingAddress =  new Address();
207
            $orderBillingAddress
208
                ->setZipCode($billingAddress['postcode'])
209
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
210
                ->setCountryCode($billingAddress['country'])
211
                ->setCity($billingAddress['city'])
212
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
213
                ->setFixPhone($billingAddress['phone'])
214
                ->setMobilePhone($billingAddress['phone'])
215
                ->setNationalId($national_id)
216
                ->setTaxId($tax_id)
217
            ;
218
            $orderUser = new User();
219
            $orderUser
220
                ->setAddress($userAddress)
221
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
222
                ->setBillingAddress($orderBillingAddress)
223
                ->setEmail($billingAddress['email'])
224
                ->setFixPhone($billingAddress['phone'])
225
                ->setMobilePhone($billingAddress['phone'])
226
                ->setShippingAddress($orderShippingAddress)
227
                ->setNationalId($national_id)
228
                ->setTaxId($tax_id)
229
            ;
230
231
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
232
            foreach ($previousOrders as $previousOrder) {
233
                $orderHistory = new OrderHistory();
234
                $orderElement = wc_get_order($previousOrder);
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

234
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
235
                $orderCreated = $orderElement->get_date_created();
236
                $orderHistory
237
                    ->setAmount(intval(100 * $orderElement->get_total()))
238
                    ->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

238
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
239
                ;
240
                $orderUser->addOrderHistory($orderHistory);
241
            }
242
243
            $metadataOrder = new Metadata();
244
            $metadata = array(
245
                'woocommerce' => 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

245
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
246
                'pagantis'         => $this->plugin_info['Version'],
247
                'php'         => phpversion()
248
            );
249
            foreach ($metadata as $key => $metadatum) {
250
                $metadataOrder->addMetadata($key, $metadatum);
251
            }
252
253
            $details = new Details();
254
            $shippingCost = $order->shipping_total;
255
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
256
            $items = $order->get_items();
257
            $promotedAmount = 0;
258
            foreach ($items as $key => $item) {
259
                $wcProduct = $item->get_product();
260
                $product = new Product();
261
                $productDescription = sprintf(
262
                    '%s %s %s',
263
                    $wcProduct->get_name(),
264
                    $wcProduct->get_description(),
265
                    $wcProduct->get_short_description()
266
                );
267
                $productDescription = substr($productDescription, 0, 9999);
268
269
                $product
270
                    ->setAmount(intval(100 * ($item->get_total() + $item->get_total_tax())))
271
                    ->setQuantity($item->get_quantity())
272
                    ->setDescription($productDescription)
273
                ;
274
                $details->addProduct($product);
275
276
                $promotedProduct = $this->isPromoted($item->get_product_id());
277
                if ($promotedProduct == 'true') {
278
                    $promotedAmount+=$product->getAmount();
279
                    $promotedMessage = 'Promoted Item: ' . $wcProduct->get_name() .
280
                                       ' - Price: ' . $item->get_total() .
281
                                       ' - Qty: ' . $product->getQuantity() .
282
                                       ' - Item ID: ' . $item['id_product'];
283
                    $promotedMessage = substr($promotedMessage, 0, 999);
284
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
285
                }
286
            }
287
288
            $orderShoppingCart = new ShoppingCart();
289
            $orderShoppingCart
290
                ->setDetails($details)
291
                ->setOrderReference($order->get_id())
292
                ->setPromotedAmount($promotedAmount)
293
                ->setTotalAmount(intval(strval(100 * $order->total)))
294
            ;
295
            $orderConfigurationUrls = new Urls();
296
            $cancelUrl = $this->getKoUrl($order);
297
            $callback_arg = array('wc-api'=>'wcpagantisgateway',
298
                'key'=>$order->get_order_key(),
299
                'order-received'=>$order->get_id(),
300
                'origin' => ''
301
            );
302
303
            $callback_arg_user = $callback_arg;
304
            $callback_arg_user['origin'] = 'redirect';
305
            $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

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

305
            $callback_url_user = /** @scrutinizer ignore-call */ add_query_arg($callback_arg_user, home_url('/'));
Loading history...
306
307
            $callback_arg_notif = $callback_arg;
308
            $callback_arg_notif['origin'] = 'notification';
309
            $callback_url_notif = add_query_arg($callback_arg_notif, home_url('/'));
310
311
            $orderConfigurationUrls
312
                ->setCancel($cancelUrl)
313
                ->setKo($callback_url_user)
314
                ->setAuthorizedNotificationCallback($callback_url_notif)
315
                ->setRejectedNotificationCallback(null)
316
                ->setOk($callback_url_user)
317
            ;
318
            $orderChannel = new Channel();
319
            $orderChannel
320
                ->setAssistedSale(false)
321
                ->setType(Channel::ONLINE)
322
            ;
323
324
            $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
325
            $purchaseCountry =
326
                in_array(strtolower($this->language), $allowedCountries) ? $this->language :
327
                in_array(strtolower($shippingAddress['country']), $allowedCountries) ? $shippingAddress['country'] :
328
                in_array(strtolower($billingAddress['country']), $allowedCountries) ? $billingAddress['country'] : null;
329
330
            $orderConfiguration = new Configuration();
331
            $orderConfiguration
332
                ->setChannel($orderChannel)
333
                ->setUrls($orderConfigurationUrls)
334
                ->setPurchaseCountry($purchaseCountry)
335
            ;
336
337
            $orderApiClient = new Order();
338
            $orderApiClient
339
                ->setConfiguration($orderConfiguration)
340
                ->setMetadata($metadataOrder)
341
                ->setShoppingCart($orderShoppingCart)
342
                ->setUser($orderUser)
343
            ;
344
345
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
346
                throw new \Exception('Public and Secret Key not found');
347
            }
348
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
349
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
350
            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...
351
                $url = $pagantisOrder->getActionUrls()->getForm();
352
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
353
            } else {
354
                throw new OrderNotFoundException();
355
            }
356
357
            if ($url=="") {
358
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
359
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
360
                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

360
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
361
                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...
362
            } else {
363
                $template_fields = array(
364
                    'url' => $url,
365
                    'checkoutUrl'   => $cancelUrl
366
                );
367
                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

367
                /** @scrutinizer ignore-call */ wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
368
            }
369
        } catch (\Exception $exception) {
370
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
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

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

370
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
371
            $this->insertLog($exception);
372
            $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

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

372
            $checkout_url = /** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout'));
Loading history...
373
            wp_redirect($checkout_url);
374
            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...
375
        }
376
    }
377
378
    /**
379
     * NOTIFICATION - Endpoint for Json notification - Hook: woocommerce_api_wcpagantisgateway
380
     */
381
    public function pagantisNotification()
382
    {
383
        try {
384
            $origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notify' : 'Order';
385
386
            include_once('notifyController.php');
387
            $notify = new WcPagantisNotify();
388
            $notify->setOrigin($origin);
389
            /** @var \Pagantis\ModuleUtils\Model\Response\AbstractJsonResponse $result */
390
            $result = $notify->processInformation();
391
        } catch (Exception $exception) {
392
            $result['notification_message'] = $exception->getMessage();
393
            $result['notification_error'] = true;
394
        }
395
396
        $paymentOrder = new WC_Order($result->getMerchantOrderId());
397
        if ($paymentOrder instanceof WC_Order) {
398
            $orderStatus = strtolower($paymentOrder->get_status());
399
        } else {
400
            $orderStatus = 'cancelled';
401
        }
402
        $acceptedStatus = array('processing', 'completed');
403
        if (in_array($orderStatus, $acceptedStatus)) {
404
            $returnUrl = $this->getOkUrl($paymentOrder);
405
        } else {
406
            $returnUrl = $this->getKoUrl($paymentOrder);
407
        }
408
409
        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

409
        /** @scrutinizer ignore-call */ 
410
        wp_redirect($returnUrl);
Loading history...
410
        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...
411
    }
412
413
    /**
414
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
415
     * @param $status
416
     * @param $order_id
417
     * @param $order
418
     *
419
     * @return string
420
     */
421
    public function pagantisCompleteStatus($status, $order_id, $order)
422
    {
423
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
424
            if ($order->get_status() == 'failed') {
425
                $status = 'processing';
426
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
427
                $status = 'processing';
428
            }
429
        }
430
431
        return $status;
432
    }
433
434
    /***********
435
     *
436
     * REDEFINED FUNCTIONS
437
     *
438
     ***********/
439
440
    /**
441
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
442
     * @return bool
443
     */
444
    public function is_available()
445
    {
446
        $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

446
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
447
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
448
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
449
        $minAmount = $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'];
450
        $maxAmount = $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'];
451
        $totalPrice = (int)$this->get_order_total();
452
        $validAmount = ($totalPrice>=$minAmount && ($totalPrice<=$maxAmount || $maxAmount=='0'));
453
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
454
            $validAmount && $allowedCountry) {
455
            return true;
456
        }
457
458
        return false;
459
    }
460
461
    /**
462
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
463
     * @return string
464
     */
465
    public function get_title()
466
    {
467
        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

467
        return /** @scrutinizer ignore-call */ 
468
               __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
468
    }
469
470
    /**
471
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
472
     * @param $order_id
473
     * @return array
474
     */
475
    public function process_payment($order_id)
476
    {
477
        try {
478
            $order = new WC_Order($order_id);
479
480
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
481
            if (strpos($redirectUrl, 'order-pay=')===false) {
482
                $redirectUrl.="&order-pay=".$order_id;
483
            }
484
485
            return array(
486
                'result'   => 'success',
487
                'redirect' => $redirectUrl
488
            );
489
490
        } catch (Exception $e) {
491
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
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

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

491
            /** @scrutinizer ignore-call */ 
492
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
492
            return array();
493
        }
494
    }
495
496
    /**
497
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
498
     */
499
    public function payment_fields()
500
    {
501
        $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

501
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
502
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
503
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
504
        $promotedAmount = $this->getPromotedAmount();
505
506
        $template_fields = array(
507
            'public_key' => $this->pagantis_public_key,
508
            'total' => WC()->session->cart_totals['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

508
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
509
            'enabled' =>  $this->settings['enabled'],
510
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
511
            'max_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MAX_AMOUNT'],
512
            'simulator_enabled' => $this->settings['simulator'],
513
            'locale' => $locale,
514
            'country' => $locale,
515
            'allowed_country' => $allowedCountry,
516
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
517
            'promoted_amount' => $promotedAmount,
518
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
519
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR']
520
        );
521
        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

521
        /** @scrutinizer ignore-call */ 
522
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
522
    }
523
524
    /***********
525
     *
526
     * UTILS FUNCTIONS
527
     *
528
     ***********/
529
530
    /**
531
     * PANEL KO_URL FIELD
532
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
533
     */
534
    private function generateOkUrl()
535
    {
536
        return $this->generateUrl($this->get_return_url());
537
    }
538
539
    /**
540
     * PANEL OK_URL FIELD
541
     */
542
    private function generateKoUrl()
543
    {
544
        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

544
        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

544
        return $this->generateUrl(/** @scrutinizer ignore-call */ get_permalink(wc_get_page_id('checkout')));
Loading history...
545
    }
546
547
    /**
548
     * Replace empty space by {{var}}
549
     * @param $url
550
     *
551
     * @return string
552
     */
553
    private function generateUrl($url)
554
    {
555
        $parsed_url = parse_url($url);
556
        if ($parsed_url !== false) {
557
            $parsed_url['query'] = !isset($parsed_url['query']) ? '' : $parsed_url['query'];
558
            parse_str($parsed_url['query'], $arrayParams);
559
            foreach ($arrayParams as $keyParam => $valueParam) {
560
                if ($valueParam=='') {
561
                    $arrayParams[$keyParam] = '{{'.$keyParam.'}}';
562
                }
563
            }
564
            $parsed_url['query'] = http_build_query($arrayParams);
565
            $return_url = $this->unparseUrl($parsed_url);
566
            return urldecode($return_url);
567
        } else {
568
            return $url;
569
        }
570
    }
571
572
    /**
573
     * Replace {{}} by vars values inside ok_url
574
     * @param $order
575
     *
576
     * @return string
577
     */
578
    private function getOkUrl($order)
579
    {
580
        return $this->getKeysUrl($order, $this->ok_url);
581
    }
582
583
    /**
584
     * Replace {{}} by vars values inside ko_url
585
     * @param $order
586
     *
587
     * @return string
588
     */
589
    private function getKoUrl($order)
590
    {
591
        return $this->getKeysUrl($order, $this->ko_url);
592
    }
593
594
    /**
595
     * Replace {{}} by vars values
596
     * @param $order
597
     * @param $url
598
     *
599
     * @return string
600
     */
601
    private function getKeysUrl($order, $url)
602
    {
603
        $defaultFields = (get_class($order)=='WC_Order') ?
604
            array('order-received'=>$order->get_id(), 'key'=>$order->get_order_key()) :
605
            array();
606
607
        $parsedUrl = parse_url($url);
608
        if ($parsedUrl !== false) {
609
            //Replace parameters from url
610
            $parsedUrl['query'] = $this->getKeysParametersUrl($parsedUrl['query'], $defaultFields);
611
612
            //Replace path from url
613
            $parsedUrl['path'] = $this->getKeysPathUrl($parsedUrl['path'], $defaultFields);
614
615
            $returnUrl = $this->unparseUrl($parsedUrl);
616
            return $returnUrl;
617
        }
618
        return $url;
619
    }
620
621
    /**
622
     * Replace {{}} by vars values inside parameters
623
     * @param $queryString
624
     * @param $defaultFields
625
     *
626
     * @return string
627
     */
628
    private function getKeysParametersUrl($queryString, $defaultFields)
629
    {
630
        parse_str(html_entity_decode($queryString), $arrayParams);
631
        $commonKeys = array_intersect_key($arrayParams, $defaultFields);
632
        if (count($commonKeys)) {
633
            $arrayResult = array_merge($arrayParams, $defaultFields);
634
        } else {
635
            $arrayResult = $arrayParams;
636
        }
637
        return urldecode(http_build_query($arrayResult));
638
    }
639
640
    /**
641
     * Replace {{}} by vars values inside path
642
     * @param $pathString
643
     * @param $defaultFields
644
     *
645
     * @return string
646
     */
647
    private function getKeysPathUrl($pathString, $defaultFields)
648
    {
649
        $arrayParams = explode("/", $pathString);
650
        foreach ($arrayParams as $keyParam => $valueParam) {
651
            preg_match('#\{{.*?}\}#', $valueParam, $match);
652
            if (count($match)) {
653
                $key = str_replace(array('{{','}}'), array('',''), $match[0]);
654
                $arrayParams[$keyParam] = $defaultFields[$key];
655
            }
656
        }
657
        return implode('/', $arrayParams);
658
    }
659
660
    /**
661
     * Replace {{var}} by empty space
662
     * @param $parsed_url
663
     *
664
     * @return string
665
     */
666
    private function unparseUrl($parsed_url)
667
    {
668
        $scheme   = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : '';
669
        $host     = isset($parsed_url['host']) ? $parsed_url['host'] : '';
670
        $port     = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : '';
671
        $query    = isset($parsed_url['query']) ? '?' . $parsed_url['query'] : '';
672
        $fragment = isset($parsed_url['fragment']) ? '#' . $parsed_url['fragment'] : '';
673
        $path     = $parsed_url['path'];
674
        return $scheme . $host . $port . $path . $query . $fragment;
675
    }
676
677
    /**
678
     * Get the orders of a customer
679
     * @param $current_user
680
     * @param $billingEmail
681
     *
682
     * @return mixed
683
     */
684
    private function getOrders($current_user, $billingEmail)
685
    {
686
        $sign_up = '';
687
        $total_orders = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_orders is dead and can be removed.
Loading history...
688
        $total_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_amt is dead and can be removed.
Loading history...
689
        $refund_amt = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $refund_amt is dead and can be removed.
Loading history...
690
        $total_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $total_refunds is dead and can be removed.
Loading history...
691
        $partial_refunds = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $partial_refunds is dead and can be removed.
Loading history...
692
        if ($current_user->user_login) {
693
            $is_guest = "false";
0 ignored issues
show
Unused Code introduced by
The assignment to $is_guest is dead and can be removed.
Loading history...
694
            $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...
695
            $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

695
            $customer_orders = /** @scrutinizer ignore-call */ get_posts(array(
Loading history...
696
                'numberposts' => - 1,
697
                'meta_key'    => '_customer_user',
698
                'meta_value'  => $current_user->ID,
699
                'post_type'   => array( 'shop_order' ),
700
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded' ),
701
            ));
702
        } else {
703
            $is_guest = "true";
704
            $customer_orders = get_posts(array(
705
                'numberposts' => - 1,
706
                'meta_key'    => '_billing_email',
707
                'meta_value'  => $billingEmail,
708
                'post_type'   => array( 'shop_order' ),
709
                'post_status' => array( 'wc-completed', 'wc-processing', 'wc-refunded'),
710
            ));
711
            foreach ($customer_orders as $customer_order) {
712
                if (trim($sign_up)=='' ||
713
                    strtotime(substr($customer_order->post_date, 0, 10)) <= strtotime($sign_up)) {
714
                    $sign_up = substr($customer_order->post_date, 0, 10);
715
                }
716
            }
717
        }
718
719
        return $customer_orders;
720
    }
721
722
723
    /**
724
     * @param $orderId
725
     * @param $pagantisOrderId
726
     *
727
     * @throws Exception
728
     */
729
    private function insertRow($orderId, $pagantisOrderId)
730
    {
731
        global $wpdb;
732
        $this->checkDbTable();
733
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
734
735
        //Check if id exists
736
        $resultsSelect = $wpdb->get_results("select * from $tableName where id='$orderId'");
737
        $countResults = count($resultsSelect);
738
        if ($countResults == 0) {
739
            $wpdb->insert(
740
                $tableName,
741
                array('id' => $orderId, 'order_id' => $pagantisOrderId),
742
                array('%d', '%s')
743
            );
744
        } else {
745
            $wpdb->update(
746
                $tableName,
747
                array('order_id' => $pagantisOrderId),
748
                array('id' => $orderId),
749
                array('%s'),
750
                array('%d')
751
            );
752
        }
753
    }
754
755
    /**
756
     * Check if orders table exists
757
     */
758
    private function checkDbTable()
759
    {
760
        global $wpdb;
761
        $tableName = $wpdb->prefix.self::ORDERS_TABLE;
762
763
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
764
            $charset_collate = $wpdb->get_charset_collate();
765
            $sql             = "CREATE TABLE $tableName ( id int, order_id varchar(50), wc_order_id varchar(50),  
766
                  UNIQUE KEY id (id)) $charset_collate";
767
768
            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...
769
            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

769
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
770
        }
771
    }
772
773
    /**
774
     * @return array
775
     */
776
    private function getExtraConfig()
777
    {
778
        global $wpdb;
779
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
780
        $response = array();
781
        $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...
782
        foreach ($dbResult as $value) {
783
            $response[$value['config']] = $value['value'];
784
        }
785
786
        return $response;
787
    }
788
789
    /**
790
     * @param $order
791
     *
792
     * @return null
793
     */
794
    private function getNationalId($order)
795
    {
796
        foreach ((array)$order->get_meta_data() as $mdObject) {
797
            $data = $mdObject->get_data();
798
            if ($data['key'] == 'vat_number') {
799
                return $data['value'];
800
            }
801
        }
802
803
        return null;
804
    }
805
806
    /**
807
     * @param $order
808
     *
809
     * @return mixed
810
     */
811
    private function getTaxId($order)
812
    {
813
        foreach ((array)$order->get_meta_data() as $mdObject) {
814
            $data = $mdObject->get_data();
815
            if ($data['key'] == 'billing_cfpiva') {
816
                return $data['value'];
817
            }
818
        }
819
    }
820
821
    /**
822
     * @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...
823
     * @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...
824
     */
825
    private function insertLog($exception = null, $message = null)
826
    {
827
        global $wpdb;
828
        $this->checkDbLogTable();
829
        $logEntry     = new LogEntry();
830
        if ($exception instanceof \Exception) {
831
            $logEntry = $logEntry->error($exception);
832
        } else {
833
            $logEntry = $logEntry->info($message);
834
        }
835
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
836
        $wpdb->insert($tableName, array('log' => $logEntry->toJson()));
837
    }
838
    /**
839
     * Check if logs table exists
840
     */
841
    private function checkDbLogTable()
842
    {
843
        global $wpdb;
844
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
845
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
846
            $charset_collate = $wpdb->get_charset_collate();
847
            $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, 
848
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate";
849
            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...
850
            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

850
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
851
        }
852
        return;
853
    }
854
855
    /**
856
     * @param $product_id
857
     *
858
     * @return string
859
     */
860
    private function isPromoted($product_id)
861
    {
862
        $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

862
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
863
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
864
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
865
    }
866
867
    /**
868
     * @return int
869
     */
870
    private function getPromotedAmount()
871
    {
872
        global $woocommerce;
873
        $items = $woocommerce->cart->get_cart();
874
        $promotedAmount = 0;
875
        foreach ($items as $key => $item) {
876
            $promotedProduct = $this->isPromoted($item['product_id']);
877
            if ($promotedProduct == 'true') {
878
                $promotedAmount+=$item['line_total'] + $item['line_tax'];
879
            }
880
        }
881
882
        return $promotedAmount;
883
    }
884
}
885