Completed
Push — master ( c144b8...1e0376 )
by Mike
19:13
created

WC_Shipping_Zone::set_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit;
5
}
6
7
/**
8
 * Represents a single shipping zone
9
 *
10
 * @class 		WC_Shipping_Zone
11
 * @version		2.6.0
12
 * @package		WooCommerce/Classes
13
 * @category	Class
14
 * @author 		WooThemes
15
 */
16
class WC_Shipping_Zone extends WC_Data {
17
18
	/**
19
	 * Zone Data
20
	 * @var array
21
	 */
22
	protected $_data = array(
23
		'zone_id'        => null,
24
		'zone_name'      => '',
25
		'zone_order'     => 0,
26
		'zone_locations' => array()
27
	);
28
29
	/**
30
	 * True when location data needs to be re-saved
31
	 * @var bool
32
	 */
33
	private $_locations_changed = false;
34
35
	/**
36
	 * Constructor for zones
37
	 * @param int|object $zone Zone ID to load from the DB (optional) or already queried data.
38
	 */
39
	public function __construct( $zone = null ) {
40
		if ( is_numeric( $zone ) && ! empty( $zone ) ) {
41
			$this->read( $zone );
42
		} elseif ( is_object( $zone ) ) {
43
			$this->set_id( $zone->zone_id );
44
			$this->set_zone_name( $zone->zone_name );
45
			$this->set_zone_order( $zone->zone_order );
46
			$this->read_zone_locations( $zone->zone_id );
47
		} elseif ( 0 === $zone ) {
48
			$this->set_id( 0 );
49
			$this->set_zone_name( __( 'Rest of the World', 'woocommerce' ) );
50
			$this->read_zone_locations( 0 );
51
		} else {
52
			$this->set_zone_name( __( 'Zone', 'woocommerce' ) );
53
		}
54
	}
55
56
	/**
57
	 * Insert zone into the database
58
	 */
59
	public function create() {
60
		global $wpdb;
61
		$wpdb->insert( $wpdb->prefix . 'woocommerce_shipping_zones', array(
62
			'zone_name'  => $this->get_zone_name(),
63
			'zone_order' => $this->get_zone_order(),
64
		) );
65
		$this->set_id( $wpdb->insert_id );
66
	}
67
68
	/**
69
	 * Read zone.
70
	 * @param int ID to read from DB
71
	 */
72
	public function read( $id ) {
73
		global $wpdb;
74
75
		if ( $zone_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_shipping_zones WHERE zone_id = %d LIMIT 1;", $id ) ) ) {
76
			$this->set_id( $zone_data->zone_id );
77
			$this->set_zone_name( $zone_data->zone_name );
78
			$this->set_zone_order( $zone_data->zone_order );
79
			$this->read_zone_locations( $zone_data->zone_id );
80
		}
81
	}
82
83
	/**
84
	 * Update zone in the database
85
	 */
86
	public function update() {
87
		global $wpdb;
88
89
		if ( $this->get_id() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->get_id() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
90
			$wpdb->update( $wpdb->prefix . 'woocommerce_shipping_zones', array(
91
				'zone_name'  => $this->get_zone_name(),
92
				'zone_order' => $this->get_zone_order(),
93
			), array( 'zone_id' => $this->get_id() ) );
94
		}
95
	}
96
97
	/**
98
	 * Delete a zone.
99
	 * @since 2.6.0
100
	 */
101
	public function delete() {
102
		if ( $this->get_id() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->get_id() of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
103
			global $wpdb;
104
			$wpdb->delete( $wpdb->prefix . 'woocommerce_shipping_zone_methods', array( 'zone_id' => $this->get_id() ) );
105
			$wpdb->delete( $wpdb->prefix . 'woocommerce_shipping_zone_locations', array( 'zone_id' => $this->get_id() ) );
106
			$wpdb->delete( $wpdb->prefix . 'woocommerce_shipping_zones', array( 'zone_id' => $this->get_id() ) );
107
			WC_Cache_Helper::incr_cache_prefix( 'shipping_zones' );
108
			$this->set_id( null );
109
		}
110
	}
111
112
	/**
113
	 * Save zone data to the database.
114
	 */
115
	public function save() {
116
		$name = $this->get_zone_name();
117
118
		if ( empty( $name ) ) {
119
			$this->set_zone_name( $this->generate_zone_name() );
120
		}
121
122
		if ( null === $this->get_id() ) {
123
			$this->create();
124
		} else {
125
			$this->update();
126
		}
127
128
		$this->save_locations();
129
		WC_Cache_Helper::incr_cache_prefix( 'shipping_zones' );
130
131
		// Increments the transient version to invalidate cache.
132
		WC_Cache_Helper::get_transient_version( 'shipping', true );
133
	}
134
135
	/**
136
	 * Get ID
137
	 * @return int|null Null if the zone does not exist. 0 is the default zone.
138
	 */
139
	public function get_id() {
140
		return $this->get_zone_id();
141
	}
142
143
	/**
144
	 * Get zone ID
145
	 * @return int|null Null if the zone does not exist. 0 is the default zone.
146
	 */
147
	public function get_zone_id() {
148
		return is_null( $this->_data['zone_id'] ) ? null : absint( $this->_data['zone_id'] );
149
	}
150
151
	/**
152
	 * Get zone name
153
	 * @return string
154
	 */
155
	public function get_zone_name() {
156
		return $this->_data['zone_name'];
157
	}
158
159
	/**
160
	 * Get zone order
161
	 * @return int
162
	 */
163
	public function get_zone_order() {
164
		return absint( $this->_data['zone_order'] );
165
	}
166
167
	/**
168
	 * Get zone locations
169
	 * @return array of zone objects
170
	 */
171
	public function get_zone_locations() {
172
		return $this->_data['zone_locations'];
173
	}
174
175
	/**
176
	 * Generate a zone name based on location.
177
	 * @return string
178
	 */
179
	protected function generate_zone_name() {
180
		$zone_name = $this->get_formatted_location();
181
182
		if ( empty( $zone_name ) ) {
183
			$zone_name = __( 'Zone', 'woocommerce' );
184
		}
185
186
		return $zone_name;
187
	}
188
189
	/**
190
	 * Return a text string representing what this zone is for.
191
	 * @return string
192
	 */
193
	public function get_formatted_location( $max = 10 ) {
194
		$location_parts = array();
195
		$all_continents = WC()->countries->get_continents();
196
		$all_countries  = WC()->countries->get_countries();
197
		$all_states     = WC()->countries->get_states();
198
		$locations      = $this->get_zone_locations();
199
		$continents     = array_filter( $locations, array( $this, 'location_is_continent' ) );
200
		$countries      = array_filter( $locations, array( $this, 'location_is_country' ) );
201
		$states         = array_filter( $locations, array( $this, 'location_is_state' ) );
202
		$postcodes      = array_filter( $locations, array( $this, 'location_is_postcode' ) );
203
204
		foreach ( $continents as $location ) {
205
			$location_parts[] = $all_continents[ $location->code ]['name'];
206
		}
207
208
		foreach ( $countries as $location ) {
209
			$location_parts[] = $all_countries[ $location->code ];
210
		}
211
212
		foreach ( $states as $location ) {
213
			$location_codes = explode( ':', $location->code );
214
			$location_parts[] = $all_states[ $location_codes[ 0 ] ][ $location_codes[ 1 ] ];
215
		}
216
217
		foreach ( $postcodes as $location ) {
218
			$location_parts[] = $location->code;
219
		}
220
221
		// Fix display of encoded characters.
222
		$location_parts = array_map( 'html_entity_decode', $location_parts );
223
224
		if ( sizeof( $location_parts ) > $max ) {
225
			$remaining = sizeof( $location_parts ) - $max;
226
			return sprintf( _n( '%s and %d other region', '%s and %d other regions', $remaining, 'woocommerce' ), implode( ', ', array_splice( $location_parts, 0, $max ) ), $remaining );
227
		} elseif ( ! empty( $location_parts ) ) {
228
			return implode( ', ', $location_parts );
229
		} else {
230
			return __( 'Everywhere', 'woocommerce' );
231
		}
232
	}
233
234
	/**
235
	 * Get shipping methods linked to this zone
236
	 * @param bool Only return enabled methods.
237
	 * @return array of objects
238
	 */
239
	public function get_shipping_methods( $enabled_only = false ) {
240
		global $wpdb;
241
242
		if ( null === $this->get_id() ) {
243
			return array();
244
		}
245
246
		$raw_methods_sql = $enabled_only ? "SELECT method_id, method_order, instance_id, is_enabled FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE zone_id = %d AND is_enabled = 1;" : "SELECT method_id, method_order, instance_id, is_enabled FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE zone_id = %d;";
247
		$raw_methods     = $wpdb->get_results( $wpdb->prepare( $raw_methods_sql, $this->get_id() ) );
248
		$wc_shipping     = WC_Shipping::instance();
249
		$allowed_classes = $wc_shipping->get_shipping_method_class_names();
250
		$methods         = array();
251
252
		foreach ( $raw_methods as $raw_method ) {
253
			if ( in_array( $raw_method->method_id, array_keys( $allowed_classes ), true ) ) {
254
				$class_name = $allowed_classes[ $raw_method->method_id ];
255
256
				// The returned array may contain instances of shipping methods, as well
257
				// as classes. If the "class" is an instance, just use it. If not,
258
				// create an instance.
259
				if ( is_object( $class_name ) ) {
260
					$class_name_of_instance = get_class( $class_name );
261
					$methods[ $raw_method->instance_id ] = new $class_name_of_instance( $raw_method->instance_id );
262
				} else {
263
					// If the class is not an object, it should be a string. It's better
264
					// to double check, to be sure (a class must be a string, anything)
265
					// else would be useless
266
					if ( is_string( $class_name ) && class_exists( $class_name ) ) {
267
						$methods[ $raw_method->instance_id ] = new $class_name( $raw_method->instance_id );
268
					}
269
				}
270
271
				// Let's make sure that we have an instance before setting its attributes
272
				if ( is_object( $methods[ $raw_method->instance_id ] ) ) {
273
					$methods[ $raw_method->instance_id ]->method_order  = absint( $raw_method->method_order );
274
					$methods[ $raw_method->instance_id ]->enabled       = $raw_method->is_enabled ? 'yes' : 'no';
275
					$methods[ $raw_method->instance_id ]->has_settings  = $methods[ $raw_method->instance_id ]->has_settings();
276
					$methods[ $raw_method->instance_id ]->settings_html = $methods[ $raw_method->instance_id ]->supports( 'instance-settings-modal' ) ? $methods[ $raw_method->instance_id ]->get_admin_options_html() : false;
277
				}
278
			}
279
		}
280
281
		return apply_filters( 'woocommerce_shipping_zone_shipping_methods', $methods, $raw_methods, $allowed_classes, $this );
282
	}
283
284
	/**
285
	 * Location type detection
286
	 * @param  object  $location
287
	 * @return boolean
288
	 */
289
	private function location_is_continent( $location ) {
290
		return 'continent' === $location->type;
291
	}
292
293
	/**
294
	 * Location type detection
295
	 * @param  object  $location
296
	 * @return boolean
297
	 */
298
	private function location_is_country( $location ) {
299
		return 'country' === $location->type;
300
	}
301
302
	/**
303
	 * Location type detection
304
	 * @param  object  $location
305
	 * @return boolean
306
	 */
307
	private function location_is_state( $location ) {
308
		return 'state' === $location->type;
309
	}
310
311
	/**
312
	 * Location type detection
313
	 * @param  object  $location
314
	 * @return boolean
315
	 */
316
	private function location_is_postcode( $location ) {
317
		return 'postcode' === $location->type;
318
	}
319
320
	/**
321
	 * Set zone ID
322
	 * @access private
323
	 * @param int $set
324
	 */
325
	private function set_id( $set ) {
326
		$this->set_zone_id( $set );
327
	}
328
329
	/**
330
	 * Set zone ID
331
	 * @access private
332
	 * @param int $set
333
	 */
334
	private function set_zone_id( $set ) {
335
		$this->_data['zone_id'] = is_null( $set ) ? null : absint( $set );
336
	}
337
338
	/**
339
	 * Set zone name
340
	 * @param string $set
341
	 */
342
	public function set_zone_name( $set ) {
343
		$this->_data['zone_name'] = wc_clean( $set );
344
	}
345
346
	/**
347
	 * Set zone order
348
	 * @param int $set
349
	 */
350
	public function set_zone_order( $set ) {
351
		$this->_data['zone_order'] = absint( $set );
352
	}
353
354
	/**
355
	 * Is passed location type valid?
356
	 * @param  string  $type
357
	 * @return boolean
358
	 */
359
	public function is_valid_location_type( $type ) {
360
		return in_array( $type, array( 'postcode', 'state', 'country', 'continent' ) );
361
	}
362
363
	/**
364
	 * Add location (state or postcode) to a zone.
365
	 * @param string $code
366
	 * @param string $type state or postcode
367
	 */
368
	public function add_location( $code, $type ) {
369
		if ( $this->is_valid_location_type( $type ) ) {
370
			if ( 'postcode' === $type ) {
371
				$code = trim( strtoupper( str_replace( chr( 226 ) . chr( 128 ) . chr( 166 ), '...', $code ) ) ); // No normalization - postcodes are matched against both normal and formatted versions to support wildcards.
372
			}
373
			$location = array(
374
				'code' => wc_clean( $code ),
375
				'type' => wc_clean( $type )
376
			);
377
			$this->_data['zone_locations'][] = (object) $location;
378
			$this->_locations_changed = true;
379
		}
380
	}
381
382
	/**
383
	 * Clear all locations for this zone.
384
	 * @param array|string $types of location to clear
385
	 */
386
	public function clear_locations( $types = array( 'postcode', 'state', 'country', 'continent' ) ) {
387
		if ( ! is_array( $types ) ) {
388
			$types = array( $types );
389
		}
390
		foreach ( $this->_data['zone_locations'] as $key => $values ) {
391
			if ( in_array( $values->type, $types ) ) {
392
				unset( $this->_data['zone_locations'][ $key ] );
393
				$this->_locations_changed = true;
394
			}
395
		}
396
	}
397
398
	/**
399
	 * Set locations
400
	 * @param array $locations Array of locations
401
	 */
402
	public function set_locations( $locations = array() ) {
403
		$this->clear_locations();
404
405
		foreach ( $locations as $location ) {
406
			$this->add_location( $location['code'], $location['type'] );
407
		}
408
409
		$this->_locations_changed = true;
410
	}
411
412
	/**
413
	 * Read location data from the database
414
	 * @param  int $zone_id
415
	 */
416
	private function read_zone_locations( $zone_id ) {
417
		global $wpdb;
418
419
		if ( $locations = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE zone_id = %d;", $zone_id ) ) ) {
420
			foreach ( $locations as $location ) {
421
				$this->add_location( $location->location_code, $location->location_type );
422
			}
423
		}
424
		$this->_locations_changed = false;
425
	}
426
427
	/**
428
	 * Save locations to the DB.
429
	 *
430
	 * This function clears old locations, then re-inserts new if any changes are found.
431
	 */
432
	private function save_locations() {
433
		if ( ! $this->_locations_changed || null === $this->get_id() ) {
434
			return false;
435
		}
436
		global $wpdb;
437
		$wpdb->delete( $wpdb->prefix . 'woocommerce_shipping_zone_locations', array( 'zone_id' => $this->get_id() ) );
438
439
		foreach ( $this->get_zone_locations() as $location ) {
440
			$wpdb->insert( $wpdb->prefix . 'woocommerce_shipping_zone_locations', array(
441
				'zone_id'       => $this->get_id(),
442
				'location_code' => $location->code,
443
				'location_type' => $location->type
444
			) );
445
		}
446
	}
447
448
	/**
449
	 * Add a shipping method to this zone.
450
	 * @param string $type shipping method type
451
	 * @return int new instance_id, 0 on failure
452
	 */
453
	public function add_shipping_method( $type ) {
454
		global $wpdb;
455
456
		if ( null === $this->get_id() ) {
457
			return 0;
458
		}
459
460
		$instance_id     = 0;
461
		$wc_shipping     = WC_Shipping::instance();
462
		$allowed_classes = $wc_shipping->get_shipping_method_class_names();
463
		$count           = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}woocommerce_shipping_zone_methods WHERE zone_id = %d", $this->get_id() ) );
464
465
		if ( in_array( $type, array_keys( $allowed_classes ) ) ) {
466
			$wpdb->insert(
467
				$wpdb->prefix . 'woocommerce_shipping_zone_methods',
468
				array(
469
					'method_id'    => $type,
470
					'zone_id'      => $this->get_id(),
471
					'method_order' => ( $count + 1 )
472
				),
473
				array(
474
					'%s',
475
					'%d',
476
					'%d'
477
				)
478
			);
479
			$instance_id = $wpdb->insert_id;
480
		}
481
482
		if ( $instance_id ) {
483
			do_action( 'woocommerce_shipping_zone_method_added', $instance_id, $type, $this->get_id() );
484
		}
485
486
		WC_Cache_Helper::get_transient_version( 'shipping', true );
487
488
		return $instance_id;
489
	}
490
}
491