Completed
Pull Request — master (#9826)
by Mike
07:49
created

WC_Shipping_Zones::get_zone_by()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 24
rs 8.5125
cc 6
eloc 16
nc 8
nop 2
1
<?php
1 ignored issue
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 17 and the first side effect is on line 4.

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
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
/**
8
 * Handles storage and retrieval of shipping zones
9
 *
10
 * @class 		WC_Shipping_Zones
11
 * @since 		2.6.0
12
 * @version		2.6.0
13
 * @package		WooCommerce/Classes
14
 * @category	Class
15
 * @author 		WooThemes
16
 */
17
class WC_Shipping_Zones {
18
19
	/**
20
	 * Get shipping zones from the database
21
	 * @since 2.6.0
22
	 * @return array of arrays
23
	 */
24
    public static function get_zones() {
25
		global $wpdb;
26
27
        $raw_zones = $wpdb->get_results( "SELECT zone_id, zone_name, zone_order FROM {$wpdb->prefix}woocommerce_shipping_zones order by zone_order ASC;" );
28
		$zones     = array();
29
30
		foreach ( $raw_zones as $raw_zone ) {
31
			$zone                                                     = new WC_Shipping_Zone( $raw_zone );
32
			$zones[ $zone->get_zone_id() ]                            = $zone->get_data();
33
			$zones[ $zone->get_zone_id() ]['formatted_zone_location'] = $zone->get_formatted_location();
34
			$zones[ $zone->get_zone_id() ]['shipping_methods']        = $zone->get_shipping_methods();
35
		}
36
37
		return $zones;
38
    }
39
40
	/**
41
	 * Get shipping zone using it's ID
42
	 * @since 2.6.0
43
	 * @param int $zone_id
44
	 * @return WC_Shipping_Zone|bool
45
	 */
46
	public static function get_zone( $zone_id ) {
47
		return self::get_zone_by( 'zone_id', $zone_id );
48
	}
49
50
	/**
51
	 * Get shipping zone by an ID.
52
	 * @since 2.6.0
53
	 * @param string $by zone_id or instance_id
54
	 * @param int $id
55
	 * @return WC_Shipping_Zone|bool
56
	 */
57
	public static function get_zone_by( $by = 'zone_id', $id = 0 ) {
58
		global $wpdb;
59
60
		$raw_zone = false;
61
62
		switch ( $by ) {
63
			case 'zone_id' :
64
				if ( 0 === $id ) {
65
					return new WC_Shipping_Zone( 0 );
66
				} else {
67
					$raw_zone = $wpdb->get_row( $wpdb->prepare( "SELECT zone_id, zone_name, zone_order FROM {$wpdb->prefix}woocommerce_shipping_zones WHERE zone_id = %d LIMIT 1;", $id ) );
68
				}
69
			break;
70
			case 'instance_id' :
71
				$zone_id = $wpdb->get_var( $wpdb->prepare( "SELECT zone_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods as methods WHERE methods.instance_id = %d LIMIT 1;", $id ) );
72
73
				if ( false !== $zone_id ) {
74
					return self::get_zone_by( 'zone_id', absint( $zone_id ) );
75
				}
76
			break;
77
		}
78
79
		return $raw_zone ? new WC_Shipping_Zone( $raw_zone ) : false;
80
	}
81
82
	/**
83
	 * Get shipping zone using it's ID
84
	 * @since 2.6.0
85
	 * @param int $zone_id
0 ignored issues
show
Bug introduced by
There is no parameter named $zone_id. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
86
	 * @return WC_Shipping_Meethod|bool
87
	 */
88
	public static function get_shipping_method( $instance_id ) {
89
		global $wpdb;
90
		$raw_shipping_method = $wpdb->get_row( $wpdb->prepare( "SELECT instance_id, method_id FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE instance_id = %d LIMIT 1;", $instance_id ) );
91
		$wc_shipping         = WC_Shipping::instance();
92
		$allowed_classes     = $wc_shipping->get_shipping_method_class_names();
93
94
		if ( in_array( $raw_shipping_method->method_id, array_keys( $allowed_classes ) ) ) {
95
			$class_name = $allowed_classes[ $raw_shipping_method->method_id ];
96
			return new $class_name( $raw_shipping_method->instance_id );
97
		}
98
		return false;
99
	}
100
101
	/**
102
	 * Delete a zone using it's ID
103
	 * @param int $zone_id
104
	 * @since 2.6.0
105
	 */
106
    public static function delete_zone( $zone_id ) {
107
		$zone = new WC_Shipping_Zone( $zone_id );
108
		$zone->delete();
109
    }
110
111
	/**
112
	 * Get postcode wildcards in array format.
113
	 *
114
	 * Internal use only.
115
	 *
116
	 * @since 2.6.0
117
	 * @access private
118
	 *
119
	 * @param  string  $postcode array of values
120
	 * @return string[] Array of postcodes with wildcards
121
	 */
122 View Code Duplication
	private static function _get_wildcard_postcodes( $postcode ) {
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...
123
		$postcodes         = array( '*', strtoupper( $postcode ), strtoupper( $postcode ) . '*' );
124
		$postcode_length   = strlen( $postcode );
125
		$wildcard_postcode = strtoupper( $postcode );
126
127
		for ( $i = 0; $i < $postcode_length; $i ++ ) {
128
			$wildcard_postcode = substr( $wildcard_postcode, 0, -1 );
129
			$postcodes[] = $wildcard_postcode . '*';
130
		}
131
		return $postcodes;
132
	}
133
134
	/**
135
	 * Find a matching zone for a given package.
136
	 * @since  2.6.0
137
	 * @uses   wc_make_numeric_postcode()
138
	 * @param  object $package
139
	 * @return WC_Shipping_Zone
140
	 */
141
	public static function get_zone_matching_package( $package ) {
142
		global $wpdb;
143
144
		$country          = strtoupper( wc_clean( $package['destination']['country'] ) );
145
		$state            = strtoupper( wc_clean( $package['destination']['state'] ) );
146
		$continent        = strtoupper( wc_clean( WC()->countries->get_continent_code_for_country( $country ) ) );
147
		$postcode         = strtoupper( wc_clean( $package['destination']['postcode'] ) );
148
		$valid_postcodes  = array_map( 'wc_clean', self::_get_wildcard_postcodes( $postcode ) );
149
		$cache_key        = WC_Cache_Helper::get_cache_prefix( 'shipping_zones' ) . 'wc_shipping_zone_' . md5( sprintf( '%s+%s+%s', $country, $state, $postcode ) );
150
		$matching_zone_id = wp_cache_get( $cache_key, 'shipping_zones' );
151
152
		if ( false === $matching_zone_id ) {
153
154
			// Work out criteria for our zone search
155
			$criteria = array();
156
			$criteria[] = $wpdb->prepare( "( ( location_type = 'country' AND location_code = %s )", $country );
157
			$criteria[] = $wpdb->prepare( "OR ( location_type = 'state' AND location_code = %s )", $country . ':' . $state );
158
			$criteria[] = $wpdb->prepare( "OR ( location_type = 'continent' AND location_code = %s ) )", $continent );
159
160
			// Postcode range and wildcard matching
161
			$postcode_locations = $wpdb->get_results( "SELECT zone_id, location_code FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE location_type = 'postcode';" );
162
163
			if ( $postcode_locations ) {
164
				$zone_ids_with_postcode_rules = array_map( 'absint', wp_list_pluck( $postcode_locations, 'zone_id' ) );
165
				$zone_id_matches              = array();
166
167
				foreach ( $postcode_locations as $postcode_location ) {
168
					$postcode_to_match = trim( strtoupper( $postcode_location->location_code ) );
169
170
					// Ranges
171
					if ( strstr( '-', $postcode_to_match ) ) {
172
						$range = array_map( 'trim', explode( '-', $postcode_to_match ) );
173
174
						if ( sizeof( $range ) != 2 ) {
175
							continue;
176
						}
177
178
						if ( is_numeric( $range[0] ) && is_numeric( $range[1] ) ) {
179
							$encoded_postcode = $postcode;
180
							$min              = $range[0];
181
							$max              = $range[1];
182
						} else {
183
							$min = wc_make_numeric_postcode( $range[0] );
184
							$max = wc_make_numeric_postcode( $range[1] );
185
							$min = str_pad( $min, $encoded_postcode_len, '0' );
186
							$max = str_pad( $max, $encoded_postcode_len, '9' );
187
						}
188
189
						if ( $encoded_postcode >= $min && $encoded_postcode <= $max ) {
190
							$zone_id_matches[] = absint( $postcode_location->zone_id );
191
						}
192
193
					// Wildcard/standard
194
					} elseif ( in_array( $postcode_to_match, $valid_postcodes ) ) {
195
						$zone_id_matches[] = absint( $postcode_location->zone_id );
196
					}
197
				}
198
199
				$do_not_match = array_unique( array_diff( $zone_ids_with_postcode_rules, $zone_id_matches ) );
200
201
				if ( $do_not_match ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $do_not_match of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
202
					$criteria[] = "AND zones.zone_id NOT IN (" . implode( ',', $do_not_match ) . ")";
203
				}
204
			}
205
206
			// Get matching zones
207
			$matching_zone_id = $wpdb->get_var( "
208
				SELECT zones.zone_id FROM {$wpdb->prefix}woocommerce_shipping_zones as zones
209
				LEFT OUTER JOIN {$wpdb->prefix}woocommerce_shipping_zone_locations as locations ON zones.zone_id = locations.zone_id
210
				WHERE " . implode( ' ', $criteria ) . "
211
				ORDER BY zone_order ASC LIMIT 1
212
			" );
213
214
			wp_cache_set( $cache_key, $matching_zone_id, 'shipping_zones' );
215
		}
216
217
		return new WC_Shipping_Zone( $matching_zone_id ? $matching_zone_id : 0 );
218
	}
219
}
220