Passed
Pull Request — master (#21)
by
unknown
03:09
created

WcPagantisGateway::admin_options()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 8
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 11
rs 10
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_header' => $this->title,
117
            'panel_description' => $this->method_description,
118
            '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

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

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

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

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

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

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

242
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
243
                ;
244
                $orderUser->addOrderHistory($orderHistory);
245
            }
246
247
            $details = new Details();
248
            $shippingCost = $order->shipping_total;
249
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
250
            $items = $woocommerce->cart->get_cart();
251
            foreach ($items as $key => $item) {
252
                $product = new Product();
253
                $productDescription = sprintf(
254
                    '%s %s %s',
255
                    $item['data']->get_title(),
256
                    $item['data']->get_description(),
257
                    $item['data']->get_short_description()
258
                );
259
                $product
260
                    ->setAmount(intval(100 * $item['line_total']))
261
                    ->setQuantity($item['quantity'])
262
                    ->setDescription($productDescription);
263
                $details->addProduct($product);
264
            }
265
266
            $orderShoppingCart = new ShoppingCart();
267
            $orderShoppingCart
268
                ->setDetails($details)
269
                ->setOrderReference($order->get_id())
270
                ->setPromotedAmount(0)
271
                ->setTotalAmount(intval(strval(100 * $order->total)))
272
            ;
273
            $orderConfigurationUrls = new Urls();
274
            $cancelUrl = $this->getKoUrl($order);
275
            $callback_arg = array(
276
                'wc-api'=>'wcpagantisgateway',
277
                'key'=>$order->get_order_key(),
278
                'order-received'=>$order->get_id());
279
            $callback_url = add_query_arg($callback_arg, 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

279
            $callback_url = add_query_arg($callback_arg, /** @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

279
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
280
            $orderConfigurationUrls
281
                ->setCancel($cancelUrl)
282
                ->setKo($callback_url)
283
                ->setAuthorizedNotificationCallback($callback_url)
284
                ->setRejectedNotificationCallback($callback_url)
285
                ->setOk($callback_url)
286
            ;
287
            $orderChannel = new Channel();
288
            $orderChannel
289
                ->setAssistedSale(false)
290
                ->setType(Channel::ONLINE)
291
            ;
292
            $orderConfiguration = new Configuration();
293
294
            $orderConfiguration
295
                ->setChannel($orderChannel)
296
                ->setUrls($orderConfigurationUrls)
297
                ->setPurchaseCountry($this->language)
298
            ;
299
            $metadataOrder = new Metadata();
300
            $metadata = array(
301
                '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

301
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
302
                'pagantis'         => $this->plugin_info['Version'],
303
                'php'         => phpversion()
304
            );
305
            foreach ($metadata as $key => $metadatum) {
306
                $metadataOrder->addMetadata($key, $metadatum);
307
            }
308
            $orderApiClient = new Order();
309
            $orderApiClient
310
                ->setConfiguration($orderConfiguration)
311
                ->setMetadata($metadataOrder)
312
                ->setShoppingCart($orderShoppingCart)
313
                ->setUser($orderUser)
314
            ;
315
316
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
317
                throw new \Exception('Public and Secret Key not found');
318
            }
319
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
320
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
321
            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...
322
                $url = $pagantisOrder->getActionUrls()->getForm();
323
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
324
            } else {
325
                throw new OrderNotFoundException();
326
            }
327
328
            if ($url=="") {
329
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
330
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
331
                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

331
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
332
                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...
333
            } else {
334
                $template_fields = array(
335
                    'url' => $url,
336
                    'checkoutUrl'   => $cancelUrl
337
                );
338
                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

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

341
            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

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

343
            $checkout_url = /** @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

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

380
        /** @scrutinizer ignore-call */ wp_redirect($returnUrl);
Loading history...
381
        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...
382
    }
383
384
    /**
385
     * After failed status, set to processing not complete -> Hook: woocommerce_payment_complete_order_status
386
     * @param $status
387
     * @param $order_id
388
     * @param $order
389
     *
390
     * @return string
391
     */
392
    public function pagantisCompleteStatus($status, $order_id, $order)
393
    {
394
        if ($order->get_payment_method() == WcPagantisGateway::METHOD_ID) {
395
            if ($order->get_status() == 'failed') {
396
                $status = 'processing';
397
            } elseif ($order->get_status() == 'pending' && $status=='completed') {
398
                $status = 'processing';
399
            }
400
        }
401
402
        return $status;
403
    }
404
405
    /***********
406
     *
407
     * REDEFINED FUNCTIONS
408
     *
409
     ***********/
410
411
    /**
412
     * CHECKOUT - Check if payment method is available (called by woocommerce, can't apply cammel caps)
413
     * @return bool
414
     */
415
    public function is_available()
416
    {
417
        $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

417
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
418
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
419
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
420
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
421
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] && $allowedCountry) {
422
            return true;
423
        }
424
425
        return false;
426
    }
427
428
    /**
429
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
430
     * @return string
431
     */
432
    public function get_title()
433
    {
434
        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

434
        return /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
435
    }
436
437
    /**
438
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
439
     * @param $order_id
440
     * @return array
441
     */
442
    public function process_payment($order_id)
443
    {
444
        try {
445
            $order = new WC_Order($order_id);
446
447
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
448
            if (strpos($redirectUrl, 'order-pay=')===false) {
449
                $redirectUrl.="&order-pay=".$order_id;
450
            }
451
452
            return array(
453
                'result'   => 'success',
454
                'redirect' => $redirectUrl
455
            );
456
457
        } catch (Exception $e) {
458
            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

458
            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

458
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
459
            return array();
460
        }
461
    }
462
463
    /**
464
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
465
     */
466
    public function payment_fields()
467
    {
468
        $locale = strtolower(strstr(get_locale(), '_', true));
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

468
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
469
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
470
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
471
472
        $template_fields = array(
473
            'public_key' => $this->pagantis_public_key,
474
            '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

474
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
475
            'enabled' =>  $this->settings['enabled'],
476
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
477
            'simulator_enabled' => $this->settings['pagantis_simulator'],
478
            'locale' => $locale,
479
            'allowedCountry' => $allowedCountry,
480
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE']
481
        );
482
        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

482
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
483
    }
484
485
    /***********
486
     *
487
     * UTILS FUNCTIONS
488
     *
489
     ***********/
490
491
    /**
492
     * PANEL KO_URL FIELD
493
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
494
     */
495
    private function generateOkUrl()
496
    {
497
        return $this->generateUrl($this->get_return_url());
498
    }
499
500
    /**
501
     * PANEL OK_URL FIELD
502
     */
503
    private function generateKoUrl()
504
    {
505
        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

505
        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

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

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

730
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
731
        }
732
    }
733
734
    /**
735
     * @return array
736
     */
737
    private function getExtraConfig()
738
    {
739
        global $wpdb;
740
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
741
        $response = array();
742
        $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...
743
        foreach ($dbResult as $value) {
744
            $response[$value['config']] = $value['value'];
745
        }
746
747
        return $response;
748
    }
749
750
    /**
751
     * @param $order
752
     *
753
     * @return null
754
     */
755
    private function getNationalId($order)
756
    {
757
        foreach ((array)$order->get_meta_data() as $mdObject) {
758
            $data = $mdObject->get_data();
759
            if ($data['key'] == 'vat_number') {
760
                return $data['value'];
761
            }
762
        }
763
764
        return null;
765
    }
766
767
    /**
768
     * @param $order
769
     *
770
     * @return mixed
771
     */
772
    private function getTaxId($order)
773
    {
774
        foreach ((array)$order->get_meta_data() as $mdObject) {
775
            $data = $mdObject->get_data();
776
            if ($data['key'] == 'billing_cfpiva') {
777
                return $data['value'];
778
            }
779
        }
780
    }
781
782
    /**
783
     * @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...
784
     * @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...
785
     */
786
    private function insertLog($exception = null, $message = null)
787
    {
788
        global $wpdb;
789
        $this->checkDbLogTable();
790
        $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...
791
        if ($exception instanceof \Exception) {
792
            $logEntry = $logEntry->error($exception);
793
        } else {
794
            $logEntry = $logEntry->info($message);
795
        }
796
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
797
        $wpdb->insert($tableName, array('log' => $logEntry->toJson()));
798
    }
799
    /**
800
     * Check if logs table exists
801
     */
802
    private function checkDbLogTable()
803
    {
804
        global $wpdb;
805
        $tableName = $wpdb->prefix.self::LOGS_TABLE;
806
        if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) {
807
            $charset_collate = $wpdb->get_charset_collate();
808
            $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, 
809
                    createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate";
810
            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...
811
            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

811
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
812
        }
813
        return;
814
    }
815
}
816