Passed
Pull Request — master (#23)
by
unknown
03:33
created

WcPagantisGateway::isPromoted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
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
18
if (!defined('ABSPATH')) {
19
    exit;
20
}
21
22
define('__ROOT__', dirname(dirname(__FILE__)));
23
24
25
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...
26
{
27
    const METHOD_ID = "pagantis";
28
29
    /** Orders tablename */
30
    const ORDERS_TABLE = 'cart_process';
31
32
    /** Concurrency tablename */
33
    const LOGS_TABLE = 'pagantis_logs';
34
35
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
36
37
    const CONFIG_TABLE = 'pagantis_config';
38
39
    /** @var Array $extraConfig */
40
    public $extraConfig;
41
42
    /** @var string $language */
43
    public $language;
44
45
    /**
46
     * WcPagantisGateway constructor.
47
     */
48
    public function __construct()
49
    {
50
        //Mandatory vars for plugin
51
        $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...
52
        $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...
53
        $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...
54
55
        //Useful vars
56
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

56
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
57
        $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...
58
        $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...
59
        $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

59
        $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...
60
        $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

60
        $this->language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
61
62
        if ($this->language == 'es' || $this->language == '') {
63
            $this->icon = esc_url(plugins_url('../assets/images/logopagamastarde.png', __FILE__));
0 ignored issues
show
Bug introduced by
The function plugins_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

63
            $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logopagamastarde.png', __FILE__));
Loading history...
Bug introduced by
The function esc_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

63
            $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logopagamastarde.png', __FILE__));
Loading history...
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...
64
        } else {
65
            $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
66
        }
67
68
        //Panel form fields
69
        $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...
70
        $this->init_settings();
71
72
        $this->extraConfig = $this->getExtraConfig();
73
        $this->title = __($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

73
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
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...
74
75
        $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...
76
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
77
        foreach ($this->settings as $setting_key => $setting_value) {
78
            $this->$setting_key = $setting_value;
79
        }
80
81
        //Hooks
82
        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

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

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

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

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

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

134
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
135
            $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...
136
        } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") {
137
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
138
            $this->settings['enabled'] = 'no';
139
        } 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

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

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

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

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

248
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
249
                'pagantis'         => $this->plugin_info['Version'],
250
                'php'         => phpversion()
251
            );
252
            foreach ($metadata as $key => $metadatum) {
253
                $metadataOrder->addMetadata($key, $metadatum);
254
            }
255
256
            $details = new Details();
257
            $shippingCost = $order->shipping_total;
258
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
259
            $items = $woocommerce->cart->get_cart();
260
            $promotedAmount = 0;
261
            foreach ($items as $key => $item) {
262
                $product = new Product();
263
                $productDescription = sprintf(
264
                    '%s %s %s',
265
                    $item['data']->get_title(),
266
                    $item['data']->get_description(),
267
                    $item['data']->get_short_description()
268
                );
269
                $product
270
                    ->setAmount(intval(100 * $item['line_total']))
271
                    ->setQuantity($item['quantity'])
272
                    ->setDescription($productDescription)
273
                ;
274
                $details->addProduct($product);
275
276
                $promotedProduct = $this->isPromoted($item['product_id']);
277
                if ($promotedProduct == 'true') {
278
                    $promotedAmount+=$product->getAmount();
279
                    $promotedMessage = 'Promoted Item: ' . $product->getDescription() .
280
                                       ' Price: ' . $item['line_total'] .
281
                                       ' Qty: ' . $product->getQuantity() .
282
                                       ' Item ID: ' . $item['id_product'];
283
                    $metadataOrder->addMetadata('promotedProduct', $promotedMessage);
284
                }
285
            }
286
287
            $orderShoppingCart = new ShoppingCart();
288
            $orderShoppingCart
289
                ->setDetails($details)
290
                ->setOrderReference($order->get_id())
291
                ->setPromotedAmount($promotedAmount)
292
                ->setTotalAmount(intval(strval(100 * $order->total)))
293
            ;
294
            $orderConfigurationUrls = new Urls();
295
            $cancelUrl = $this->getKoUrl($order);
296
            $callback_arg = array(
297
                'wc-api'=>'wcpagantisgateway',
298
                'key'=>$order->get_order_key(),
299
                'order-received'=>$order->get_id());
300
            $callback_url = add_query_arg($callback_arg, home_url('/'));
0 ignored issues
show
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

300
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
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

300
            $callback_url = add_query_arg($callback_arg, /** @scrutinizer ignore-call */ home_url('/'));
Loading history...
301
            $orderConfigurationUrls
302
                ->setCancel($cancelUrl)
303
                ->setKo($callback_url)
304
                ->setAuthorizedNotificationCallback($callback_url)
305
                ->setRejectedNotificationCallback($callback_url)
306
                ->setOk($callback_url)
307
            ;
308
            $orderChannel = new Channel();
309
            $orderChannel
310
                ->setAssistedSale(false)
311
                ->setType(Channel::ONLINE)
312
            ;
313
            $orderConfiguration = new Configuration();
314
315
            $orderConfiguration
316
                ->setChannel($orderChannel)
317
                ->setUrls($orderConfigurationUrls)
318
                ->setPurchaseCountry($this->language)
319
            ;
320
321
            $orderApiClient = new Order();
322
            $orderApiClient
323
                ->setConfiguration($orderConfiguration)
324
                ->setMetadata($metadataOrder)
325
                ->setShoppingCart($orderShoppingCart)
326
                ->setUser($orderUser)
327
            ;
328
329
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
330
                throw new \Exception('Public and Secret Key not found');
331
            }
332
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
333
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
334
            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...
335
                $url = $pagantisOrder->getActionUrls()->getForm();
336
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
337
            } else {
338
                throw new OrderNotFoundException();
339
            }
340
341
            if ($url=="") {
342
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
343
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
344
                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

344
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
345
                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...
346
            } else {
347
                $template_fields = array(
348
                    'url' => $url,
349
                    'checkoutUrl'   => $cancelUrl
350
                );
351
                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

351
                /** @scrutinizer ignore-call */ wc_get_template('iframe.php', $template_fields, '', $this->template_path);
Loading history...
352
            }
353
        } catch (\Exception $exception) {
354
            wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

354
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

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

447
        return /** @scrutinizer ignore-call */ 
448
               __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
448
    }
449
450
    /**
451
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
452
     * @param $order_id
453
     * @return array
454
     */
455
    public function process_payment($order_id)
456
    {
457
        try {
458
            $order = new WC_Order($order_id);
459
460
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
461
            if (strpos($redirectUrl, 'order-pay=')===false) {
462
                $redirectUrl.="&order-pay=".$order_id;
463
            }
464
465
            return array(
466
                'result'   => 'success',
467
                'redirect' => $redirectUrl
468
            );
469
470
        } catch (Exception $e) {
471
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

471
            /** @scrutinizer ignore-call */ 
472
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

471
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
472
            return array();
473
        }
474
    }
475
476
    /**
477
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
478
     */
479
    public function payment_fields()
480
    {
481
        global $woocommerce;
482
483
        $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

483
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
484
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
485
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
486
        $promotedAmount = $this->getPromotedAmount();
487
488
        $template_fields = array(
489
            'public_key' => $this->pagantis_public_key,
490
            '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

490
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
491
            'enabled' =>  $this->settings['enabled'],
492
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
493
            'simulator_enabled' => $this->settings['pagantis_simulator'],
494
            'locale' => $locale,
495
            'allowedCountry' => $allowedCountry,
496
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE'],
497
            'promoted_amount' => $promotedAmount
498
        );
499
        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

499
        /** @scrutinizer ignore-call */ 
500
        wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
500
    }
501
502
    /***********
503
     *
504
     * UTILS FUNCTIONS
505
     *
506
     ***********/
507
508
    /**
509
     * PANEL KO_URL FIELD
510
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
511
     */
512
    private function generateOkUrl()
513
    {
514
        return $this->generateUrl($this->get_return_url());
515
    }
516
517
    /**
518
     * PANEL OK_URL FIELD
519
     */
520
    private function generateKoUrl()
521
    {
522
        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

522
        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

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

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

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

828
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
829
        }
830
        return;
831
    }
832
833
    /**
834
     * @param $product_id
835
     *
836
     * @return string
837
     */
838
    private function isPromoted($product_id)
839
    {
840
        $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

840
        $metaProduct = /** @scrutinizer ignore-call */ get_post_meta($product_id);
Loading history...
841
        return ($metaProduct['custom_product_pagantis_promoted']['0'] === 'yes') ? 'true' : 'false';
842
    }
843
844
    /**
845
     * @return int
846
     */
847
    private function getPromotedAmount()
848
    {
849
        global $woocommerce;
850
        $items = $woocommerce->cart->get_cart();
851
        $promotedAmount = 0;
852
        foreach ($items as $key => $item) {
853
            $promotedProduct = $this->isPromoted($item['product_id']);
854
            if ($promotedProduct == 'true') {
855
                $promotedAmount+=$item['line_total'];
856
            }
857
        }
858
859
        return $promotedAmount;
860
    }
861
}
862