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

WC_Structured_Data::generate_review_data()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 2
eloc 17
c 3
b 0
f 1
nc 2
nop 1
dl 0
loc 24
rs 8.9713
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    Clément Cazaud <[email protected]>
15
 */
16
class WC_Structured_Data {
17
	
18
	/**
19
	 * @var null|array $_data
20
	 */
21
	private $_data;
22
23
	/**
24
	 * Constructor.
25
	 */
26
	public function __construct() {
27
		// Generate data...
28
		add_action( 'woocommerce_before_main_content',    array( $this, 'generate_website_data' ),        30, 0 );
29
		add_action( 'woocommerce_breadcrumb',             array( $this, 'generate_breadcrumblist_data' ), 10, 1 );
30
		add_action( 'woocommerce_shop_loop',              array( $this, 'generate_product_data' ),        10, 0 );
31
		add_action( 'woocommerce_single_product_summary', array( $this, 'generate_product_data' ),        60, 0 );
32
		add_action( 'woocommerce_review_meta',            array( $this, 'generate_review_data' ),         20, 1 );
33
		add_action( 'woocommerce_email_order_details',    array( $this, 'generate_order_data' ),          20, 3 );
34
		
35
		// Output structured data...
36
		add_action( 'woocommerce_email_order_details',    array( $this, 'output_structured_data' ),       30, 0 );
37
		add_action( 'wp_footer',                          array( $this, 'output_structured_data' ),       10, 0 );
38
39
		// Filters...
40
		add_filter( 'woocommerce_structured_data_product_limit', array( $this, 'limit_product_data' ),    10, 1 );
41
	}
42
43
	/**
44
	 * Sets `$this->_data`.
45
	 *
46
	 * @param  array $data
47
	 * @param  bool  $reset (default: false)
48
	 * @return bool
49
	 */
50
	public function set_data( $data, $reset = false ) {
51
		if ( ! isset( $data['@type'] ) ) {
52
			return false;
53
		} elseif ( ! is_string( $data['@type'] ) ) {
54
			return false;
55
		}
56
57
		if ( $reset && isset( $this->_data ) ) {
58
			unset( $this->_data );
59
		}
60
		
61
		$this->_data[] = $data;
62
63
		return true;
64
	}
65
	
66
	/**
67
	 * Gets `$this->_data`.
68
	 *
69
	 * @return array
70
	 */
71
	public function get_data() {
72
		return isset( $this->_data ) ? $this->_data : array();
73
	}
74
75
	/**
76
	 * Structures and returns data.
77
	 *
78
	 * List of types available by default for specific request:
79
	 *
80
	 * 'product',
81
	 * 'review',
82
	 * 'breadcrumblist',
83
	 * 'website',
84
	 * 'order',
85
	 *
86
	 * @param  bool|array|string $requested_types (default: false)
87
	 * @return array
88
	 */
89
	public function get_structured_data( $requested_types = false ) {
90
		$data = $this->get_data();
91
92
		if ( empty( $data ) || ( $requested_types && ! is_array( $requested_types ) && ! is_string( $requested_types ) || is_null( $requested_types ) ) ) {
93
			return array();
94
		} elseif ( $requested_types && is_string( $requested_types ) ) {
95
			$requested_types = array( $requested_types );
96
		}
97
98
		// Puts together the values of same type of structured data.
99
		foreach ( $data as $value ) {
100
			$structured_data[ strtolower( $value['@type'] ) ][] = $value;
101
		}
102
103
		// Wraps the multiple values of each type of structured data inside a graph. Then adds context to each type of value.
104
		foreach ( $structured_data as $type => $value ) {
105
			$structured_data[ $type ] = count( $value ) > 1 ? array( '@graph' => $value ) : $value[0];
106
			$structured_data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'http://schema.org/' ), $structured_data, $type, $value ) + $structured_data[ $type ];
107
		}
108
109
		// If requested types, picks them up. Finally changes the associative array to an indexed one.
110
		$structured_data = $requested_types ? array_values( array_intersect_key( $structured_data, array_flip( $requested_types ) ) ) : array_values( $structured_data );
111
112
		if ( ! empty( $structured_data ) ) {
113
			$structured_data = count( $structured_data ) > 1 ?  array( '@graph' => $structured_data ) : $structured_data[0];
114
		}
115
116
		return $structured_data;
117
	}
118
119
	/**
120
	 * Sanitizes, encodes and outputs structured data.
121
	 * 
122
	 * @uses   `wp_footer` action hook
123
	 * @uses   `woocommerce_email_order_details` action hook
124
	 * @param  bool|array|string $requested_types (default: true)
125
	 * @return bool
126
	 */
127
	public function output_structured_data( $requested_types = true ) {
128
		if ( $requested_types === true ) {
129
			$requested_types = array_filter( apply_filters( 'woocommerce_structured_data_type_for_page', array(
130
				  is_shop() || is_product_category() || is_product() ? 'product'        : null,
131
				  is_shop() && is_front_page()                       ? 'website'        : null,
132
				  is_product()                                       ? 'review'         : null,
133
				! is_shop()                                          ? 'breadcrumblist' : null,
134
				                                                       'order',
135
			) ) );
136
		}
137
138
		if ( $structured_data = $this->sanitize_data( $this->get_structured_data( $requested_types ) ) ) {
139
			echo '<script type="application/ld+json">' . wp_json_encode( $structured_data ) . '</script>';
140
			
141
			return true;
142
		} else {
143
			return false;
144
		}	
145
	}
146
147
	/**
148
	 * Sanitizes data.
149
	 *
150
	 * @param  array $data
151
	 * @return array
152
	 */
153
	public function sanitize_data( $data ) {
154
		if ( ! $data || ! is_array( $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...
155
			return array();
156
		}
157
158
		foreach ( $data as $key => $value ) {
159
			$sanitized_data[ sanitize_text_field( $key ) ] = is_array( $value ) ? $this->sanitize_data( $value ) : sanitize_text_field( $value );
160
		}
161
162
		return $sanitized_data;
163
	}
164
165
	/**
166
	 * Generates, sanitizes, encodes and outputs specific structured data type.
167
	 *
168
	 * @param  string $type
169
	 * @param  mixed  $object  (default: null)
170
	 * @param  mixed  $param_1 (default: null)
171
	 * @param  mixed  $param_2 (default: null)
172
	 * @param  mixed  $param_3 (default: null)
173
	 * @return bool
174
	 */
175
	public function generate_output_structured_data( $type, $object = null, $param_1 = null, $param_2 = null, $param_3 = null ) {
176
		if ( ! is_string( $type ) ) {
177
			return false;
178
		}
179
		
180
		$generate = 'generate_' . $type . '_data';
181
182
		if ( method_exists( $this, $generate ) && $this->$generate( $object, $param_1, $param_2, $param_3 ) ) {
183
			return $this->output_structured_data( $type );
184
		} else {
185
			return false;
186
		}
187
	}
188
189
	/**
190
	 * Limit Product structured data.
191
	 *
192
	 * @param  bool $limit_data
193
	 * @return bool $limit_data
194
	 */
195
	public function limit_product_data( $limit_data ) {
0 ignored issues
show
Unused Code introduced by
The parameter $limit_data is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
196
		return $limit_data = is_product_taxonomy() || is_shop() ? true : false;
0 ignored issues
show
Unused Code introduced by
$limit_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...
197
	}
198
199
	/*
200
	|--------------------------------------------------------------------------
201
	| Generators
202
	|--------------------------------------------------------------------------
203
	|
204
	| Methods for generating specific structured data types:
205
	|
206
	| - Product
207
	| - Review
208
	| - BreadcrumbList
209
	| - WebSite
210
	| - Order
211
	|
212
	| The generated data is stored into `$this->_data`.
213
	| See the methods above for handling `$this->_data`.
214
	|
215
	*/
216
217
	/**
218
	 * Generates Product structured data.
219
	 *
220
	 * @uses   `woocommerce_single_product_summary` action hook
221
	 * @uses   `woocommerce_shop_loop` action hook
222
	 * @param  bool|object $product    (default: false)
223
	 * @param  bool        $limit_data (default: false)
224
	 * @return bool
225
	 */
226
	public function generate_product_data( $product = false, $limit_data = false ) {
227
		if ( $product === false ) {
228
			global $product;
229
		}
230
231
		if ( ! is_object( $product ) ) {
232
			return false;
233
		}
234
235
		$limit_data = apply_filters( 'woocommerce_structured_data_product_limit', $limit_data );
236
		
237
		$markup['@type']       = 'Product';
238
		$markup['@id']         = get_permalink( $product->get_id() );
239
		$markup['url']         = $markup['@id'];
240
		$markup['name']        = $product->get_title();
241
242
		if ( $limit_data ) {
243
			return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
244
		}
245
246
		if ( $is_variable = $product->is_type( 'variable' ) ) {
247
			$variations = $product->get_available_variations();
248
			
249
			foreach ( $variations as $variation ) {
250
				$product_variations[] = wc_get_product( $variation['variation_id'] );
251
			}
252
		} else {
253
			$product_variations[] = $product;
254
		}
255
256
		foreach ( $product_variations as $product_variation ) {
257
			$markup_offers[] = array(
258
				'@type'         => 'Offer',
259
				'priceCurrency' => get_woocommerce_currency(),
260
				'price'         => $product_variation->get_price(),
261
				'availability'  => 'http://schema.org/' . $stock = ( $product_variation->is_in_stock() ? 'InStock' : 'OutOfStock' ),
262
				'sku'           => $product_variation->get_sku(),
263
				'image'         => wp_get_attachment_url( $product_variation->get_image_id() ),
264
				'description'   => $is_variable ? $product_variation->get_variation_description() : '',
265
				'seller'        => array(
266
					'@type' => 'Organization',
267
					'name'  => get_bloginfo( 'name' ),
268
					'url'   => get_bloginfo( 'url' ),
269
				),
270
			);
271
		}
272
		
273
		$markup['description'] = get_the_excerpt( $product->get_id() );
274
		$markup['offers']      = $markup_offers;
275
		
276
		if ( $product->get_rating_count() ) {
277
			$markup['aggregateRating'] = array(
278
				'@type'       => 'AggregateRating',
279
				'ratingValue' => $product->get_average_rating(),
280
				'ratingCount' => $product->get_rating_count(),
281
				'reviewCount' => $product->get_review_count(),
282
			);
283
		}
284
285
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
286
	}
287
288
	/**
289
	 * Generates Review structured data.
290
	 *
291
	 * @uses   `woocommerce_review_meta` action hook
292
	 * @param  object $comment
293
	 * @return bool
294
	 */
295
	public function generate_review_data( $comment ) {
296
		if ( ! is_object( $comment ) ) {
297
			return false;
298
		}
299
300
		$markup['@type']         = 'Review';
301
		$markup['@id']           = get_comment_link( $comment->comment_ID );
302
		$markup['datePublished'] = get_comment_date( 'c', $comment->comment_ID );
303
		$markup['description']   = get_comment_text( $comment->comment_ID );
304
		$markup['itemReviewed']  = array(
305
			'@type' => 'Product',
306
			'name'  => get_the_title( $comment->post_ID ),
307
		);
308
		$markup['reviewRating']  = array(
309
			'@type'       => 'rating',
310
			'ratingValue' => get_comment_meta( $comment->comment_ID, 'rating', true ),
311
		);
312
		$markup['author']        = array(
313
			'@type' => 'Person',
314
			'name'  => get_comment_author( $comment->comment_ID ),
315
		);
316
		
317
		return $this->set_data( apply_filters( 'woocommerce_structured_data_review', $markup, $comment ) );
318
	}
319
320
	/**
321
	 * Generates BreadcrumbList structured data.
322
	 *
323
	 * @uses   `woocommerce_breadcrumb` action hook
324
	 * @param  object $breadcrumbs
325
	 * @return bool|void
326
	 */
327
	public function generate_breadcrumblist_data( $breadcrumbs ) {
328
		if ( ! is_object( $breadcrumbs ) ) {
329
			return false;
330
		} elseif ( ! $crumbs = $breadcrumbs->get_breadcrumb() ) {
331
			return;
332
		}
333
334
		foreach ( $crumbs as $key => $crumb ) {
335
			$markup_crumbs[ $key ] = array(
336
				'@type'    => 'ListItem',
337
				'position' => $key + 1,
338
				'item'     => array(
339
					'name' => $crumb[0],
340
				),
341
			);
342
343
			if ( ! empty( $crumb[1] ) && sizeof( $crumbs ) !== $key + 1 ) {
344
				$markup_crumbs[ $key ]['item'] += array( '@id' => $crumb[1] );
345
			}
346
		}
347
348
		$markup['@type']           = 'BreadcrumbList';
349
		$markup['itemListElement'] = $markup_crumbs;
350
351
		return $this->set_data( apply_filters( 'woocommerce_structured_data_breadcrumblist', $markup, $breadcrumbs ) );
352
	}
353
354
	/**
355
	 * Generates WebSite structured data.
356
	 *
357
	 * @uses  `woocommerce_before_main_content` action hook
358
	 * @return bool
359
	 */
360
	public function generate_website_data() {
361
		$markup['@type']           = 'WebSite';
362
		$markup['name']            = get_bloginfo( 'name' );
363
		$markup['url']             = get_bloginfo( 'url' );
364
		$markup['potentialAction'] = array(
365
			'@type'       => 'SearchAction',
366
			'target'      => get_bloginfo( 'url' ) . '/?s={search_term_string}&post_type=product',
367
			'query-input' => 'required name=search_term_string',
368
		);
369
370
		return $this->set_data( apply_filters( 'woocommerce_structured_data_website', $markup ) );
371
	}
372
	
373
	/**
374
	 * Generates Order structured data.
375
	 *
376
	 * @uses   `woocommerce_email_order_details` action hook
377
	 * @param  object    $order
378
	 * @param  bool	     $sent_to_admin (default: false)
379
	 * @param  bool	     $plain_text (default: false)
380
	 * @return bool|void
381
	 */
382
	public function generate_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
383
		if ( ! is_object( $order ) ) {
384
			return false;
385
		} elseif ( $plain_text ) {
386
			return;
387
		}
388
389
		foreach ( $order->get_items() as $item ) {
390
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
391
				continue;
392
			}
393
394
			$product        = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
395
			$product_exists = is_object( $product );
396
			$is_visible     = $product_exists && $product->is_visible();
397
			$order_url      = $sent_to_admin ? admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) : $order->get_view_order_url();
398
399
			$markup_offers[]  = array(
400
				'@type'              => 'Offer',
401
				'price'              => $order->get_line_subtotal( $item ),
402
				'priceCurrency'      => $order->get_currency(),
403
				'priceSpecification' => array(
404
					'price'            => $order->get_line_subtotal( $item ),
405
					'priceCurrency'    => $order->get_currency(),
406
					'eligibleQuantity' => array(
407
						'@type' => 'QuantitativeValue',
408
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
409
					),
410
				),
411
				'itemOffered'        => array(
412
					'@type' => 'Product',
413
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
414
					'sku'   => $product_exists ? $product->get_sku() : '',
415
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
416
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
417
				),
418
				'seller'             => array(
419
					'@type' => 'Organization',
420
					'name'  => get_bloginfo( 'name' ),
421
					'url'   => get_bloginfo( 'url' ),
422
				),
423
			);
424
		}
425
426
		switch ( $order->get_status() ) {
427
			case 'pending':
428
				$order_status = 'http://schema.org/OrderPaymentDue';
429
				break;
430
			case 'processing':
431
				$order_status = 'http://schema.org/OrderProcessing';
432
				break;
433
			case 'on-hold':
434
				$order_status = 'http://schema.org/OrderProblem';
435
				break;
436
			case 'completed':
437
				$order_status = 'http://schema.org/OrderDelivered';
438
				break;
439
			case 'cancelled':
440
				$order_status = 'http://schema.org/OrderCancelled';
441
				break;
442
			case 'refunded':
443
				$order_status = 'http://schema.org/OrderReturned';
444
				break;
445
			case 'failed':
446
				$order_status = 'http://schema.org/OrderProblem';
447
				break;
448
		}
449
450
		$markup['@type']              = 'Order';
451
		$markup['url']                = $order_url;
452
		$markup['orderStatus']        = $order_status;
453
		$markup['orderNumber']        = $order->get_order_number();
454
		$markup['orderDate']          = date( 'c', $order->get_date_created() );
455
		$markup['acceptedOffer']      = $markup_offers;
456
		$markup['discount']           = $order->get_total_discount();
457
		$markup['discountCurrency']   = $order->get_currency();
458
		$markup['price']              = $order->get_total();
459
		$markup['priceCurrency']      = $order->get_currency();
460
		$markup['priceSpecification'] = array(
461
			'price'                 => $order->get_total(),
462
			'priceCurrency'         => $order->get_currency(),
463
			'valueAddedTaxIncluded' => true,
464
		);
465
		$markup['billingAddress']     = array(
466
			'@type'           => 'PostalAddress',
467
			'name'            => $order->get_formatted_billing_full_name(),
468
			'streetAddress'   => $order->get_billing_address_1(),
469
			'postalCode'      => $order->get_billing_postcode(),
470
			'addressLocality' => $order->get_billing_city(),
471
			'addressRegion'   => $order->get_billing_state(),
472
			'addressCountry'  => $order->get_billing_country(),
473
			'email'           => $order->get_billing_email(),
474
			'telephone'       => $order->get_billing_phone(),
475
		);
476
		$markup['customer']           = array(
477
			'@type' => 'Person',
478
			'name'  => $order->get_formatted_billing_full_name(),
479
		);
480
		$markup['merchant']           = array(
481
			'@type' => 'Organization',
482
			'name'  => get_bloginfo( 'name' ),
483
			'url'   => get_bloginfo( 'url' ),
484
		);
485
		$markup['potentialAction']    = array(
486
			'@type'  => 'ViewAction',
487
			'name'   => 'View Order',
488
			'url'    => $order_url,
489
			'target' => $order_url,
490
		);
491
492
		return $this->set_data( apply_filters( 'woocommerce_structured_data_order', $markup, $sent_to_admin, $order ), true );
493
	}
494
}
495