Completed
Push — master ( da3f71...7a2686 )
by pablo
19s queued 14s
created

WcPagantisGateway::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 36
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 24
nc 8
nop 0
dl 0
loc 36
rs 9.536
c 0
b 0
f 0
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
            $orderConfiguration = new Configuration();
324
325
            $orderConfiguration
326
                ->setChannel($orderChannel)
327
                ->setUrls($orderConfigurationUrls)
328
                ->setPurchaseCountry($this->language)
329
            ;
330
331
            $orderApiClient = new Order();
332
            $orderApiClient
333
                ->setConfiguration($orderConfiguration)
334
                ->setMetadata($metadataOrder)
335
                ->setShoppingCart($orderShoppingCart)
336
                ->setUser($orderUser)
337
            ;
338
339
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
340
                throw new \Exception('Public and Secret Key not found');
341
            }
342
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
343
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
344
            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...
345
                $url = $pagantisOrder->getActionUrls()->getForm();
346
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
347
            } else {
348
                throw new OrderNotFoundException();
349
            }
350
351
            if ($url=="") {
352
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
353
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
354
                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

354
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
355
                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...
356
            } else {
357
                $template_fields = array(
358
                    'url' => $url,
359
                    'checkoutUrl'   => $cancelUrl
360
                );
361
                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

361
                /** @scrutinizer ignore-call */ wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
362
            }
363
        } catch (\Exception $exception) {
364
            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

364
            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

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

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

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

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

440
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
441
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
442
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
443
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
444
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] && $allowedCountry) {
445
            return true;
446
        }
447
448
        return false;
449
    }
450
451
    /**
452
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
453
     * @return string
454
     */
455
    public function get_title()
456
    {
457
        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

457
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
458
    }
459
460
    /**
461
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
462
     * @param $order_id
463
     * @return array
464
     */
465
    public function process_payment($order_id)
466
    {
467
        try {
468
            $order = new WC_Order($order_id);
469
470
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
471
            if (strpos($redirectUrl, 'order-pay=')===false) {
472
                $redirectUrl.="&order-pay=".$order_id;
473
            }
474
475
            return array(
476
                'result'   => 'success',
477
                'redirect' => $redirectUrl
478
            );
479
480
        } catch (Exception $e) {
481
            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

481
            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

481
            /** @scrutinizer ignore-call */ 
482
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
482
            return array();
483
        }
484
    }
485
486
    /**
487
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
488
     */
489
    public function payment_fields()
490
    {
491
        $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

491
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
492
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
493
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
494
        $promotedAmount = $this->getPromotedAmount();
495
496
        $template_fields = array(
497
            'public_key' => $this->pagantis_public_key,
498
            '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

498
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
499
            'enabled' =>  $this->settings['enabled'],
500
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
501
            'simulator_enabled' => $this->settings['simulator'],
502
            'locale' => $locale,
503
            'country' => $locale,
504
            'allowed_country' => $allowedCountry,
505
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
506
            'promoted_amount' => $promotedAmount,
507
            'thousandSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_THOUSANDS_SEPARATOR'],
508
            'decimalSeparator' => $this->extraConfig['PAGANTIS_SIMULATOR_DECIMAL_SEPARATOR']
509
        );
510
        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

510
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
511
    }
512
513
    /***********
514
     *
515
     * UTILS FUNCTIONS
516
     *
517
     ***********/
518
519
    /**
520
     * PANEL KO_URL FIELD
521
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
522
     */
523
    private function generateOkUrl()
524
    {
525
        return $this->generateUrl($this->get_return_url());
526
    }
527
528
    /**
529
     * PANEL OK_URL FIELD
530
     */
531
    private function generateKoUrl()
532
    {
533
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
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

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

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

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

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

839
            /** @scrutinizer ignore-call */ 
840
            dbDelta($sql);
Loading history...
840
        }
841
        return;
842
    }
843
844
    /**
845
     * @param $product_id
846
     *
847
     * @return string
848
     */
849
    private function isPromoted($product_id)
850
    {
851
        $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

851
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
852
        return (array_key_exists('custom_product_pagantis_promoted', $metaProduct) &&
853
                $metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
854
    }
855
856
    /**
857
     * @return int
858
     */
859
    private function getPromotedAmount()
860
    {
861
        global $woocommerce;
862
        $items = $woocommerce->cart->get_cart();
863
        $promotedAmount = 0;
864
        foreach ($items as $key => $item) {
865
            $promotedProduct = $this->isPromoted($item['product_id']);
866
            if ($promotedProduct == 'true') {
867
                $promotedAmount+=$item['line_total'] + $item['line_tax'];
868
            }
869
        }
870
871
        return $promotedAmount;
872
    }
873
}
874