Completed
Push — master ( 026455...55c688 )
by
unknown
13s
created

WcPagantisGateway::__construct()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 40
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 16
nop 0
dl 0
loc 40
rs 8.8817
c 0
b 0
f 0
1
<?php
2
3
//namespace empty
4
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
5
use Pagantis\OrdersApiClient\Model\Order\User\Address;
6
use Pagantis\OrdersApiClient\Model\Order\User;
7
use Pagantis\OrdersApiClient\Model\Order\User\OrderHistory;
8
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details;
9
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart;
10
use Pagantis\OrdersApiClient\Model\Order\ShoppingCart\Details\Product;
11
use Pagantis\OrdersApiClient\Model\Order\Metadata;
12
use Pagantis\OrdersApiClient\Model\Order\Configuration\Urls;
13
use Pagantis\OrdersApiClient\Model\Order\Configuration\Channel;
14
use Pagantis\OrdersApiClient\Model\Order\Configuration;
15
use Pagantis\OrdersApiClient\Client;
16
use Pagantis\OrdersApiClient\Model\Order;
17
18
if (!defined('ABSPATH')) {
19
    exit;
20
}
21
22
define('__ROOT__', dirname(dirname(__FILE__)));
23
24
25
class WcPagantisGateway extends WC_Payment_Gateway
0 ignored issues
show
Bug introduced by
The type WC_Payment_Gateway was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
26
{
27
    const METHOD_ID = "pagantis";
28
29
    /** Orders tablename */
30
    const ORDERS_TABLE = 'cart_process';
31
32
    /** Concurrency tablename */
33
    const LOGS_TABLE = 'pagantis_logs';
34
35
    const NOT_CONFIRMED = 'No se ha podido confirmar el pago';
36
37
    const CONFIG_TABLE = 'pagantis_config';
38
39
    /** @var Array $extraConfig */
40
    public $extraConfig;
41
42
    /** @var string $language */
43
    public $language;
44
45
    /**
46
     * WcPagantisGateway constructor.
47
     */
48
    public function __construct()
49
    {
50
        //Mandatory vars for plugin
51
        $this->id = WcPagantisGateway::METHOD_ID;
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
52
        $this->has_fields = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
54
55
        //Useful vars
56
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

56
        $this->template_path = /** @scrutinizer ignore-call */ plugin_dir_path(__FILE__) . '../templates/';
Loading history...
57
        $this->allowed_currencies = array("EUR");
0 ignored issues
show
Bug Best Practice introduced by
The property allowed_currencies does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
58
        $this->mainFileLocation = dirname(plugin_dir_path(__FILE__)) . '/WC_Pagantis.php';
0 ignored issues
show
Bug Best Practice introduced by
The property mainFileLocation does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
59
        $this->plugin_info = get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
0 ignored issues
show
Bug introduced by
The function get_file_data was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

59
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
60
        $this->language = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

63
            $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logopagamastarde.png', __FILE__));
Loading history...
Bug Best Practice introduced by
The property icon does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
64
        } else {
65
            $this->icon = esc_url(plugins_url('../assets/images/logo.png', __FILE__));
66
        }
67
68
        //Panel form fields
69
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
        $this->init_settings();
71
72
        $this->extraConfig = $this->getExtraConfig();
73
        $this->title = __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

73
        $this->title = /** @scrutinizer ignore-call */ __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
74
75
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
76
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
77
        foreach ($this->settings as $setting_key => $setting_value) {
78
            $this->$setting_key = $setting_value;
79
        }
80
81
        //Hooks
82
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

82
        /** @scrutinizer ignore-call */ add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
Loading history...
83
        add_action('admin_notices', array($this, 'pagantisCheckFields'));                          //Check config fields
84
        add_action('woocommerce_receipt_'.$this->id, array($this, 'pagantisReceiptPage'));          //Pagantis form
85
        add_action('woocommerce_api_wcpagantisgateway', array($this, 'pagantisNotification'));      //Json Notification
86
        add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
0 ignored issues
show
Bug introduced by
The function add_filter was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

86
        /** @scrutinizer ignore-call */ add_filter('woocommerce_payment_complete_order_status', array($this,'pagantisCompleteStatus'), 10, 3);
Loading history...
87
        add_filter('load_textdomain_mofile', array($this, 'loadPagantisTranslation'), 10, 2);
88
    }
89
90
    /**
91
     * @param $mofile
92
     * @param $domain
93
     *
94
     * @return string
95
     */
96
    public function loadPagantisTranslation($mofile, $domain)
97
    {
98
        if ('pagantis' === $domain) {
99
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . get_locale() . '.mo';
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

99
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
Bug introduced by
The constant WP_LANG_DIR was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
100
        }
101
        return $mofile;
102
    }
103
104
    /***********
105
     *
106
     * HOOKS
107
     *
108
     ***********/
109
110
    /**
111
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
112
     */
113
    public function admin_options()
114
    {
115
        $template_fields = array(
116
            'panel_description' => $this->method_description,
117
            'button1_label' => __('Login to your panel', 'pagantis'),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

117
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to your panel', 'pagantis'),
Loading history...
118
            'button2_label' => __('Documentation', 'pagantis'),
119
            'logo' => $this->icon,
120
            'settings' => $this->generate_settings_html($this->form_fields, false)
121
        );
122
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

122
        /** @scrutinizer ignore-call */ wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
Loading history...
123
    }
124
125
    /**
126
     * PANEL - Check admin panel fields -> Hook: admin_notices
127
     */
128
    public function pagantisCheckFields()
129
    {
130
        $error_string = '';
131
        if ($this->settings['enabled'] !== 'yes') {
132
            return;
133
        } elseif (!version_compare(phpversion(), '5.3.0', '>=')) {
134
            $error_string =  __(' is not compatible with your php and/or curl version', 'pagantis');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

134
            $error_string =  /** @scrutinizer ignore-call */ __(' is not compatible with your php and/or curl version', 'pagantis');
Loading history...
135
            $this->settings['enabled'] = 'no';
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
136
        } elseif ($this->settings['pagantis_public_key']=="" || $this->settings['pagantis_private_key']=="") {
137
            $error_string = __(' is not configured correctly, the fields Public Key and Secret Key are mandatory for use this plugin', 'pagantis');
138
            $this->settings['enabled'] = 'no';
139
        } elseif (!in_array(get_woocommerce_currency(), $this->allowed_currencies)) {
0 ignored issues
show
Bug introduced by
The function get_woocommerce_currency was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

139
        } elseif (!in_array(/** @scrutinizer ignore-call */ get_woocommerce_currency(), $this->allowed_currencies)) {
Loading history...
140
            $error_string =  __(' only can be used in Euros', 'pagantis');
141
            $this->settings['enabled'] = 'no';
142
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']<'2'
143
                  || $this->extraConfig['PAGANTIS_SIMULATOR_MAX_INSTALLMENTS']>'12') {
144
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
145
        } elseif ($this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']<'2'
146
                  || $this->extraConfig['PAGANTIS_SIMULATOR_START_INSTALLMENTS']>'12') {
147
            $error_string = __(' only can be payed from 2 to 12 installments', 'pagantis');
148
        } elseif ($this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT']<0) {
149
            $error_string = __(' can not have a minimum amount less than 0', 'pagantis');
150
        }
151
152
        if ($error_string!='') {
153
            $template_fields = array(
154
                'error_msg' => ucfirst(WcPagantisGateway::METHOD_ID).' '.$error_string,
155
            );
156
            wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

156
            /** @scrutinizer ignore-call */ wc_get_template('error_msg.php', $template_fields, '', $this->template_path);
Loading history...
157
        }
158
    }
159
160
161
    /**
162
     * CHECKOUT - Generate the pagantis form. "Return" iframe or redirect. - Hook: woocommerce_receipt_pagantis
163
     * @param $order_id
164
     *
165
     * @throws Exception
166
     */
167
    public function pagantisReceiptPage($order_id)
168
    {
169
        try {
170
            require_once(__ROOT__.'/vendor/autoload.php');
171
            global $woocommerce;
172
            $order = new WC_Order($order_id);
0 ignored issues
show
Bug introduced by
The type WC_Order was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
173
            $order->set_payment_method(ucfirst($this->id));
174
            $order->save();
175
176
            if (!isset($order)) {
177
                throw new Exception(_("Order not found"));
178
            }
179
180
            $shippingAddress = $order->get_address('shipping');
181
            $billingAddress = $order->get_address('billing');
182
            if ($shippingAddress['address_1'] == '') {
183
                $shippingAddress = $billingAddress;
184
            }
185
186
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WcPagantisGateway::getNationalId() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
187
            $tax_id = $this->getTaxId($order);
188
189
            $userAddress = new Address();
190
            $userAddress
191
                ->setZipCode($shippingAddress['postcode'])
192
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
193
                ->setCountryCode('ES')
194
                ->setCity($shippingAddress['city'])
195
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
196
            ;
197
            $orderShippingAddress = new Address();
198
            $orderShippingAddress
199
                ->setZipCode($shippingAddress['postcode'])
200
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
201
                ->setCountryCode('ES')
202
                ->setCity($shippingAddress['city'])
203
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
204
                ->setFixPhone($shippingAddress['phone'])
205
                ->setMobilePhone($shippingAddress['phone'])
206
                ->setNationalId($national_id)
207
                ->setTaxId($tax_id)
208
            ;
209
            $orderBillingAddress =  new Address();
210
            $orderBillingAddress
211
                ->setZipCode($billingAddress['postcode'])
212
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
213
                ->setCountryCode('ES')
214
                ->setCity($billingAddress['city'])
215
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
216
                ->setFixPhone($billingAddress['phone'])
217
                ->setMobilePhone($billingAddress['phone'])
218
                ->setNationalId($national_id)
219
                ->setTaxId($tax_id)
220
            ;
221
            $orderUser = new User();
222
            $orderUser
223
                ->setAddress($userAddress)
224
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
225
                ->setBillingAddress($orderBillingAddress)
226
                ->setEmail($billingAddress['email'])
227
                ->setFixPhone($billingAddress['phone'])
228
                ->setMobilePhone($billingAddress['phone'])
229
                ->setShippingAddress($orderShippingAddress)
230
                ->setNationalId($national_id)
231
                ->setTaxId($tax_id)
232
            ;
233
234
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
235
            foreach ($previousOrders as $previousOrder) {
236
                $orderHistory = new OrderHistory();
237
                $orderElement = wc_get_order($previousOrder);
0 ignored issues
show
Bug introduced by
The function wc_get_order was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

237
                $orderElement = /** @scrutinizer ignore-call */ wc_get_order($previousOrder);
Loading history...
238
                $orderCreated = $orderElement->get_date_created();
239
                $orderHistory
240
                    ->setAmount(intval(100 * $orderElement->get_total()))
241
                    ->setDate(new \DateTime($orderCreated->date('Y-m-d H:i:s')))
0 ignored issues
show
Bug introduced by
new DateTime($orderCreated->date('Y-m-d H:i:s')) of type DateTime is incompatible with the type string expected by parameter $date of Pagantis\OrdersApiClient...OrderHistory::setDate(). ( Ignorable by Annotation )

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

241
                    ->setDate(/** @scrutinizer ignore-type */ new \DateTime($orderCreated->date('Y-m-d H:i:s')))
Loading history...
242
                ;
243
                $orderUser->addOrderHistory($orderHistory);
244
            }
245
246
            $details = new Details();
247
            $shippingCost = $order->shipping_total;
248
            $details->setShippingCost(intval(strval(100 * $shippingCost)));
249
            $items = $woocommerce->cart->get_cart();
250
            foreach ($items as $key => $item) {
251
                $product = new Product();
252
                $productDescription = sprintf(
253
                    '%s %s %s',
254
                    $item['data']->get_title(),
255
                    $item['data']->get_description(),
256
                    $item['data']->get_short_description()
257
                );
258
                $product
259
                    ->setAmount(intval(100 * $item['line_total']))
260
                    ->setQuantity($item['quantity'])
261
                    ->setDescription($productDescription);
262
                $details->addProduct($product);
263
            }
264
265
            $orderShoppingCart = new ShoppingCart();
266
            $orderShoppingCart
267
                ->setDetails($details)
268
                ->setOrderReference($order->get_id())
269
                ->setPromotedAmount(0)
270
                ->setTotalAmount(intval(strval(100 * $order->total)))
271
            ;
272
            $orderConfigurationUrls = new Urls();
273
            $cancelUrl = $this->getKoUrl($order);
274
            $callback_arg = array(
275
                'wc-api'=>'wcpagantisgateway',
276
                'key'=>$order->get_order_key(),
277
                'order-received'=>$order->get_id());
278
            $callback_url = add_query_arg($callback_arg, home_url('/'));
0 ignored issues
show
Bug introduced by
The function add_query_arg was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

278
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
Bug introduced by
The function home_url was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

340
            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

340
            /** @scrutinizer ignore-call */ wc_add_notice(__('Payment error ', 'pagantis') . $exception->getMessage(), 'error');
Loading history...
341
            $this->insertLog($exception);
342
            $checkout_url = get_permalink(wc_get_page_id('checkout'));
0 ignored issues
show
Bug introduced by
The function wc_get_page_id was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

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

433
        return /** @scrutinizer ignore-call */ 
434
               __($this->extraConfig['PAGANTIS_TITLE'], 'pagantis');
Loading history...
434
    }
435
436
    /**
437
     * CHECKOUT - Called after push pagantis button on checkout(called by woocommerce, can't apply cammel caps
438
     * @param $order_id
439
     * @return array
440
     */
441
    public function process_payment($order_id)
442
    {
443
        try {
444
            $order = new WC_Order($order_id);
445
446
            $redirectUrl = $order->get_checkout_payment_url(true); //pagantisReceiptPage function
447
            if (strpos($redirectUrl, 'order-pay=')===false) {
448
                $redirectUrl.="&order-pay=".$order_id;
449
            }
450
451
            return array(
452
                'result'   => 'success',
453
                'redirect' => $redirectUrl
454
            );
455
456
        } catch (Exception $e) {
457
            wc_add_notice(__('Payment error ', 'pagantis') . $e->getMessage(), 'error');
0 ignored issues
show
Bug introduced by
The function wc_add_notice was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

457
            wc_add_notice(/** @scrutinizer ignore-call */ __('Payment error ', 'pagantis') . $e->getMessage(), 'error');
Loading history...
458
            return array();
459
        }
460
    }
461
462
    /**
463
     * CHECKOUT - simulator (called by woocommerce, can't apply cammel caps)
464
     */
465
    public function payment_fields()
466
    {
467
        $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

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

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

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

504
        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

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

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

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

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