Completed
Push — master ( f77a5b...d9795d )
by
unknown
12:33
created

wpshop_orders   D

Complexity

Total Complexity 160

Size/Duplication

Total Lines 653
Duplicated Lines 20.83 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 136
loc 653
rs 4.6538
c 0
b 0
f 0
wmc 160
lcom 1
cbo 6

17 Methods

Rating   Name   Duplication   Size   Complexity  
B create_orders_type() 34 35 1
B add_meta_boxes() 3 27 2
F order_actions() 0 100 31
A order_container_in_admin() 0 8 1
A order_content() 0 18 3
A order_generate_billing_number() 0 18 4
A get_new_order_reference() 17 17 3
A get_new_pre_order_reference() 19 19 4
B set_order_customer_addresses() 0 25 6
A orders_edit_columns() 0 16 1
D orders_custom_columns() 12 110 46
C list_table_filters() 0 23 8
F list_table_filter_parse_query() 51 102 28
C latest_products_ordered() 0 37 15
A get_order_list_for_customer() 0 19 3
A display_customer_pay_quotation() 0 8 3
A display_customer_pay_order() 0 14 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like wpshop_orders 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 wpshop_orders, and based on these observations, apply Extract Interface, too.

1
<?php if (!defined('ABSPATH')) {
2
    exit;
3
}
4
5
/**
6
 * Products management method file
7
 *
8
 * This file contains the different methods for products management
9
 * @author Eoxia <[email protected]>
10
 * @version 1.1
11
 * @package wpshop
12
 * @subpackage librairies
13
 */
14
15
/*    Check if file is include. No direct access possible with file url    */
16
if (!defined('WPSHOP_VERSION')) {
17
    die(__('Access is not allowed by this way', 'wpshop'));
18
}
19
20
/**
21
 * This file contains the different methods for products management
22
 * @author Eoxia <[email protected]>
23
 * @version 1.1
24
 * @package wpshop
25
 * @subpackage librairies
26
 */
27
class wpshop_orders
28
{
29
30
    /**
31
     * Create a new custom post type in wordpress for current element
32
     */
33 View Code Duplication
    public static function create_orders_type()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
34
    {
35
        register_post_type(WPSHOP_NEWTYPE_IDENTIFIER_ORDER, array(
36
            'labels' => array(
37
                'name' => __('Orders', 'wpshop'),
38
                'singular_name' => __('Order', 'wpshop'),
39
                'add_new' => __('Add quotation', 'wpshop'),
40
                'add_new_item' => __('Add new quotation', 'wpshop'),
41
                'edit' => __('Edit', 'wpshop'),
42
                'edit_item' => __('Edit Order', 'wpshop'),
43
                'new_item' => __('New quotation', 'wpshop'),
44
                'view' => __('View Order', 'wpshop'),
45
                'view_item' => __('View Order', 'wpshop'),
46
                'search_items' => __('Search Orders', 'wpshop'),
47
                'not_found' => __('No Orders found', 'wpshop'),
48
                'not_found_in_trash' => __('No Orders found in trash', 'wpshop'),
49
                'parent' => __('Parent Orders', 'wpshop'),
50
            ),
51
            'description' => __('This is where store orders are stored.', 'wpshop'),
52
            'public' => true,
53
            'show_ui' => true,
54
            'capability_type' => 'post',
55
            'publicly_queryable' => false,
56
            'exclude_from_search' => true,
57
            'show_in_menu' => true,
58
            'hierarchical' => false,
59
            'show_in_nav_menus' => false,
60
            'show_in_admin_bar' => false,
61
            'rewrite' => false,
62
            'query_var' => true,
63
            'supports' => array(''),
64
            'has_archive' => false,
65
            'menu_icon' => 'dashicons-cart',
66
        ));
67
    }
68
69
    /**
70
     *    Call the different boxes in edition page
71
     */
72
    public static function add_meta_boxes()
73
    {
74
        global $post;
75
76
        /**    Add action button    */
77
        add_meta_box(
78
            'wpshop_order_actions',
79
            '<span class="dashicons dashicons-info"></span> ' . __('Actions on order', 'wpshop'),
80
            array('wpshop_orders', 'order_actions'),
81
            WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'high'
82
        );
83
84 View Code Duplication
        if (!in_array($post->post_status, array('auto-draft'))) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
            add_meta_box('wpshop_credit_actions', __('Credit on order', 'wpshop'), array('wps_credit', 'wps_credit_meta_box'), WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'low');
86
        }
87
88
        /**    Box    containing listing of customer notification */
89
//         $notifs = self::get_notification_by_object( array('object_type' => 'order', 'object_id' => $post->ID) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
57% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
90
        //         if ( !empty($notifs) ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
91
        //             add_meta_box(
92
        //                 'wpshop_order_customer_notification',
93
        //                 __('Customer Notification', 'wpshop'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
94
        //                 array('wpshop_orders', 'wpshop_order_customer_notification'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
78% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
95
        //                     WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'side', 'low'
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
96
        //             );
97
        //         }
98
    }
99
100
    /**
101
     * Define the box for actions on order
102
     *
103
     * @param object $order The current order being edited
104
     */
105
    public static function order_actions($order)
106
    {
107
        $output = '';
0 ignored issues
show
Unused Code introduced by
$output is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
108
109
        $order_status = unserialize(WPSHOP_ORDER_STATUS);
110
        $order_postmeta = get_post_meta($order->ID, '_order_postmeta', true);
111
112
        $tpl_component = array();
113
114
        $delete_button = wpshop_display::display_template_element('wpshop_admin_order_action_del_button', array('ADMIN_ORDER_DELETE_LINK' => esc_url(get_delete_post_link($order->ID)), 'ADMIN_ORDER_DELETE_TEXT' => (!EMPTY_TRASH_DAYS ? __('Delete Permanently', 'wpshop') : __('Move to Trash', 'wpshop'))), array(), 'admin');
115
        $tpl_component['ADMIN_ORDER_DELETE_ORDER'] = current_user_can("delete_post", $order->ID) ? $delete_button : '';
116
117
        /**    Add an action list    */
118
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] = '';
119
120
        /**    Display main information about the order    */
121
        $order_main_info = '';
122
        if (!empty($order_postmeta['order_date'])) {
123
            $order_main_info .= '<div class="wps-product-section"><span class="dashicons dashicons-calendar-alt"></span> <strong>' . __('Order date', 'wpshop') . ' : </strong><br/>' . mysql2date('d F Y H:i:s', $order_postmeta['order_date'], true) . '</div>';
124
        }
125
        $order_main_info .= '<div class="wps-product-section">';
126
        if (empty($order_postmeta['order_date']) || (empty($order_postmeta['order_key']) && empty($order_postmeta['order_temporary_key']) && empty($order_postmeta['order_invoice_ref']))) {
127
            $order_main_info .= '<span class="dashicons dashicons-arrow-right"></span> <strong>' . __('Temporary quotation reference', 'wpshop') . ': </strong>' . self::get_new_pre_order_reference(false) . '<br/>';
128
        } else {
129
            if (!empty($order_postmeta['order_key'])) {
130
                $order_main_info .= '<span class="dashicons dashicons-arrow-right"></span> <strong>' . __('Order reference', 'wpshop') . ' : </strong>' . $order_postmeta['order_key'] . '<br/>';
131
            }
132
            if (!empty($order_postmeta['order_temporary_key'])) {
133
                $order_main_info .= '<span class="dashicons dashicons-arrow-right"></span> <strong>' . __('Pre-order reference', 'wpshop') . ': </strong>' . $order_postmeta['order_temporary_key'] . '<br/>';
134
                $post_ID = !empty($_GET['post']) ? (int) $_GET['post'] : 0;
135
                $order_main_info .= '<a href="' . admin_url('admin-post.php?action=wps_invoice&order_id=' . $post_ID . '&mode=pdf') . '">' . __('Download the quotation', 'wpshop') . '</a><br />';
136
            }
137
            if (!empty($order_postmeta['order_invoice_ref'])) {
138
                $sub_tpl_component = array();
0 ignored issues
show
Unused Code introduced by
$sub_tpl_component is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
139
                $order_invoice_download = '<a href="' . admin_url('admin-post.php?action=wps_invoice&order_id=' . $order->ID . '&invoice_ref=' . $order_postmeta['order_invoice_ref'] . '&mode=pdf') . '">' . __('Download invoice', 'wpshop') . '</a><br />';
140
                $order_main_info .= '<span class="dashicons dashicons-arrow-right"></span> <strong>' . __('Invoice number', 'wpshop') . ': </strong>' . $order_postmeta['order_invoice_ref'] . '<br/>' . $order_invoice_download . '';
141
            } else {
142
                $order_main_info .= wpshop_display::display_template_element('wpshop_admin_order_generate_invoice_button', array(), array(), 'admin');
143
            }
144
        }
145
        $order_main_info .= '</div>';
146
147
        /*Add the current order status in display**/
148
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= (!empty($order_postmeta['order_status'])) ? (sprintf('<span class="order_status_' . $order->ID . ' wpshop_order_status_container wpshop_order_status_%1$s ">%2$s</span>', sanitize_title(strtolower($order_postmeta['order_status'])), __($order_status[strtolower($order_postmeta['order_status'])], 'wpshop'))) : '';
149
150
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= $order_main_info;
151
152
        /**    Add a box allowing to notify the customer on order update    */
153
        /**
154
         *
155
         * To check because notification is not really send
156
         *
157
         */
158
        /*if ( !empty($order->post_author) ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
159
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '
160
        <div class="wps-product-section wpshop_order_notify_customer_on_update_container" >
161
        <input type="checkbox" name="notif_the_customer" id="wpshop_order_notif_the_customer_on_update" /> <label for="wpshop_order_notif_the_customer_on_update" >'.__('Send a notification to the customer', 'wpshop').'</label>
162
        <!-- <br/><input type="checkbox" name="notif_the_customer_sendsms" id="wpshop_order_notif_the_customer_sendsms_on_update" /> <label for="wpshop_order_nnotif_the_customer_sendsms_on_update" >'.__('Send a SMS to the customer', 'wpshop').'</label> -->
163
        </div>';
164
        }*/
165
166
        if (in_array($order_postmeta['order_status'], array('awaiting_payment', 'partially_paid')) && (float) $order_postmeta['order_amount_to_pay_now'] != (float) 0) {
167
            if (((!empty($order_postmeta['cart_type']) && $order_postmeta['cart_type'] == 'quotation') || !empty($order_postmeta['order_temporary_key']))) {
168
                $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section">' . self::display_customer_pay_quotation(isset($order_postmeta['pay_quotation']), $order->ID) . '</div>';
169
            } else {
170
                $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section">' . self::display_customer_pay_order($order->ID) . '</div>';
171
            }
172
        }
173
        /**
174
         * Only for quotations
175
         */
176
        /*if( ( ( !empty($order_postmeta['cart_type']) && $order_postmeta['cart_type'] == 'quotation' ) || !empty( $order_postmeta['order_temporary_key'] ) ) && $order_postmeta['order_status'] != 'canceled' && (float) $order_postmeta['order_amount_to_pay_now'] != (float) 0 ) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
177
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section"><input type="text" value="' . wpshop_checkout::wps_direct_payment_link_url( $order->ID ) . '"/></div>';
178
        }*/
179
180
        /*Add the button regarding the order status**/
181
        if (!empty($order_postmeta['order_status'])) {
182
            if ($order_postmeta['order_status'] == 'awaiting_payment') {
183
                $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section"><button class="wps-bton-second-mini-rounded markAsCanceled order_' . $order->ID . '" >' . __('Cancel this order', 'wpshop') . '</button><input type="hidden" id="markascanceled_order_hidden_indicator" name="markascanceled_order_hidden_indicator" /></div>';
184
            }
185
            $credit_meta = get_post_meta($order->ID, '_wps_order_credit', true);
186
187
            $total_received = (float) 0;
188
            if (!empty($order_postmeta['order_payment']) && !empty($order_postmeta['order_payment']['received'])) {
189
                foreach ($order_postmeta['order_payment']['received'] as $received) {
190
                    $total_received += (float) isset($received['received_amount']) ? $received['received_amount'] : 0;
191
                }
192
            }
193
194
            if (empty($credit_meta) && (float) 0 !== $total_received) {
195
                if ($order_postmeta['order_status'] == 'refunded') {
196
                    $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section wps_markAsRefunded_container">' . __('Credit Slip number', 'wpshop') . ' : <strong>' . ((!empty($order_postmeta) && !empty($order_postmeta['order_payment']) && !empty($order_postmeta['order_payment']['refunded_action']) && !empty($order_postmeta['order_payment']['refunded_action']['credit_slip_ref'])) ? '<a href="' . admin_url('admin-post.php?action=wps_invoice&order_id=' . $order->ID . '&amp;invoice_ref=' . $order_postmeta['order_payment']['refunded_action']['credit_slip_ref'] . '&credit_slip=ok') . '" target="_blank">' . $order_postmeta['order_payment']['refunded_action']['credit_slip_ref'] . '</a>' : '') . '</strong></div>';
197
                } else {
198
                    $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] .= '<div class="wps-product-section wps_markAsRefunded_container" ><button class="wps-bton-second-mini-rounded markAsRefunded order_' . $order->ID . '">' . __('Refund this order', 'wpshop') . '</button><input type="hidden" id="markasrefunded_order_hidden_indicator" name="markasrefunded_order_hidden_indicator" /></div>';
199
                }
200
            }
201
        }
202
        $tpl_component['ADMIN_ORDER_ACTIONS_LIST'] = strrev(preg_replace(strrev('/wps-product-section/'), '', strrev($tpl_component['ADMIN_ORDER_ACTIONS_LIST']), 1));
203
        echo wpshop_display::display_template_element('wpshop_admin_order_action_box', $tpl_component, array('type' => WPSHOP_NEWTYPE_IDENTIFIER_ORDER, 'id' => $order->ID), 'admin');
204
    }
205
206
    public function order_container_in_admin()
207
    {
208
        global $post;
209
        $output = '<div id="wps_order_content_container">';
210
        $output .= self::order_content($post);
211
        $output .= '</div>';
212
        echo $output;
213
    }
214
215
    /**
216
     * Display the order content: the list of element put into order
217
     *
218
     * @param order $post The complete order content
219
     */
220
    public function order_content($post)
221
    {
222
        $order_content = '';
223
224
        $order = get_post_meta($post->ID, '_order_postmeta', true);
225
226
        $order_content .= '<div id="order_product_container" class="order_product_container wpshop_cls" >';
227
        if ($order) {
228
/*    Read the order content if the order has product    */
229
            $order_content .= '<input type="hidden" value="" name="order_products_to_delete" id="order_products_to_delete" />' . wpshop_cart::display_cart(true, $order, 'admin');
230
            if (empty($order['order_invoice_ref'])) {
231
                $order_content .= '<div id="order_refresh_button_container" class="wpshop_clear_block" ><input type="button" class="button-primary alignright wpshopHide" id="wpshop_admin_order_recalculate" value="' . __('Refresh order informations', 'wpshop') . '" /></div>';
232
            }
233
        }
234
        $order_content .= '<div class="wpshop_cls" ></div></div>';
235
236
        return $order_content;
237
    }
238
239
    /** Generate the billing reference regarding the order $order_id
240
     * @return void
241
     */
242
    public function order_generate_billing_number($order_id, $force_invoicing = false)
243
    {
244
        global $wpdb, $wpshop_modules_billing;
245
246
        // Get the order from the db
247
        $order = get_post_meta($order_id, '_order_postmeta', true);
248
249
        // If the payment is completed
250
        if (($order['order_status'] == 'completed') || $force_invoicing) {
251
252
            // If the reference hasn't been generated yet
253
            if (empty($order['order_invoice_ref'])) {
254
                $order['order_invoice_ref'] = $wpshop_modules_billing->generate_invoice_number($order_id);
255
256
                update_post_meta($order_id, '_order_postmeta', $order);
257
            }
258
        }
259
    }
260
261
    /** Renvoi une nouvelle r�f�rence unique pour une commande
262
     * @return int
263
     */
264 View Code Duplication
    public static function get_new_order_reference()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
265
    {
266
        $number_figures = get_option('wpshop_order_number_figures', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
267
        /* If the number doesn't exist, we create a default one */
268
        if (!$number_figures) {
269
            $number_figures = 5;
270
            update_option('wpshop_order_number_figures', $number_figures);
271
        }
272
273
        $order_current_number = get_option('wpshop_order_current_number', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
274
        /* If the counter doesn't exist, we initiate it */
275
        if (!$order_current_number) {$order_current_number = 1;} else { $order_current_number++;}
276
        update_option('wpshop_order_current_number', $order_current_number);
277
278
        $order_ref = (string) sprintf('%0' . $number_figures . 'd', $order_current_number);
279
        return WPSHOP_ORDER_REFERENCE_PREFIX . $order_ref;
280
    }
281
282
    /** Renvoi une nouvelle r�f�rence unique pour un devis
283
     * @return int
284
     */
285 View Code Duplication
    public static function get_new_pre_order_reference($save = true)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
286
    {
287
        $number_figures = get_option('wpshop_order_number_figures', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
288
        /* If the number doesn't exist, we create a default one */
289
        if (!$number_figures) {
290
            $number_figures = 5;
291
            update_option('wpshop_order_number_figures', $number_figures);
292
        }
293
294
        $order_current_number = get_option('wpshop_preorder_current_number', false);
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
295
        /* If the counter doesn't exist, we initiate it */
296
        if (!$order_current_number) {$order_current_number = 1;} else { $order_current_number++;}
297
        if ($save) {
298
            update_option('wpshop_preorder_current_number', $order_current_number);
299
        }
300
301
        $order_ref = (string) sprintf('%0' . $number_figures . 'd', $order_current_number);
302
        return WPSHOP_PREORDER_REFERENCE_PREFIX . $order_ref;
303
    }
304
305
    /**
306
     *    Add information about user to the selected order
307
     *
308
     *    @param int $user_id The user identifier to get information for and to add to order meta informations
309
     *    @param int $order_id The order identifier to update meta information for
310
     *
311
     *    @return void
312
     */
313
    public static function set_order_customer_addresses($user_id, $order_id, $shipping_address_id = '', $billing_address_id = '')
0 ignored issues
show
Unused Code introduced by
The parameter $user_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
314
    {
315
        /**    Get order informations    */
316
        $billing_info['id'] = get_post_meta($billing_address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$billing_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $billing_info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
317
        $billing_info['address'] = get_post_meta($billing_address_id, '_' . WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS . '_metadata', true);
318
        $billing_info['address_id'] = (!empty($_SESSION['billing_address'])) ? intval($_SESSION['billing_address']) : '';
319
        if (!empty($_SESSION['shipping_partner_id'])) {
320
            $partner_address_id = get_post_meta($_SESSION['shipping_partner_id'], '_wpshop_attached_address', true);
321
            if (!empty($partner_address_id)) {
322
                foreach ($partner_address_id as $address_id) {
323
                    $shipping_info['id'] = get_post_meta($address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$shipping_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $shipping_info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
324
                    $shipping_info['address'] = get_post_meta($address_id, '_' . WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS . '_metadata', true);
325
                }
326
            }
327
        } else {
328
            $shipping_info['id'] = get_post_meta($shipping_address_id, WPSHOP_ADDRESS_ATTRIBUTE_SET_ID_META_KEY, true);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$shipping_info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $shipping_info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
329
            $shipping_info['address'] = get_post_meta($shipping_address_id, '_' . WPSHOP_NEWTYPE_IDENTIFIER_ADDRESS . '_metadata', true);
330
            $shipping_info['address_id'] = (!empty($_SESSION['shipping_address'])) ? intval($_SESSION['shipping_address']) : '';
331
        }
332
333
        $order_info = array('billing' => $billing_info, 'shipping' => $shipping_info);
0 ignored issues
show
Bug introduced by
The variable $shipping_info does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
334
335
        /**    Update order info metadata with new shipping    */
336
        update_post_meta($order_id, '_order_info', $order_info);
337
    }
338
339
    /** Set the custom colums
340
     * @return array
341
     */
342
    public static function orders_edit_columns($columns)
0 ignored issues
show
Unused Code introduced by
The parameter $columns is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
343
    {
344
        $columns = array(
345
            'cb' => '<input type="checkbox" />',
346
            'order_identifier' => __('Identifiers', 'wpshop'),
347
            'order_status' => __('Status', 'wpshop'),
348
            'order_type' => __('Order type', 'wpshop'),
349
            'order_billing' => __('Billing', 'wpshop'),
350
            'order_shipping' => __('Shipping', 'wpshop'),
351
            'order_total' => __('Order total', 'wpshop'),
352
            'date' => __('Date', 'wpshop'),
353
            //'order_actions' => __('Actions', 'wpshop')
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
354
        );
355
356
        return $columns;
357
    }
358
359
    /** Give the content by column
360
     * @return array
361
     */
362
    public static function orders_custom_columns($column, $post_id)
363
    {
364
        if (get_post_type($post_id) == WPSHOP_NEWTYPE_IDENTIFIER_ORDER) {
365
            global $civility, $order_status;
366
367
            $metadata = get_post_custom();
368
369
            $order_postmeta = isset($metadata['_order_postmeta'][0]) ? unserialize($metadata['_order_postmeta'][0]) : '';
370
            $addresses = get_post_meta($post_id, '_order_info', true);
371
372
            switch ($column) {
373
                case "order_identifier":
374
                    if (!empty($order_postmeta['order_key'])) {
375
                        echo '<b>' . $order_postmeta['order_key'] . '</b><br>';
376
                    }
377
                    if (!empty($order_postmeta['order_invoice_ref'])) {
378
                        echo '<i>' . $order_postmeta['order_invoice_ref'] . '</i>';
379
                    } elseif (!empty($order_postmeta['order_temporary_key'])) {
380
                        echo '<b>' . $order_postmeta['order_temporary_key'] . '</b>';
381
                    }
382
                    break;
383
384
                case "order_status":
385
                    echo !empty($order_postmeta['order_status']) ? sprintf('<mark class="%s" id="order_status_' . $post_id . '">%s</mark>', sanitize_title(strtolower($order_postmeta['order_status'])), __($order_status[strtolower($order_postmeta['order_status'])], 'wpshop')) : __('Unknown Status', 'wpshop');
386
                    break;
387
388
                case "order_billing":
389 View Code Duplication
                    if (!empty($addresses['billing']) && !empty($addresses['billing']['address']) && is_array($addresses['billing']['address'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
390
                        $billing = $addresses['billing']['address'];
391
                    } else if (!empty($addresses['billing'])) {
392
                        $billing = $addresses['billing'];
393
                    }
394
                    if (!empty($billing)) {
395
                        echo (!empty($billing['civility']) ? __(wpshop_attributes::get_attribute_type_select_option_info($billing['civility'], 'label', 'custom'), 'wpshop') : null) . ' <strong>' . (!empty($billing['address_first_name']) ? $billing['address_first_name'] : null) . ' ' . (!empty($billing['address_last_name']) ? $billing['address_last_name'] : null) . '</strong>';
396
                        echo empty($billing['company']) ? '<br />' : ', <i>' . $billing['company'] . '</i><br />';
397
                        echo !empty($billing['address']) ? $billing['address'] : null;
398
                        echo !empty($billing['postcode']) ? '<br />' . $billing['postcode'] . ' ' : null;
399
                        echo !empty($billing['city']) ? $billing['city'] . ', ' : null;
400
                        echo !empty($billing['country']) ? $billing['country'] : null;
401
                        echo (!empty($billing['phone']) ? '<br /><b>' . $billing['phone'] . '</b>' : '');
402
                    } else {
403
                        echo __('No information available for user billing', 'wpshop');
404
                    }
405
                    break;
406
407
                case "order_shipping":
408 View Code Duplication
                    if (!empty($addresses['shipping']) && !empty($addresses['shipping']['address']) && is_array($addresses['shipping']['address'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
409
                        $shipping = $addresses['shipping']['address'];
410
                    } else if (!empty($addresses['shipping'])) {
411
                        $shipping = $addresses['shipping'];
412
                    }
413
                    if (!empty($shipping)) {
414
                        echo '<strong>' . (!empty($shipping['address_first_name']) ? $shipping['address_first_name'] : null) . ' ' . (!empty($shipping['address_last_name']) ? $shipping['address_last_name'] : null) . '</strong>';
415
                        echo empty($shipping['company']) ? '<br />' : ', <i>' . $shipping['company'] . '</i><br />';
416
                        echo (!empty($shipping['address']) ? $shipping['address'] : null);
417
                        echo !empty($billing['postcode']) ? '<br />' . $billing['postcode'] . ' ' : null;
0 ignored issues
show
Bug introduced by
The variable $billing seems only to be defined at a later point. As such the call to empty() seems to always evaluate to true.

This check marks calls to isset(...) or empty(...) that are found before the variable itself is defined. These will always have the same result.

This is likely the result of code being shifted around. Consider removing these calls.

Loading history...
418
                        echo !empty($billing['city']) ? $billing['city'] . ', ' : null;
419
                        echo !empty($billing['country']) ? $billing['country'] : null;
420
                    } else {
421
                        echo __('No information available for user shipping', 'wpshop');
422
                    }
423
                    break;
424
425
                case "order_type":
426
                    echo '<a href="' . admin_url('post.php?post=' . $post_id . '&action=edit') . '">' . (!empty($order_postmeta['order_temporary_key']) ? __('Quotation', 'wpshop') : __('Basic order', 'wpshop')) . '</a>';
427
                    $buttons = '<p class="row-actions">';
428
                    // Voir la commande
429
                    $buttons .= '<a class="button button-small" href="' . admin_url('post.php?post=' . $post_id . '&action=edit') . '">' . __('View', 'wpshop') . '</a>';
430
                    // Marquer comme envoy�
431
                    if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'completed')) {
432
                        $buttons .= '<a data-id="' . $post_id . '" class="wps-bton-second-mini-rounded markAsShipped order_' . $post_id . ' wps-bton-loader">' . __('Mark as shipped', 'wpshop') . '</a> ';
433
                    } else if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'awaiting_payment')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
434
                        //        $buttons .= '<a class="button markAsCompleted order_'.$post_id.' alignleft" >'.__('Payment received', 'wpshop').'</a>' . wpshop_payment::display_payment_receiver_interface($post_id) . ' ';
0 ignored issues
show
Unused Code Comprehensibility introduced by
46% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
435
                    }
436
                    $buttons .= '</p>';
437
                    $buttons .= '<input type="hidden" name="input_wpshop_change_order_state" id="input_wpshop_change_order_state" value="' . wp_create_nonce("wpshop_change_order_state") . '" />';
438
                    $buttons .= '<input type="hidden" name="input_wpshop_dialog_inform_shipping_number" id="input_wpshop_dialog_inform_shipping_number" value="' . wp_create_nonce("wpshop_dialog_inform_shipping_number") . '" />';
439
                    $buttons .= '<input type="hidden" name="input_wpshop_validate_payment_method" id="input_wpshop_validate_payment_method" value="' . wp_create_nonce("wpshop_validate_payment_method") . '" />';
440
441
                    echo $buttons;
442
                    break;
443
444
                case "order_total":
445
                    $currency = !empty($order_postmeta['order_currency']) ? $order_postmeta['order_currency'] : get_option('wpshop_shop_default_currency');
446
                    echo isset($order_postmeta['order_grand_total']) ? number_format($order_postmeta['order_grand_total'], 2, '.', '') . ' ' . wpshop_tools::wpshop_get_sigle($currency) : 'NaN';
447
                    break;
448
449
                    /*case "order_actions":
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
450
            $buttons = '<p class="row-actions">';
451
            // Marquer comme envoy�
452
            if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'completed')) {
453
            $buttons .= '<a class="button markAsShipped order_'.$post_id.'">'.__('Mark as shipped', 'wpshop').'</a> ';
454
            }
455
            else if (!empty($order_postmeta['order_status']) && ($order_postmeta['order_status'] == 'awaiting_payment' )) {
456
            //        $buttons .= '<a class="button markAsCompleted order_'.$post_id.' alignleft" >'.__('Payment received', 'wpshop').'</a>' . wpshop_payment::display_payment_receiver_interface($post_id) . ' ';
457
            }
458
459
            // Voir la commande
460
            $buttons .= '<a class="button alignright" href="'.admin_url('post.php?post='.$post_id.'&action=edit').'">'.__('View', 'wpshop').'</a>';
461
            $buttons .= '</p>';
462
            $buttons .= '<input type="hidden" name="input_wpshop_change_order_state" id="input_wpshop_change_order_state" value="' . wp_create_nonce("wpshop_change_order_state") . '" />';
463
            $buttons .= '<input type="hidden" name="input_wpshop_dialog_inform_shipping_number" id="input_wpshop_dialog_inform_shipping_number" value="' . wp_create_nonce("wpshop_dialog_inform_shipping_number") . '" />';
464
            $buttons .= '<input type="hidden" name="input_wpshop_validate_payment_method" id="input_wpshop_validate_payment_method" value="' . wp_create_nonce("wpshop_validate_payment_method") . '" />';
465
466
            echo $buttons;
467
            break;*/
468
            }
469
470
        }
471
    }
472
473
    public static function list_table_filters()
474
    {
475
        $post_type = !empty($_GET['post_type']) ? sanitize_text_field($_GET['post_type']) : '';
476
        $entity_filter = !empty($_GET['entity_filter']) ? sanitize_text_field($_GET['entity_filter']) : '';
477
        $entity_filter_btpf = !empty($_GET['entity_filter_btpf']) ? sanitize_text_field($_GET['entity_filter_btpf']) : '';
478
        $entity_filter_btps = !empty($_GET['entity_filter_btps']) ? sanitize_text_field($_GET['entity_filter_btps']) : '';
479
480
        if (isset($post_type)) {
481
            if (post_type_exists($post_type) && ($post_type == WPSHOP_NEWTYPE_IDENTIFIER_ORDER)) {
482
                $filter_possibilities = array();
483
                $filter_possibilities['all'] = __('-- Select Filter --', 'wpshop');
484
                $filter_possibilities['only_orders'] = __('List orders only', 'wpshop');
485
                $filter_possibilities['quotations'] = __('List quotations only', 'wpshop');
486
                $filter_possibilities['free_orders'] = __('List orders free', 'wpshop');
487
                echo wpshop_form::form_input_select('entity_filter', 'entity_filter', $filter_possibilities, $entity_filter, '', 'index');
488
                $min = $entity_filter_btpf;
489
                $max = $entity_filter_btps;
490
                echo ' <label for="entity_filter_btpf">' . __('Between two prices', 'wpshop') . '</label> ';
491
                echo wpshop_form::form_input('entity_filter_btpf', 'entity_filter_btpf', $min, 'text', 'placeholder="' . __('Minimum price', 'wpshop') . '"', null);
492
                echo wpshop_form::form_input('entity_filter_btps', 'entity_filter_btps', $max, 'text', 'placeholder="' . __('Maximum price', 'wpshop') . '"', null);
493
            }
494
        }
495
    }
496
497
    public static function list_table_filter_parse_query($query)
498
    {
499
        global $pagenow, $wpdb;
500
        $post_type = !empty($_GET['post_type']) ? sanitize_text_field($_GET['post_type']) : '';
501
        $entity_filter = !empty($_GET['entity_filter']) ? sanitize_text_field($_GET['entity_filter']) : '';
502
        $entity_filter_btpf = !empty($_GET['entity_filter_btpf']) ? sanitize_text_field($_GET['entity_filter_btpf']) : '';
0 ignored issues
show
Unused Code introduced by
$entity_filter_btpf is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
503
        $entity_filter_btps = !empty($_GET['entity_filter_btps']) ? sanitize_text_field($_GET['entity_filter_btps']) : '';
0 ignored issues
show
Unused Code introduced by
$entity_filter_btps is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
504
505
        if (is_admin() && ($pagenow == 'edit.php') && !empty($post_type) && ($post_type == WPSHOP_NEWTYPE_IDENTIFIER_ORDER) && !empty($entity_filter)) {
506
            $check = null;
507
            switch ($entity_filter) {
508
                case 'all':
509
                    $sql_query = $wpdb->prepare(
510
                        "SELECT ID
511
						FROM {$wpdb->posts}
512
						WHERE post_type = %s
513
						AND post_status != %s",
514
                        WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
515
                        'auto-draft');
516
                    $check = 'post__in';
517
                    break;
518 View Code Duplication
                case 'only_orders':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
519
                    $sql_query = $wpdb->prepare(
520
                        "SELECT ID
521
						FROM {$wpdb->posts}
522
						INNER JOIN {$wpdb->postmeta}
523
						ON post_id = ID
524
						AND meta_key = %s
525
						AND meta_value NOT LIKE %s
526
						AND meta_value NOT LIKE %s
527
						WHERE post_type = %s
528
						AND post_status != %s",
529
                        '_order_postmeta',
530
                        '%s:9:"cart_type";s:9:"quotation";%',
531
                        '%s:17:"order_grand_total";d:0;%',
532
                        WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
533
                        'auto-draft');
534
                    $check = 'post__in';
535
                    break;
536 View Code Duplication
                case 'quotations':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
537
                    $sql_query = $wpdb->prepare(
538
                        "SELECT ID
539
						FROM {$wpdb->posts}
540
						INNER JOIN {$wpdb->postmeta}
541
						ON post_id = ID
542
						AND meta_key = %s
543
						AND meta_value LIKE %s
544
						WHERE post_type = %s
545
						AND post_status != %s",
546
                        '_order_postmeta',
547
                        '%s:9:"cart_type";s:9:"quotation";%',
548
                        WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
549
                        'auto-draft');
550
                    $check = 'post__in';
551
                    break;
552 View Code Duplication
                case 'free_orders':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
553
                    $sql_query = $wpdb->prepare(
554
                        "SELECT ID
555
							FROM {$wpdb->posts}
556
							INNER JOIN {$wpdb->postmeta}
557
							ON post_id = ID
558
							AND meta_key = %s
559
							AND meta_value LIKE %s
560
							WHERE post_type = %s
561
							AND post_status != %s",
562
                        '_order_postmeta',
563
                        '%s:17:"order_grand_total";d:0;%',
564
                        WPSHOP_NEWTYPE_IDENTIFIER_ORDER,
565
                        'auto-draft');
566
                    $check = 'post__in';
567
                    $no_btp = 'yes';
568
                    break;
569
            }
570
571
            if (!empty($check)) {
572
                if (!empty($no_btp) && $no_btp == 'yes') {
573
                    $min = 'minimum';
574
                    $max = 'maximum';
575
                } else {
576
                    $min = (!empty($_GET['entity_filter_btpf']) && is_numeric($_GET['entity_filter_btpf'])) ? sanitize_text_field($_GET['entity_filter_btpf']) : 'minimum';
577
                    $max = (!empty($_GET['entity_filter_btps']) && is_numeric($_GET['entity_filter_btps'])) ? sanitize_text_field($_GET['entity_filter_btps']) : 'maximum';
578
                }
579
                $results = $wpdb->get_results($sql_query);
0 ignored issues
show
Bug introduced by
The variable $sql_query does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
580
                $post_id_list = array();
581
                $i = 0;
0 ignored issues
show
Unused Code introduced by
$i is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
582
                foreach ($results as $item) {
583
                    $meta_value = get_post_meta($item->ID, '_order_postmeta');
584
                    $price = (!empty($meta_value[0]['order_grand_total'])) ? $meta_value[0]['order_grand_total'] : '';
585
                    if ($price >= $min || $min == 'minimum') {
586
                        if ($price <= $max || $max == 'maximum') {
587
                            $post_id_list[] = $item->ID;
588
                        }
589
                    }
590
                }
591
                if (empty($post_id_list)) {
592
                    $post_id_list[] = 'no_result';
593
                }
594
                $query->query_vars[$check] = $post_id_list;
595
            }
596
            $query->query_vars['post_type'] = WPSHOP_NEWTYPE_IDENTIFIER_ORDER;
597
        }
598
    }
599
600
    public function latest_products_ordered($orders)
601
    {
602
        global $wpdb;
603
        $product_id = $output = '';
0 ignored issues
show
Unused Code introduced by
$product_id is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
604
        $products = array();
605
        $display_option = get_option('wpshop_display_option');
606
        if (!empty($orders) && !empty($display_option) && !empty($display_option['latest_products_ordered'])) {
607
            foreach ($orders as $order) {
608
                $order_content = get_post_meta($order->ID, '_order_postmeta', true);
609
                if (!empty($order_content) && !empty($order_content['order_items'])) {
610
611
                    foreach ($order_content['order_items'] as $item) {
612
                        if (count($products) >= $display_option['latest_products_ordered']) {
613
                            continue;
614
                        }
615
                        $product_id = $item['item_id'];
616
                        if (!empty($item) && !empty($item['item_meta']) && !empty($item['item_meta']['variation_definition'])) {
617
                            $parent_def = wpshop_products::get_parent_variation($item['item_id']);
618
                            if (!empty($parent_def)) {
619
                                $parent_post = $parent_def['parent_post'];
620
                                $product_id = $parent_post->ID;
621
                            }
622
                        }
623
624
                        if (!in_array($product_id, $products)) {
625
                            $products[] = $product_id;
626
                        }
627
                    }
628
                }
629
            }
630
            if (!empty($products)) {
631
                $products_id = implode(",", $products);
632
                $output = wpshop_display::display_template_element('latest_products_ordered', array('LATEST_PRODUCTS_ORDERED' => do_shortcode('[wpshop_products pid="' . $products_id . '"]')));
633
            }
634
        }
635
        return $output;
636
    }
637
638
    public function get_order_list_for_customer($customer_id)
639
    {
640
        global $wpdb;
641
        $output = '';
642
643
        if (!empty($customer_id)) {
644
            $query = $wpdb->prepare('SELECT *
645
							 		   FROM ' . $wpdb->posts . '
646
							 		   WHERE post_author = %d
647
							 		   AND post_type = %s', $customer_id, WPSHOP_NEWTYPE_IDENTIFIER_CUSTOMERS);
648
            $orders = $wpdb->get_results($query);
649
650
            foreach ($orders as $order) {
0 ignored issues
show
Unused Code introduced by
This foreach statement is empty and can be removed.

This check looks for foreach loops that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

Consider removing the loop.

Loading history...
651
652
            }
653
        }
654
655
        return $output;
656
    }
657
    public static function display_customer_pay_quotation($state, $oid)
658
    {
659
        $btn = '<p><a role="button" data-nonce="' . wp_create_nonce('wps_quotation_is_payable_by_customer') . '" class="wps-bton-' . (($state) ? 'third' : 'second') . '-mini-rounded quotation_is_payable_by_customer" href="#" >' . __('Valid quotation', 'wpshop') . '</a></p>';
660
        if ($state) {
661
            $btn .= self::display_customer_pay_order($oid);
662
        }
663
        return $btn;
664
    }
665
    public static function display_customer_pay_order($oid)
666
    {
667
        $output = '<span>';
668
        $output .= '<input id="wps_direct_link_url" type="text" value="' . wpshop_checkout::wps_direct_payment_link_url($oid) . '"/>';
669
        $output .= '<a class="button" data-copy-target="#wps_direct_link_url" title="' . __('Copy', 'wpshop') . '">';
670
        $output .= '<span class="dashicons dashicons-clipboard"></span>';
671
        $output .= '</a>';
672
        $output .= '<a data-nonce="' . wp_create_nonce('wps_send_direct_payment_link') . '" role="button" class="button" href="#" title="' . __('Send by mail', 'wpshop') . '">';
673
        $output .= '<span class="dashicons dashicons-email"></span>';
674
        $output .= '</a>';
675
        $output .= '</span>';
676
        $output .= '<span>' . sprintf(__('Link is valid until %s', 'wpshop'), mysql2date(get_option('date_format'), date_format(date_create(date('Y-m') . ' + 2month - 1day'), 'Y-m-d H:i:s'), true)) . '</span>';
677
        return $output;
678
    }
679
}
680