Completed
Push — master ( 1a7b7a...d6aa9b )
by Dan
06:23
created

Shipping_API::process_api_request()   C

Complexity

Conditions 9
Paths 9

Size

Total Lines 50
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90
Metric Value
dl 0
loc 50
ccs 0
cts 32
cp 0
rs 6
cc 9
eloc 31
nc 9
nop 1
crap 90
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 21 and the first side effect is on line 12.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * SSI Shipping API Connector
4
 *
5
 * @package     PrintCenter\Shipping_API
6
 * @since       1.0.0
7
 */
8
9
10
// Exit if accessed directly
11
if( ! defined( 'ABSPATH' ) ) {
12
	exit;
13
}
14
15
16
/**
17
 * Main Shipping_API class
18
 *
19
 * @since       1.0.0
20
 */
21
class Shipping_API {
22
23
24
	/**
25
	 * Get things started
26
	 *
27
	 * @access      public
28
	 * @since       1.0.0
29
	 * @return      void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
30
	 */
31
	public function __construct() {
32
		$this->hooks();
33
	}
34
35
36
	/**
37
	 * Run action and filter hooks
38
	 *
39
	 * @access      public
40
	 * @since       1.0.0
41
	 * @return      void
42
	 */
43
	public function hooks() {
44
		add_action( 'rest_api_init', array( $this, 'api_init' ) );
45
		add_action( 'woocommerce_admin_order_data_after_shipping_address', array( $this, 'display_order_data' ) );
46
		add_filter( 'woocommerce_email_classes', array( $this, 'add_shipped_email' ) );
47
	}
48
49
50
	/**
51
	 * Initialize our API endpoint
52
	 *
53
	 * @access      public
54
	 * @since       1.0.0
55
	 * @return      void
56
	 */
57
	public function api_init() {
58
		register_rest_route( 'ssi-shipping/v1', '/order', array(
59
			'methods'  => 'POST',
60
			'callback' => array( $this, 'process_api_request' ),
61
			'args'     => array(
62
				'key' => array(
63
					'required' => true
64
				)
65
			)
66
		) );
67
	}
68
69
70
	/**
71
	 * Process a call to the shipping API
72
	 *
73
	 * @access      public
74
	 * @since       1.0.0
75
	 * @param       array $data Data passed to the API
76
	 * @return      void
77
	 */
78
	public function process_api_request( $data ) {
79
		$sitekey = md5( home_url() );
80
81
		if( $data['key'] == $sitekey ) {
82
			$xmldata = $data->get_body();
0 ignored issues
show
Bug introduced by
The method get_body cannot be called on $data (of type array<string,?,{"key":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
83
			$xmldata = xmlstr_to_array( $xmldata );
84
85
			if( isset( $xmldata['@attributes']['id'] ) && isset( $xmldata['@attributes']['status'] ) ) {
86
				$order_id = (int) $xmldata['@attributes']['id'];
87
88
				// Bail if this isn't an order
89
				if( get_post_type( $order_id ) !== 'shop_order' ) {
90
					return false;
91
				}
92
93
				// Update shipped status
94
				if( $xmldata['@attributes']['status'] == 'shipped' ) {
95
					update_post_meta( $order_id, '_ssi_shipped', 'true' );
96
					update_post_meta( $order_id, '_ssi_ship_date', current_time( 'm/d/Y' ) );
97
				} else {
98
					delete_post_meta( $order_id, '_ssi_shipped' );
99
				}
100
101
				if( count( $xmldata['tracking'] ) > 0 ) {
102
					if( count( $xmldata['tracking'] ) > 1 ) {
103
						foreach( $xmldata['tracking'] as $tracking_data ) {
104
							$tracking_numbers[] = $tracking_data['@attributes']['number'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tracking_numbers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tracking_numbers = 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...
105
						}
106
					} else {
107
						$tracking_numbers[] = $xmldata['tracking']['@attributes']['number'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$tracking_numbers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tracking_numbers = 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...
108
					}
109
110
					update_post_meta( $order_id, '_ssi_tracking_numbers', $tracking_numbers );
0 ignored issues
show
Bug introduced by
The variable $tracking_numbers 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...
111
					update_post_meta( $order_id, '_ssi_shipper', $xmldata['shipment']['@attributes']['shipper'] );
112
				}
113
114
				//do_action( 'printcenter_send_shipping_email', $order_id );
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
115
				require_once WP_PLUGIN_DIR . '/woocommerce/includes/libraries/class-emogrifier.php';
116
				require_once WP_PLUGIN_DIR . '/woocommerce/includes/emails/class-wc-email.php';
117
				require_once PRINTCENTER_DIR . 'includes/class.wc-order-shipped-email.php';
118
				$mail = new WC_Order_Shipped_Email();
119
				$mail->trigger( $order_id );
120
121
				return true;
122
			}
123
			return false;
124
		} else {
125
			return false;
126
		}
127
	}
128
129
130
	/**
131
	 * Display order data in dashboard
132
	 *
133
	 * @access      public
134
	 * @since       1.0.0
135
	 * @param       object $order The data for a given order
136
	 * @return      void
137
	 */
138
	public function display_order_data( $order ) {
139
		$shipping_status  = get_post_meta( $order->id, '_ssi_shipped', true );
140
		$shipper          = get_post_meta( $order->id, '_ssi_shipper', true );
141
		$shipping_date    = get_post_meta( $order->id, '_ssi_ship_date', true );
142
		$tracking_numbers = get_post_meta( $order->id, '_ssi_tracking_numbers' );
143
144
		$html  = '<h4>' . __( 'Shipping Status', 'printcenter' ) . '</h4>';
145
		$html .= '<div class="shipping-status">';
146
		$html .= '<p>';
147
		$html .= '<strong>' . __( 'Shipped:', 'printcenter' ) . '</strong><br />';
148
		$html .= ( $shipping_status ? sprintf( __( 'Yes (%s)', 'printcenter' ), $shipping_date ) : __( 'No', 'printcenter' ) );
149
		$html .= '</p>';
150
		$html .= '<p>';
151
		$html .= '<strong>' . __( 'Tracking Numbers:', 'printcenter' ) . '</strong><br />';
152
153
		if( $tracking_numbers ) {
154
			foreach( $tracking_numbers[0] as $tracking_number ) {
155
				if( $shipper == 'USPS' ) {
156
					$html .= '<a href="https://tools.usps.com/go/TrackConfirmAction?tLabels=' . $tracking_number . '" target="_blank">' . $tracking_number . '</a><br />';
157
				} else {
158
					$html .= $tracking_number . '<br />';
159
				}
160
			}
161
		} else {
162
			$html .= __( 'Unknown', 'printcenter' );
163
		}
164
165
		$html .= '</p>';
166
		$html .= '</div>';
167
168
		echo $html;
169
	}
170
171
172
	/**
173
	 * Adds an email for product shipping notifications
174
	 *
175
	 * @access      public
176
	 * @since       1.0.0
177
	 * @param       array $email_classes Available email classes
178
	 * @return      array Filtered available email classes
179
	 */
180
	public function add_shipped_email( $email_classes ) {
181
		require_once PRINTCENTER_DIR . 'includes/class.wc-order-shipped-email.php';
182
183
		$email_classes['WC_Order_Shipped_Email'] = new WC_Order_Shipped_Email();
184
185
		return $email_classes;
186
	}
187
}