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

WC_Structured_Data::get_structured_data()   C

Complexity

Conditions 14
Paths 73

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 14
eloc 15
nc 73
nop 1
dl 0
loc 29
rs 5.0864
c 3
b 0
f 0

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