Completed
Push — master ( dc4a33...026455 )
by
unknown
16s queued 10s
created

WcPagantisGateway::checkDbLogTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 12
rs 9.9666
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
    /**
43
     * WcPagantisGateway constructor.
44
     */
45
    public function __construct()
46
    {
47
        //Mandatory vars for plugin
48
        $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...
49
        $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
0 ignored issues
show
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
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

49
        $this->icon = esc_url(/** @scrutinizer ignore-call */ plugins_url('../assets/images/logo.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

49
        $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
50
        $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...
51
        $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...
52
        $this->title = $this->extraConfig['PAGANTIS_TITLE'];
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
54
        //Useful vars
55
        $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

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

58
        $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...
59
60
        //Panel form fields
61
        $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...
62
        $this->init_settings();
63
64
        $this->extraConfig = $this->getExtraConfig();
65
66
        $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...
67
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
68
        foreach ($this->settings as $setting_key => $setting_value) {
69
            $this->$setting_key = $setting_value;
70
        }
71
72
        //Hooks
73
        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

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

77
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
78
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
79
    }
80
81
    /**
82
     * @param $mofile
83
     * @param $domain
84
     *
85
     * @return string
86
     */
87
    public function loadPagantisTranslation($mofile, $domain)
88
    {
89
        if ('pagantis' === $domain) {
90
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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

90
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
91
        }
92
        return $mofile;
93
    }
94
95
    /***********
96
     *
97
     * HOOKS
98
     *
99
     ***********/
100
101
    /**
102
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
103
     */
104
    public function admin_options()
105
    {
106
        $template_fields = array(
107
            'panel_header' => $this->title,
108
            'panel_description' => $this->method_description,
109
            'button1_label' => __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
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

109
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
Loading history...
110
            'button2_label' => __('Documentation', 'pagantis'),
111
            'logo' => $this->icon,
112
            'settings' => $this->generate_settings_html($this->form_fields, false)
113
        );
114
        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

114
        /** @scrutinizer ignore-call */ wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
115
    }
116
117
    /**
118
     * PANEL - Check admin panel fields -> Hook: admin_notices
119
     */
120
    public function pagantisCheckFields()
121
    {
122
        $error_string = '';
123
        if ($this->settings['enabled'] !== 'yes') {
124
            return;
125
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
126
            $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

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

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

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

229
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
230
                $orderCreated = $orderElement->get_date_created();
231
                $orderHistory
232
                    ->setAmount(intval(100 * $orderElement->get_total()))
233
                    ->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

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

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

270
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
271
            $orderConfigurationUrls
272
                ->setCancel($cancelUrl)
273
                ->setKo($callback_url)
274
                ->setAuthorizedNotificationCallback($callback_url)
275
                ->setRejectedNotificationCallback($callback_url)
276
                ->setOk($callback_url)
277
            ;
278
            $orderChannel = new Channel();
279
            $orderChannel
280
                ->setAssistedSale(false)
281
                ->setType(Channel::ONLINE)
282
            ;
283
            $orderConfiguration = new Configuration();
284
            $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

284
            $language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
285
            $orderConfiguration
286
                ->setChannel($orderChannel)
287
                ->setUrls($orderConfigurationUrls)
288
                ->setPurchaseCountry($language)
289
            ;
290
            $metadataOrder = new Metadata();
291
            $metadata = array(
292
                '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

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

322
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
323
                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...
324
            } else {
325
                $template_fields = array(
326
                    'url' => $url,
327
                    'checkoutUrl'   => $cancelUrl
328
                );
329
                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

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

332
            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

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

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

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

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

408
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
409
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
410
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
411
        if ($this->enabled==='yes' && $this->pagantis_public_key!='' && $this->pagantis_private_key!='' &&
412
            (int)$this->get_order_total()>$this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'] && $allowedCountry) {
413
            return true;
414
        }
415
416
        return false;
417
    }
418
419
    /**
420
     * CHECKOUT - Checkout + admin panel title(method_title - get_title) (called by woocommerce,can't apply cammel caps)
421
     * @return string
422
     */
423
    public function get_title()
424
    {
425
        return $this->extraConfig['PAGANTIS_TITLE'];
426
    }
427
428
    /**
429
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
430
     * @param $order_id
431
     * @return array
432
     */
433
    public function process_payment($order_id)
434
    {
435
        try {
436
            $order = new WC_Order($order_id);
437
438
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
439
            if (strpos($redirectUrl, 'order-pay=')===false) {
440
                $redirectUrl.="&order-pay=".$order_id;
441
            }
442
443
            return array(
444
                'result'   => 'success',
445
                'redirect' => $redirectUrl
446
            );
447
448
        } catch (Exception $e) {
449
            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

449
            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

449
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
450
            return array();
451
        }
452
    }
453
454
    /**
455
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
456
     */
457
    public function payment_fields()
458
    {
459
        $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

459
        $locale = strtolower(strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true));
Loading history...
460
        $allowedCountries = unserialize($this->extraConfig['PAGANTIS_ALLOWED_COUNTRIES']);
461
        $allowedCountry = (in_array(strtolower($locale), $allowedCountries));
462
463
        $template_fields = array(
464
            'public_key' => $this->pagantis_public_key,
465
            '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

465
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
466
            'enabled' =>  $this->settings['enabled'],
467
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
468
            'message' => __($this->extraConfig['PAGANTIS_TITLE_EXTRA']),
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

468
            'message' => /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE_EXTRA']),
Loading history...
469
            'simulator_enabled' => $this->settings['pagantis_simulator'],
470
            'locale' => $locale,
471
            'allowedCountry' => $allowedCountry,
472
            'simulator_type' => $this->extraConfig['PAGANTIS_SIMULATOR_DISPLAY_TYPE']
473
        );
474
        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

474
        /** @scrutinizer ignore-call */ wc_get_template('checkout_description.php', $template_fields, '', $this->template_path);
Loading history...
475
    }
476
477
    /***********
478
     *
479
     * UTILS FUNCTIONS
480
     *
481
     ***********/
482
483
    /**
484
     * PANEL KO_URL FIELD
485
     * CHECKOUT PAGE => ?page_id=91 // ORDER-CONFIRMATION PAGE => ?page_id=91&order-pay=<order_id>&key=<order_key>
486
     */
487
    private function generateOkUrl()
488
    {
489
        return $this->generateUrl($this->get_return_url());
490
    }
491
492
    /**
493
     * PANEL OK_URL FIELD
494
     */
495
    private function generateKoUrl()
496
    {
497
        return $this->generateUrl(get_permalink(wc_get_page_id('checkout')));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

497
        return $this->generateUrl(get_permalink(/** @scrutinizer ignore-call */ wc_get_page_id('checkout')));
Loading history...
Bug introduced by
The function get_permalink was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

803
            /** @scrutinizer ignore-call */ dbDelta($sql);
Loading history...
804
        }
805
        return;
806
    }
807
}
808