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

WcPagantisGateway::generateUrl()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
c 0
b 0
f 0
nc 7
nop 1
dl 0
loc 16
rs 9.5555
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
174
            if (!isset($order)) {
175
                throw new Exception(_("Order not found"));
176
            }
177
178
            $shippingAddress = $order->get_address('shipping');
179
            $billingAddress = $order->get_address('billing');
180
            if ($shippingAddress['address_1'] == '') {
181
                $shippingAddress = $billingAddress;
182
            }
183
184
            $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...
185
            $tax_id = $this->getTaxId($order);
186
187
            $userAddress = new Address();
188
            $userAddress
189
                ->setZipCode($shippingAddress['postcode'])
190
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
191
                ->setCountryCode('ES')
192
                ->setCity($shippingAddress['city'])
193
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
194
            ;
195
            $orderShippingAddress = new Address();
196
            $orderShippingAddress
197
                ->setZipCode($shippingAddress['postcode'])
198
                ->setFullName($shippingAddress['first_name']." ".$shippingAddress['last_name'])
199
                ->setCountryCode('ES')
200
                ->setCity($shippingAddress['city'])
201
                ->setAddress($shippingAddress['address_1']." ".$shippingAddress['address_2'])
202
                ->setFixPhone($shippingAddress['phone'])
203
                ->setMobilePhone($shippingAddress['phone'])
204
                ->setNationalId($national_id)
205
                ->setTaxId($tax_id)
206
            ;
207
            $orderBillingAddress =  new Address();
208
            $orderBillingAddress
209
                ->setZipCode($billingAddress['postcode'])
210
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
211
                ->setCountryCode('ES')
212
                ->setCity($billingAddress['city'])
213
                ->setAddress($billingAddress['address_1']." ".$billingAddress['address_2'])
214
                ->setFixPhone($billingAddress['phone'])
215
                ->setMobilePhone($billingAddress['phone'])
216
                ->setNationalId($national_id)
217
                ->setTaxId($tax_id)
218
            ;
219
            $orderUser = new User();
220
            $orderUser
221
                ->setAddress($userAddress)
222
                ->setFullName($billingAddress['first_name']." ".$billingAddress['last_name'])
223
                ->setBillingAddress($orderBillingAddress)
224
                ->setEmail($billingAddress['email'])
225
                ->setFixPhone($billingAddress['phone'])
226
                ->setMobilePhone($billingAddress['phone'])
227
                ->setShippingAddress($orderShippingAddress)
228
                ->setNationalId($national_id)
229
                ->setTaxId($tax_id)
230
            ;
231
232
            $previousOrders = $this->getOrders($order->get_user(), $billingAddress['email']);
233
            foreach ($previousOrders as $previousOrder) {
234
                $orderHistory = new OrderHistory();
235
                $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

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

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

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

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

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

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

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

338
            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

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

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

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

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

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

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

455
            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

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

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

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

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

502
        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

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

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

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

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