Completed
Push — master ( 4417de...be9c8e )
by
unknown
15s queued 11s
created

WcPagantisGateway   F

Complexity

Total Complexity 92

Size/Duplication

Total Lines 744
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 385
dl 0
loc 744
rs 2
c 0
b 0
f 0
wmc 92

26 Methods

Rating   Name   Duplication   Size   Complexity  
A getKeysParametersUrl() 0 10 2
A is_available() 0 11 6
A getOkUrl() 0 3 1
A generateOkUrl() 0 3 1
A admin_options() 0 11 1
A process_payment() 0 18 3
A getNationalId() 0 10 3
A checkDbTable() 0 12 2
A getKeysPathUrl() 0 11 3
A generateKoUrl() 0 3 1
A generateUrl() 0 16 5
A getTaxId() 0 6 3
F pagantisReceiptPage() 0 177 12
A unparseUrl() 0 9 6
A __construct() 0 34 4
A pagantisNotification() 0 30 5
A loadPagantisTranslation() 0 6 2
A pagantisCompleteStatus() 0 11 5
A getExtraConfig() 0 11 2
A insertRow() 0 22 2
A getOrders() 0 36 5
A get_title() 0 3 1
A getKeysUrl() 0 18 3
C pagantisCheckFields() 0 29 12
A getKoUrl() 0 3 1
A payment_fields() 0 18 1

How to fix   Complexity   

Complex Class

Complex classes like WcPagantisGateway often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WcPagantisGateway, and based on these observations, apply Extract Interface, too.

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

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

filter:
    dependency_paths: ["lib/*"]

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

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

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

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

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

49
        $this->icon = /** @scrutinizer ignore-call */ esc_url(plugins_url('../assets/images/logo.png', __FILE__));
Loading history...
50
        $this->has_fields = true;
0 ignored issues
show
Bug Best Practice introduced by
The property has_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
51
        $this->method_title = ucfirst($this->id);
0 ignored issues
show
Bug Best Practice introduced by
The property method_title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
52
        $this->title = $this->extraConfig['PAGANTIS_TITLE'];
0 ignored issues
show
Bug Best Practice introduced by
The property title does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
53
54
        //Useful vars
55
        $this->template_path = plugin_dir_path(__FILE__) . '../templates/';
0 ignored issues
show
Bug Best Practice introduced by
The property template_path does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
The function plugin_dir_path was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

58
        $this->plugin_info = /** @scrutinizer ignore-call */ get_file_data($this->mainFileLocation, array('Version' => 'Version'), false);
Loading history...
Bug Best Practice introduced by
The property plugin_info does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
59
60
        //Panel form fields
61
        $this->form_fields = include(plugin_dir_path(__FILE__).'../includes/settings-pagantis.php');//Panel options
0 ignored issues
show
Bug Best Practice introduced by
The property form_fields does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
62
        $this->init_settings();
63
64
        $this->extraConfig = $this->getExtraConfig();
65
66
        $this->settings['ok_url'] = ($this->extraConfig['PAGANTIS_URL_OK']!='')?$this->extraConfig['PAGANTIS_URL_OK']:$this->generateOkUrl();
0 ignored issues
show
Bug Best Practice introduced by
The property settings does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
67
        $this->settings['ko_url'] = ($this->extraConfig['PAGANTIS_URL_KO']!='')?$this->extraConfig['PAGANTIS_URL_KO']:$this->generateKoUrl();
68
        foreach ($this->settings as $setting_key => $setting_value) {
69
            $this->$setting_key = $setting_value;
70
        }
71
72
        //Hooks
73
        add_action('woocommerce_update_options_payment_gateways_'.$this->id, array($this,'process_admin_options')); //Save plugin options
0 ignored issues
show
Bug introduced by
The function add_action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

90
            $mofile = WP_LANG_DIR . '/../plugins/pagantis/languages/pagantis-' . /** @scrutinizer ignore-call */ get_locale() . '.mo';
Loading history...
91
        }
92
        return $mofile;
93
    }
94
95
    /***********
96
     *
97
     * HOOKS
98
     *
99
     ***********/
100
101
    /**
102
     * PANEL - Display admin panel -> Hook: woocommerce_update_options_payment_gateways_pagantis
103
     */
104
    public function admin_options()
105
    {
106
        $template_fields = array(
107
            'panel_header' => $this->title,
108
            'panel_description' => $this->method_description,
109
            'button1_label' => __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

109
            'button1_label' => /** @scrutinizer ignore-call */ __('Login to panel of ', 'pagantis') . ucfirst(WcPagantisGateway::METHOD_ID),
Loading history...
110
            'button2_label' => __('Documentation', 'pagantis'),
111
            'logo' => $this->icon,
112
            'settings' => $this->generate_settings_html($this->form_fields, false)
113
        );
114
        wc_get_template('admin_header.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
165
            $order->set_payment_method(ucfirst($this->id)); //Method showed in confirmation page.
166
            $order->save();
167
168
            if (!isset($order)) {
169
                throw new Exception(_("Order not found"));
170
            }
171
172
            $shippingAddress = $order->get_address('shipping');
173
            $billingAddress = $order->get_address('billing');
174
            if ($shippingAddress['address_1'] == '') {
175
                $shippingAddress = $billingAddress;
176
            }
177
178
            $national_id = $this->getNationalId($order);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $national_id is correct as $this->getNationalId($order) targeting WcPagantisGateway::getNationalId() seems to always return null.

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

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

}

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

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

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

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

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

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

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

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

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

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

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

270
            $callback_url = /** @scrutinizer ignore-call */ add_query_arg($callback_arg, home_url('/'));
Loading history...
271
            $orderConfigurationUrls
272
                ->setCancel($cancelUrl)
273
                ->setKo($callback_url)
274
                ->setAuthorizedNotificationCallback($callback_url)
275
                ->setRejectedNotificationCallback($callback_url)
276
                ->setOk($callback_url)
277
            ;
278
            $orderChannel = new Channel();
279
            $orderChannel
280
                ->setAssistedSale(false)
281
                ->setType(Channel::ONLINE)
282
            ;
283
            $orderConfiguration = new Configuration();
284
            $language = strstr(get_locale(), '_', true);
0 ignored issues
show
Bug introduced by
The function get_locale was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

284
            $language = strstr(/** @scrutinizer ignore-call */ get_locale(), '_', true);
Loading history...
285
            $orderConfiguration
286
                ->setChannel($orderChannel)
287
                ->setUrls($orderConfigurationUrls)
288
                ->setPurchaseCountry($language)
289
            ;
290
            $metadataOrder = new Metadata();
291
            $metadata = array(
292
                'woocommerce' => WC()->version,
0 ignored issues
show
Bug introduced by
The function WC was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

292
                'woocommerce' => /** @scrutinizer ignore-call */ WC()->version,
Loading history...
293
                'pagantis'         => $this->plugin_info['Version'],
294
                'php'         => phpversion()
295
            );
296
            foreach ($metadata as $key => $metadatum) {
297
                $metadataOrder->addMetadata($key, $metadatum);
298
            }
299
            $orderApiClient = new Order();
300
            $orderApiClient
301
                ->setConfiguration($orderConfiguration)
302
                ->setMetadata($metadataOrder)
303
                ->setShoppingCart($orderShoppingCart)
304
                ->setUser($orderUser)
305
            ;
306
307
            if ($this->pagantis_public_key=='' || $this->pagantis_private_key=='') {
308
                throw new \Exception('Public and Secret Key not found');
309
            }
310
            $orderClient = new Client($this->pagantis_public_key, $this->pagantis_private_key);
311
            $pagantisOrder = $orderClient->createOrder($orderApiClient);
312
            if ($pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
313
                $url = $pagantisOrder->getActionUrls()->getForm();
314
                $this->insertRow($order->get_id(), $pagantisOrder->getId());
315
            } else {
316
                throw new OrderNotFoundException();
317
            }
318
319
            if ($url=="") {
320
                throw new Exception(_("No ha sido posible obtener una respuesta de Pagantis"));
321
            } elseif ($this->extraConfig['PAGANTIS_FORM_DISPLAY_TYPE']=='0') {
322
                wp_redirect($url);
0 ignored issues
show
Bug introduced by
The function wp_redirect was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

322
                /** @scrutinizer ignore-call */ wp_redirect($url);
Loading history...
323
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
324
            } else {
325
                $template_fields = array(
326
                    'url' => $url,
327
                    'checkoutUrl'   => $cancelUrl
328
                );
329
                wc_get_template('iframe.php', $template_fields, '', $this->template_path);
0 ignored issues
show
Bug introduced by
The function wc_get_template was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

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

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

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

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

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

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

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

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

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

448
            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

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

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

464
            'total' => /** @scrutinizer ignore-call */ WC()->session->cart_totals['total'],
Loading history...
465
            'enabled' =>  $this->settings['enabled'],
466
            'min_installments' => $this->extraConfig['PAGANTIS_DISPLAY_MIN_AMOUNT'],
467
            'message' => __($this->extraConfig['PAGANTIS_TITLE_EXTRA']),
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

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

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

496
        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

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

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

721
            /** @scrutinizer ignore-call */ 
722
            dbDelta($sql);
Loading history...
722
        }
723
    }
724
725
    /**
726
     * @return array
727
     */
728
    private function getExtraConfig()
729
    {
730
        global $wpdb;
731
        $tableName = $wpdb->prefix.self::CONFIG_TABLE;
732
        $response = array();
733
        $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...
734
        foreach ($dbResult as $value) {
735
            $response[$value['config']] = $value['value'];
736
        }
737
738
        return $response;
739
    }
740
741
    /**
742
     * @param $order
743
     *
744
     * @return null
745
     */
746
    private function getNationalId($order)
747
    {
748
        foreach ((array)$order->get_meta_data() as $mdObject) {
749
            $data = $mdObject->get_data();
750
            if ($data['key'] == 'vat_number') {
751
                return $data['value'];
752
            }
753
        }
754
755
        return null;
756
    }
757
758
    /**
759
     * @param $order
760
     *
761
     * @return mixed
762
     */
763
    private function getTaxId($order)
764
    {
765
        foreach ((array)$order->get_meta_data() as $mdObject) {
766
            $data = $mdObject->get_data();
767
            if ($data['key'] == 'billing_cfpiva') {
768
                return $data['value'];
769
            }
770
        }
771
    }
772
}
773