Completed
Pull Request — master (#11455)
by
unknown
08:09
created

WC_Structured_Data::generate_email_order_data()   F

Complexity

Conditions 17
Paths 274

Size

Total Lines 114
Code Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 17
eloc 91
c 5
b 1
f 0
nc 274
nop 3
dl 0
loc 114
rs 3.6909

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if ( ! defined( 'ABSPATH' ) ) {
4
	exit; // Exit if accessed directly
5
}
6
7
/**
8
 * Structured data's handler and generator using JSON-LD format.
9
 *
10
 * @class     WC_Structured_Data
11
 * @since     2.7.0
12
 * @version   2.7.0
13
 * @package   WooCommerce/Classes
14
 * @author    Clement Cazaud <[email protected]>
15
 */
16
class WC_Structured_Data {
17
	
18
	/**
19
	 * @var null|array $_data Partially structured data from `generate_*` methods
20
	 */
21
	private $_data;
22
23
	/**
24
	 * @var null|array $_structured_data
25
	 */
26
	private $_structured_data;
27
28
	/**
29
	 * Constructor.
30
	 */
31
	public function __construct() {
32
		// Generate data...
33
		add_action( 'woocommerce_before_main_content',    array( $this, 'generate_website_data' ),        30, 0 );
34
		add_action( 'woocommerce_breadcrumb',             array( $this, 'generate_breadcrumb_data' ),     10, 1 );
35
		add_action( 'woocommerce_shop_loop',              array( $this, 'generate_product_data' ),        10, 0 );
36
		add_action( 'woocommerce_single_product_summary', array( $this, 'generate_product_data' ),        60, 0 );
37
		add_action( 'woocommerce_review_meta',            array( $this, 'generate_product_review_data' ), 20, 1 );
38
		add_action( 'woocommerce_email_order_details',    array( $this, 'generate_email_order_data' ),    20, 3 );
39
		// Enqueue structured data...
40
		add_action( 'woocommerce_email_order_details',    array( $this, 'enqueue_data' ),                 30, 0 );
41
		add_action( 'wp_footer',                          array( $this, 'enqueue_data_type_for_page' ),   10, 0 );
42
	}
43
44
	/**
45
	 * Sets `$this->_data`.
46
	 *
47
	 * @param  array $data
48
	 * @param  bool $reset (default: false)
49
	 * @return bool
50
	 */
51
	public function set_data( $data, $reset = false ) {
52
		if ( ! is_array( $data ) || ! array_key_exists( '@type', $data ) ) {
53
			return false;
54
		}
55
56
		if ( $reset && isset( $this->_data ) ) {
57
			unset( $this->_data );
58
		}
59
		
60
		$this->_data[] = $data;
61
62
		return true;
63
	}
64
	
65
	/**
66
	 * Gets `$this->_data`.
67
	 *
68
	 * @return array $data
69
	 */
70
	public function get_data() {
71
		return $data = isset( $this->_data ) ? $this->_data : array();
0 ignored issues
show
Unused Code introduced by
$data 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...
72
	}
73
74
	/**
75
	 * Sets `$this->_structured_data`.
76
	 *
77
	 * @return bool
78
	 */
79
	public function set_structured_data() {
80
		if ( empty( $this->get_data() ) ) {
81
			return false;
82
		}
83
84
		foreach ( $this->get_data() as $value ) {
85
			switch ( $type = $value['@type'] ) {
86
				case 'MusicAlbum':
87
				case 'SoftwareApplication':
88
					$type = 'Product';
89
					break;
90
			}
91
92
			$structured_data[ $type ][] = $value;
93
		}
94
95
		foreach ( $structured_data as $type => $value ) {
96
			if ( count( $value ) > 1 ) {
97
				$structured_data[ $type ] = array( '@graph' => $value );
98
			} else {
99
				$structured_data[ $type ] = $value[0];
100
			}
101
102
			$structured_data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'http://schema.org/' ), $structured_data, $type, $value ) + $structured_data[ $type ];
103
		}
104
105
		$this->_structured_data = $structured_data;
106
107
		return true;
108
	}
109
110
	/**
111
	 * Gets `$this->_structured_data`.
112
	 * 
113
	 * @return array $structured_data
114
	 */
115
	public function get_structured_data() {
116
		$this->set_structured_data();
117
118
		return $structured_data = isset( $this->_structured_data ) ? $this->_structured_data : array();
0 ignored issues
show
Unused Code introduced by
$structured_data 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...
119
	}
120
121
	/**
122
	 * Sanitizes, encodes and echoes structured data.
123
	 * 
124
	 * List of the types available by default for specific request:
125
	 * 'Product',
126
	 * 'Review',
127
	 * 'BreadcrumbList',
128
	 * 'WebSite',
129
	 * 'Order',
130
	 *
131
	 * @uses   `woocommerce_email_order_details` action hook
132
	 * @param  bool|array $requested_types (default: false)
133
	 * @return bool
134
	 */
135
	public function enqueue_data( $requested_types = false ) {
136
		if ( ! $structured_data = $this->get_structured_data() ) {
137
			return false;
138
		}
139
140
		if ( $requested_types ) {
141
			if ( ! is_array( $requested_types ) ) {
142
				return false;
143
			}
144
145
			foreach ( $structured_data as $type => $value ) {
146
				foreach ( $requested_types as $requested_type ) {
147
					if ( $requested_type === $type ) {
148
						$json[] = $value;
149
					}
150
				}
151
			}
152
153
			if ( ! isset( $json ) ) {
154
				return false;
155
			}
156
		} else {
157
			foreach ( $structured_data as $value ) {
158
				$json[] = $value;
159
			}
160
		}
161
162
		if ( count( $json ) > 1 ) {
163
			$json = array( '@graph' => $json );
164
		} else {
165
			$json = $json[0];
166
		}
167
168
		if ( $json = $this->sanitize_data( $json ) ) {
169
			// Testing/Debugging
170
			//echo json_encode( $json, JSON_UNESCAPED_SLASHES );
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...
171
			echo '<script type="application/ld+json">' . wp_json_encode( $json ) . '</script>';
172
173
			return true;
174
		}
175
		
176
		return false;
177
	}
178
179
	/**
180
	 * Sanitizes, encodes and echoes specific structured data type on scpecific page.
181
	 * 
182
	 * @uses   `wp_footer` action hook
183
	 * @return bool
184
	 */
185
	public function enqueue_data_type_for_page() {
186
		$requested_types = apply_filters( 'woocommerce_structured_data_type_for_page', array(
187
			is_shop() && is_front_page() ? 'WebSite' : null,
188
			                               'BreadcrumbList',
189
			                               'Product',
190
			                               'Review',
191
		) );
192
193
		return $this->enqueue_data( $requested_types );
194
	}
195
196
	/**
197
	 * Sanitizes data.
198
	 *
199
	 * @param  array $data
200
	 * @return array
201
	 */
202
	public function sanitize_data( $data ) {
203
		if ( ! $data ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data 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...
204
			return array();
205
		}
206
207
		foreach ( $data as $key => $value ) {
208
			$sanitized_data[ sanitize_text_field( $key ) ] = is_array( $value ) ? $this->sanitize_data( $value ) : sanitize_text_field( $value );
209
		}
210
211
		return $sanitized_data;
212
	}
213
214
	/**
215
	 * Generates Product structured data.
216
	 *
217
	 * @uses   `woocommerce_single_product_summary` action hook
218
	 * @uses   `woocommerce_shop_loop` action hook
219
	 * @param  bool|object $product (default: false)
220
	 * @return bool
221
	 */
222
	public function generate_product_data( $product = false ) {
223
		if ( ! $product ) {
224
			global $product;
225
		}
226
227
		if ( ! is_object( $product ) ) {
228
			return false;
229
		}
230
231
		if ( $is_multi_variation = count( $product->get_children() ) > 1 ? true : false ) {
232
			$variations = $product->get_available_variations();
233
		} else {
234
			$variations = array( null );
235
		}
236
237
		foreach ( $variations as $variation ) {
238
			$product_variation = $is_multi_variation ? wc_get_product( $variation['variation_id'] ) : $product;
239
			
240
			$markup_offers[] = array(
241
				'@type'         => 'Offer',
242
				'priceCurrency' => get_woocommerce_currency(),
243
				'price'         => $product_variation->get_price(),
244
				'availability'  => 'http://schema.org/' . $stock = ( $product_variation->is_in_stock() ? 'InStock' : 'OutOfStock' ),
245
				'sku'           => $product_variation->get_sku(),
246
				'image'         => wp_get_attachment_url( $product_variation->get_image_id() ),
247
				'description'   => $is_multi_variation ? $product_variation->get_variation_description() : '',
248
				'seller'        => array(
249
					'@type' => 'Organization',
250
					'name'  => get_bloginfo( 'name' ),
251
					'url'   => get_bloginfo( 'url' ),
252
				),
253
			);
254
		}
255
		
256
		if ( $product->is_downloadable() ) {
257
			switch ( $product->download_type ) {
258
				case 'application' :
259
					$type = "SoftwareApplication";
260
					break;
261
				case 'music' :
262
					$type = "MusicAlbum";
263
					break;
264
				default :
265
					$type = "Product";
266
					break;
267
			}
268
		} else {
269
			$type = "Product";
270
		}
271
272
		$markup['@type']       = $type;
273
		$markup['@id']         = get_the_permalink();
274
		$markup['name']        = get_the_title();
275
		$markup['description'] = get_the_excerpt();
276
		$markup['url']         = get_the_permalink();
277
		$markup['offers']      = $markup_offers;
278
		
279
		if ( $product->get_rating_count() ) {
280
			$markup['aggregateRating'] = array(
281
				'@type'       => 'AggregateRating',
282
				'ratingValue' => $product->get_average_rating(),
283
				'ratingCount' => $product->get_rating_count(),
284
				'reviewCount' => $product->get_review_count(),
285
			);
286
		}
287
288
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
289
	}
290
291
	/**
292
	 * Generates Product Review structured data.
293
	 *
294
	 * @uses   `woocommerce_review_meta` action hook
295
	 * @param  object $comment
296
	 * @return bool
297
	 */
298
	public function generate_product_review_data( $comment ) {
299
		if ( ! is_object( $comment ) ) {
300
			return false;
301
		}
302
303
		$markup['@type']         = 'Review';
304
		$markup['@id']           = get_the_permalink() . '#li-comment-' . get_comment_ID();
305
		$markup['datePublished'] = get_comment_date( 'c' );
306
		$markup['description']   = get_comment_text();
307
		$markup['itemReviewed']  = array(
308
			'@type' => 'Product',
309
			'name'  => get_the_title(),
310
		);
311
		$markup['reviewRating']  = array(
312
			'@type'       => 'rating',
313
			'ratingValue' => intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ),
314
		);
315
		$markup['author']        = array(
316
			'@type' => 'Person',
317
			'name'  => get_comment_author(),
318
		);
319
		
320
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product_review', $markup, $comment ) );
321
	}
322
323
	/**
324
	 * Generates BreadcrumbList structured data.
325
	 *
326
	 * @uses   `woocommerce_breadcrumb` action hook
327
	 * @param  array $breadcrumb
328
	 * @return bool|void
329
	 */
330
	public function generate_breadcrumb_data( $breadcrumb ) {
331
		if ( ! is_array( $breadcrumb ) ) {
332
			return false;
333
		}
334
		
335
		if ( empty( $breadcrumb = $breadcrumb['breadcrumb'] ) ) {
336
			return;
337
		}
338
339
		$position = 1;
340
341
		foreach ( $breadcrumb as $key => $value ) {
342
			$markup_crumbs[] = array(
343
				'@type'    => 'ListItem',
344
				'position' => $position ++,
345
				'item'     => array(
346
					'@id'  => ! empty( $value[1] ) && sizeof( $breadcrumb ) !== $key + 1 ? $value[1] : '#',
347
					'name' => $value[0],
348
				),
349
			);
350
		}
351
352
		$markup['@type']           = 'BreadcrumbList';
353
		$markup['itemListElement'] = $markup_crumbs;
354
355
		return $this->set_data( apply_filters( 'woocommerce_structured_data_breadcrumb', $markup, $breadcrumb ) );
356
	}
357
358
	/**
359
	 * Generates WebSite structured data.
360
	 *
361
	 * @uses  `woocommerce_before_main_content` action hook
362
	 * @return bool
363
	 */
364
	public function generate_website_data() {
365
		$markup['@type']           = 'WebSite';
366
		$markup['name']            = get_bloginfo( 'name' );
367
		$markup['url']             = get_bloginfo( 'url' );
368
		$markup['potentialAction'] = array(
369
			'@type'       => 'SearchAction',
370
			'target'      => get_bloginfo( 'url' ) . '/?s={search_term_string}&post_type=product',
371
			'query-input' => 'required name=search_term_string',
372
		);
373
374
		return $this->set_data( apply_filters( 'woocommerce_structured_data_website', $markup ) );
375
	}
376
	
377
	/**
378
	 * Generates Email Order structured data.
379
	 *
380
	 * @uses   `woocommerce_email_order_details` action hook
381
	 * @param  object $order
382
	 * @param  bool	$sent_to_admin (default: false)
383
	 * @param  bool	$plain_text (default: false)
384
	 * @return bool|void
385
	 */
386
	public function generate_email_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
387
		if ( ! is_object( $order ) ) {
388
			return false;
389
		}
390
		
391
		if ( $plain_text ) {
392
			return;
393
		}
394
395
		foreach ( $order->get_items() as $item ) {
396
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
397
				continue;
398
			}
399
400
			$product        = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
401
			$product_exists = is_object( $product );
402
			$is_visible     = $product_exists && $product->is_visible();
403
			$order_url      = $sent_to_admin ? admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) : $order->get_view_order_url();
404
405
			$markup_offers[]  = array(
406
				'@type'              => 'Offer',
407
				'price'              => $order->get_line_subtotal( $item ),
408
				'priceCurrency'      => $order->get_currency(),
409
				'priceSpecification' => array(
410
					'price'            => $order->get_line_subtotal( $item ),
411
					'priceCurrency'    => $order->get_currency(),
412
					'eligibleQuantity' => array(
413
						'@type' => 'QuantitativeValue',
414
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
415
					),
416
				),
417
				'itemOffered'        => array(
418
					'@type' => 'Product',
419
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
420
					'sku'   => $product_exists ? $product->get_sku() : '',
421
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
422
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
423
				),
424
				'seller'             => array(
425
					'@type' => 'Organization',
426
					'name'  => get_bloginfo( 'name' ),
427
					'url'   => get_bloginfo( 'url' ),
428
				),
429
			);
430
		}
431
432
		switch ( $order->get_status() ) {
433
			case 'pending':
434
				$order_status = 'http://schema.org/OrderPaymentDue';
435
				break;
436
			case 'processing':
437
				$order_status = 'http://schema.org/OrderProcessing';
438
				break;
439
			case 'on-hold':
440
				$order_status = 'http://schema.org/OrderProblem';
441
				break;
442
			case 'completed':
443
				$order_status = 'http://schema.org/OrderDelivered';
444
				break;
445
			case 'cancelled':
446
				$order_status = 'http://schema.org/OrderCancelled';
447
				break;
448
			case 'refunded':
449
				$order_status = 'http://schema.org/OrderReturned';
450
				break;
451
			case 'failed':
452
				$order_status = 'http://schema.org/OrderProblem';
453
				break;
454
		}
455
456
		$markup['@type']              = 'Order';
457
		$markup['orderStatus']        = $order_status;
458
		$markup['orderNumber']        = $order->get_order_number();
459
		$markup['orderDate']          = date( 'c', $order->get_date_created() );
460
		$markup['url']                = $order_url;
461
		$markup['acceptedOffer']      = $markup_offers;
462
		$markup['discount']           = $order->get_total_discount();
463
		$markup['discountCurrency']   = $order->get_currency();
464
		$markup['price']              = $order->get_total();
465
		$markup['priceCurrency']      = $order->get_currency();
466
		$markup['priceSpecification'] = array(
467
			'price'                 => $order->get_total(),
468
			'priceCurrency'         => $order->get_currency(),
469
			'valueAddedTaxIncluded' => true,
470
		);
471
		$markup['billingAddress']     = array(
472
			'@type'           => 'PostalAddress',
473
			'name'            => $order->get_formatted_billing_full_name(),
474
			'streetAddress'   => $order->get_billing_address_1(),
475
			'postalCode'      => $order->get_billing_postcode(),
476
			'addressLocality' => $order->get_billing_city(),
477
			'addressRegion'   => $order->get_billing_state(),
478
			'addressCountry'  => $order->get_billing_country(),
479
			'email'           => $order->get_billing_email(),
480
			'telephone'       => $order->get_billing_phone(),
481
		);
482
		$markup['customer']           = array(
483
			'@type' => 'Person',
484
			'name'  => $order->get_formatted_billing_full_name(),
485
		);
486
		$markup['merchant']           = array(
487
			'@type' => 'Organization',
488
			'name'  => get_bloginfo( 'name' ),
489
			'url'   => get_bloginfo( 'url' ),
490
		);
491
		$markup['potentialAction']    = array(
492
			'@type'  => 'ViewAction',
493
			'name'   => 'View Order',
494
			'url'    => $order_url,
495
			'target' => $order_url,
496
		);
497
498
		return $this->set_data( apply_filters( 'woocommerce_structured_data_email_order', $markup, $sent_to_admin, $order ), true );
499
	}
500
}
501