Completed
Push — master ( 684c91...3e895b )
by Dan
07:28
created

Shipping_API::display_order_data()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 32
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30
Metric Value
dl 0
loc 32
ccs 0
cts 26
cp 0
rs 8.439
cc 5
eloc 24
nc 4
nop 1
crap 30
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
	}
47
48
49
	/**
50
	 * Initialize our API endpoint
51
	 *
52
	 * @access      public
53
	 * @since       1.0.0
54
	 * @return      void
55
	 */
56
	public function api_init() {
57
		register_rest_route( 'ssi-shipping/v1', '/order', array(
58
			'methods'  => 'POST',
59
			'callback' => array( $this, 'process_api_request' ),
60
			'args'     => array(
61
				'key' => array(
62
					'required' => true
63
				)
64
			)
65
		) );
66
	}
67
68
69
	/**
70
	 * Process a call to the shipping API
71
	 *
72
	 * @access      public
73
	 * @since       1.0.0
74
	 * @param       array $data Data passed to the API
75
	 * @return      void
76
	 */
77
	public function process_api_request( $data ) {
78
		$sitekey = md5( home_url() );
79
80
		if( $data['key'] == $sitekey ) {
81
			$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...
82
			$xmldata = xmlstr_to_array( $xmldata );
83
84
			if( isset( $xmldata['@attributes']['id'] ) && isset( $xmldata['@attributes']['status'] ) ) {
85
				$order_id = (int) $xmldata['@attributes']['id'];
86
87
				// Bail if this isn't an order
88
				if( get_post_type( $order_id ) !== 'shop_order' ) {
89
					return false;
90
				}
91
92
				// Update shipped status
93
				if( $xmldata['@attributes']['status'] == 'shipped' ) {
94
					update_post_meta( $order_id, '_ssi_shipped', 'true' );
95
					update_post_meta( $order_id, '_ssi_ship_date', current_time( 'm/d/Y' ) );
96
				} else {
97
					delete_post_meta( $order_id, '_ssi_shipped' );
98
				}
99
100
				if( count( $xmldata['tracking'] ) > 0 ) {
101
					if( count( $xmldata['tracking'] ) > 1 ) {
102
						foreach( $xmldata['tracking'] as $tracking_data ) {
103
							$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...
104
						}
105
					} else {
106
						$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...
107
					}
108
109
					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...
110
					update_post_meta( $order_id, '_ssi_shipper', $xmldata['shipment']['@attributes']['shipper'] );
111
				}
112
			}
113
			return true;
114
		} else {
115
			return false;
116
		}
117
	}
118
119
120
	/**
121
	 * Display order data in dashboard
122
	 *
123
	 * @access      public
124
	 * @since       1.0.0
125
	 * @param       object $order The data for a given order
126
	 * @return      void
127
	 */
128
	public function display_order_data( $order ) {
129
		$shipping_status  = get_post_meta( $order->id, '_ssi_shipped', true );
130
		$shipper          = get_post_meta( $order->id, '_ssi_shipper', true );
131
		$shipping_date    = get_post_meta( $order->id, '_ssi_ship_date', true );
132
		$tracking_numbers = get_post_meta( $order->id, '_ssi_tracking_numbers' );
133
134
		$html  = '<h4>' . __( 'Shipping Status', 'printcenter' ) . '</h4>';
135
		$html .= '<div class="shipping-status">';
136
		$html .= '<p>';
137
		$html .= '<strong>' . __( 'Shipped:', 'printcenter' ) . '</strong><br />';
138
		$html .= ( $shipping_status ? sprintf( __( 'Yes (%s)', 'printcenter' ), $shipping_date ) : __( 'No', 'printcenter' ) );
139
		$html .= '</p>';
140
		$html .= '<p>';
141
		$html .= '<strong>' . __( 'Tracking Numbers:', 'printcenter' ) . '</strong><br />';
142
143
		if( $tracking_numbers ) {
144
			foreach( $tracking_numbers[0] as $tracking_number ) {
145
				if( $shipper == 'USPS' ) {
146
					$html .= '<a href="https://tools.usps.com/go/TrackConfirmAction?tLabels=' . $tracking_number . '" target="_blank">' . $tracking_number . '</a><br />';
147
				} else {
148
					$html .= $tracking_number . '<br />';
149
				}
150
			}
151
		} else {
152
			$html .= __( 'Unknown', 'printcenter' );
153
		}
154
155
		$html .= '</p>';
156
		$html .= '</div>';
157
158
		echo $html;
159
	}
160
}