Completed
Pull Request — master (#11455)
by
unknown
11:57
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 8
Bugs 1 Features 1
Metric Value
cc 14
eloc 15
nc 73
nop 1
dl 0
loc 29
rs 5.0864
c 8
b 1
f 1

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
40
	/**
41
	 * Sets `$this->_data`.
42
	 *
43
	 * @param  array $data
44
	 * @param  bool  $reset (default: false)
45
	 * @return bool
46
	 */
47
	public function set_data( $data, $reset = false ) {
48
		if ( ! isset( $data['@type'] ) ) {
49
			return false;
50
		} elseif ( ! is_string( $data['@type'] ) ) {
51
			return false;
52
		}
53
54
		if ( $reset && isset( $this->_data ) ) {
55
			unset( $this->_data );
56
		}
57
		
58
		$this->_data[] = $data;
59
60
		return true;
61
	}
62
	
63
	/**
64
	 * Gets `$this->_data`.
65
	 *
66
	 * @return array $data
67
	 */
68
	public function get_data() {
69
		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...
70
	}
71
72
	/**
73
	 * Structures and returns data.
74
	 *
75
	 * List of types available by default for specific request:
76
	 *
77
	 * 'product',
78
	 * 'review',
79
	 * 'breadcrumblist',
80
	 * 'website',
81
	 * 'order',
82
	 *
83
	 * @param  bool|array|string $requested_types (default: false)
84
	 * @return array
85
	 */
86
	public function get_structured_data( $requested_types = false ) {
87
		$data = $this->get_data();
88
89
		if ( empty( $data ) || ( $requested_types && ! is_array( $requested_types ) && ! is_string( $requested_types ) || is_null( $requested_types ) ) ) {
90
			return array();
91
		} elseif ( $requested_types && is_string( $requested_types ) ) {
92
			$requested_types = array( $requested_types );
93
		}
94
95
		// Puts together the values of same type of structured data.
96
		foreach ( $data as $value ) {
97
			$structured_data[ strtolower( $value['@type'] ) ][] = $value;
98
		}
99
100
		// Wraps the multiple values of each type of structured data inside a graph. Then adds context for each type of value.
101
		foreach ( $structured_data as $type => $value ) {
102
			$structured_data[ $type ] = count( $value ) > 1 ? array( '@graph' => $value ) : $value[0];
103
			$structured_data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'http://schema.org/' ), $structured_data, $type, $value ) + $structured_data[ $type ];
104
		}
105
106
		// If requested types, picks them up. Finally changes the associative array into an indexed one.
107
		$structured_data = $requested_types ? array_values( array_intersect_key( $structured_data, array_flip( $requested_types ) ) ) : array_values( $structured_data );
108
109
		if ( ! empty( $structured_data ) ) {
110
			$structured_data = count( $structured_data ) > 1 ?  array( '@graph' => $structured_data ) : $structured_data[0];
111
		}
112
113
		return $structured_data;
114
	}
115
116
	/**
117
	 * Sanitizes, encodes and outputs structured data.
118
	 * 
119
	 * @uses   `wp_footer` action hook
120
	 * @uses   `woocommerce_email_order_details` action hook
121
	 * @param  bool|array|string $requested_types (default: true)
122
	 * @return bool
123
	 */
124
	public function output_structured_data( $requested_types = true ) {
125
		if ( $requested_types === true ) {
126
			$requested_types = array_filter( apply_filters( 'woocommerce_structured_data_type_for_page', array(
127
				  is_shop() || is_product_category() || is_product() ? 'product'        : null,
128
				  is_shop() && is_front_page()                       ? 'website'        : null,
129
				  is_product()                                       ? 'review'         : null,
130
				! is_shop()                                          ? 'breadcrumblist' : null,
131
				                                                       'order',
132
			) ) );
133
		}
134
135
		if ( $structured_data = $this->sanitize_data( $this->get_structured_data( $requested_types ) ) ) {
136
			echo '<script type="application/ld+json">' . wp_json_encode( $structured_data ) . '</script>';
137
			
138
			return true;
139
		} else {
140
			return false;
141
		}	
142
	}
143
144
	/**
145
	 * Sanitizes data.
146
	 *
147
	 * @param  array $data
148
	 * @return array
149
	 */
150
	public function sanitize_data( $data ) {
151
		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...
152
			return array();
153
		}
154
155
		foreach ( $data as $key => $value ) {
156
			$sanitized_data[ sanitize_text_field( $key ) ] = is_array( $value ) ? $this->sanitize_data( $value ) : sanitize_text_field( $value );
157
		}
158
159
		return $sanitized_data;
160
	}
161
162
	/**
163
	 * Generates, sanitizes, encodes and outputs specific structured data type.
164
	 *
165
	 * @param  string $type
166
	 * @param  mixed  $object  (default: null)
167
	 * @param  mixed  $param_1 (default: null)
168
	 * @param  mixed  $param_2 (default: null)
169
	 * @param  mixed  $param_3 (default: null)
170
	 * @return bool
171
	 */
172
	public function generate_output_structured_data( $type, $object = null, $param_1 = null, $param_2 = null, $param_3 = null ) {
173
		if ( ! is_string( $type ) ) {
174
			return false;
175
		}
176
		
177
		$generate = 'generate_' . $type . '_data';
178
179
		if ( method_exists( $this, $generate ) && $this->$generate( $object, $param_1, $param_2, $param_3 ) ) {
180
			return $this->output_structured_data( $type );
181
		} else {
182
			return false;
183
		}
184
	}
185
186
	/*
187
	|--------------------------------------------------------------------------
188
	| Generators
189
	|--------------------------------------------------------------------------
190
	|
191
	| Methods for generating specific structured data types:
192
	|
193
	| - Product
194
	| - Review
195
	| - BreadcrumbList
196
	| - WebSite
197
	| - Order
198
	|
199
	| The generated data is stored into `$this->_data`.
200
	| See the methods above for handling `$this->_data`.
201
	|
202
	*/
203
204
	/**
205
	 * Generates Product structured data.
206
	 *
207
	 * @uses   `woocommerce_single_product_summary` action hook
208
	 * @uses   `woocommerce_shop_loop` action hook
209
	 * @param  bool|object $product (default: false)
210
	 * @return bool
211
	 */
212
	public function generate_product_data( $product = false ) {
213
		if ( $product === false ) {
214
			global $product;
215
		}
216
217
		if ( ! is_object( $product ) ) {
218
			return false;
219
		}
220
221
		$variations = $product->is_type( 'variable' ) ? $product->get_available_variations() : array( $product );
222
223
		foreach ( $variations as $variation ) {
224
			$product_variation = count( $variations ) > 1 ? wc_get_product( $variation['variation_id'] ) : $variation;
225
			
226
			$markup_offers[] = array(
227
				'@type'         => 'Offer',
228
				'priceCurrency' => get_woocommerce_currency(),
229
				'price'         => $product_variation->get_price(),
230
				'availability'  => 'http://schema.org/' . $stock = ( $product_variation->is_in_stock() ? 'InStock' : 'OutOfStock' ),
231
				'sku'           => $product_variation->get_sku(),
232
				'image'         => wp_get_attachment_url( $product_variation->get_image_id() ),
233
				'description'   => count( $variations ) > 1 ? $product_variation->get_variation_description() : '',
234
				'seller'        => array(
235
					'@type' => 'Organization',
236
					'name'  => get_bloginfo( 'name' ),
237
					'url'   => get_bloginfo( 'url' ),
238
				),
239
			);
240
		}
241
		
242
		$markup['@type']       = 'Product';
243
		$markup['@id']         = get_permalink( $product->get_id() );
244
		$markup['url']         = get_permalink( $product->get_id() );
245
		$markup['name']        = $product->get_title();
246
		$markup['image']       = wp_get_attachment_url( $product->get_image_id() );
247
		$markup['description'] = get_the_excerpt( $product->get_id() );
248
		$markup['offers']      = $markup_offers;
249
		
250
		if ( $product->get_rating_count() ) {
251
			$markup['aggregateRating'] = array(
252
				'@type'       => 'AggregateRating',
253
				'ratingValue' => $product->get_average_rating(),
254
				'ratingCount' => $product->get_rating_count(),
255
				'reviewCount' => $product->get_review_count(),
256
			);
257
		}
258
259
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
260
	}
261
262
	/**
263
	 * Generates Review structured data.
264
	 *
265
	 * @uses   `woocommerce_review_meta` action hook
266
	 * @param  object $comment
267
	 * @return bool
268
	 */
269
	public function generate_review_data( $comment ) {
270
		if ( ! is_object( $comment ) ) {
271
			return false;
272
		}
273
274
		$markup['@type']         = 'Review';
275
		$markup['@id']           = get_comment_link( $comment->comment_ID );
276
		$markup['datePublished'] = get_comment_date( 'c', $comment->comment_ID );
277
		$markup['description']   = get_comment_text( $comment->comment_ID );
278
		$markup['itemReviewed']  = array(
279
			'@type' => 'Product',
280
			'name'  => get_the_title( $comment->post_ID ),
281
		);
282
		$markup['reviewRating']  = array(
283
			'@type'       => 'rating',
284
			'ratingValue' => get_comment_meta( $comment->comment_ID, 'rating', true ),
285
		);
286
		$markup['author']        = array(
287
			'@type' => 'Person',
288
			'name'  => get_comment_author( $comment->comment_ID ),
289
		);
290
		
291
		return $this->set_data( apply_filters( 'woocommerce_structured_data_review', $markup, $comment ) );
292
	}
293
294
	/**
295
	 * Generates BreadcrumbList structured data.
296
	 *
297
	 * @uses   `woocommerce_breadcrumb` action hook
298
	 * @param  array $breadcrumb
299
	 * @return bool|void
300
	 */
301
	public function generate_breadcrumblist_data( $breadcrumb ) {
302
		if ( ! is_array( $breadcrumb ) ) {
303
			return false;
304
		}
305
306
		if ( isset( $breadcrumb['breadcrumb'] ) ) {
307
			$breadcrumb = $breadcrumb['breadcrumb'];
308
		}
309
310
		if ( empty( $breadcrumb ) ) {
311
			return;
312
		}
313
314
		$position = 1;
315
316
		foreach ( $breadcrumb as $key => $crumb ) {
317
			$markup_crumbs[ $key ] = array(
318
				'@type'    => 'ListItem',
319
				'position' => $position ++,
320
				'item'     => array(
321
					'name' => $crumb[0],
322
				),
323
			);
324
325
			if ( ! empty( $crumb[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
326
				$markup_crumbs[ $key ]['item'] += array( '@id' => $crumb[1] );
327
			}
328
		}
329
330
		$markup['@type']           = 'BreadcrumbList';
331
		$markup['itemListElement'] = $markup_crumbs;
332
333
		return $this->set_data( apply_filters( 'woocommerce_structured_data_breadcrumblist', $markup, $breadcrumb ) );
334
	}
335
336
	/**
337
	 * Generates WebSite structured data.
338
	 *
339
	 * @uses  `woocommerce_before_main_content` action hook
340
	 * @return bool
341
	 */
342
	public function generate_website_data() {
343
		$markup['@type']           = 'WebSite';
344
		$markup['name']            = get_bloginfo( 'name' );
345
		$markup['url']             = get_bloginfo( 'url' );
346
		$markup['potentialAction'] = array(
347
			'@type'       => 'SearchAction',
348
			'target'      => get_bloginfo( 'url' ) . '/?s={search_term_string}&post_type=product',
349
			'query-input' => 'required name=search_term_string',
350
		);
351
352
		return $this->set_data( apply_filters( 'woocommerce_structured_data_website', $markup ) );
353
	}
354
	
355
	/**
356
	 * Generates Order structured data.
357
	 *
358
	 * @uses   `woocommerce_email_order_details` action hook
359
	 * @param  object    $order
360
	 * @param  bool	     $sent_to_admin (default: false)
361
	 * @param  bool	     $plain_text (default: false)
362
	 * @return bool|void
363
	 */
364
	public function generate_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
365
		if ( ! is_object( $order ) ) {
366
			return false;
367
		}
368
		
369
		if ( $plain_text ) {
370
			return;
371
		}
372
373
		foreach ( $order->get_items() as $item ) {
374
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
375
				continue;
376
			}
377
378
			$product        = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
379
			$product_exists = is_object( $product );
380
			$is_visible     = $product_exists && $product->is_visible();
381
			$order_url      = $sent_to_admin ? admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) : $order->get_view_order_url();
382
383
			$markup_offers[]  = array(
384
				'@type'              => 'Offer',
385
				'price'              => $order->get_line_subtotal( $item ),
386
				'priceCurrency'      => $order->get_currency(),
387
				'priceSpecification' => array(
388
					'price'            => $order->get_line_subtotal( $item ),
389
					'priceCurrency'    => $order->get_currency(),
390
					'eligibleQuantity' => array(
391
						'@type' => 'QuantitativeValue',
392
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
393
					),
394
				),
395
				'itemOffered'        => array(
396
					'@type' => 'Product',
397
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
398
					'sku'   => $product_exists ? $product->get_sku() : '',
399
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
400
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
401
				),
402
				'seller'             => array(
403
					'@type' => 'Organization',
404
					'name'  => get_bloginfo( 'name' ),
405
					'url'   => get_bloginfo( 'url' ),
406
				),
407
			);
408
		}
409
410
		switch ( $order->get_status() ) {
411
			case 'pending':
412
				$order_status = 'http://schema.org/OrderPaymentDue';
413
				break;
414
			case 'processing':
415
				$order_status = 'http://schema.org/OrderProcessing';
416
				break;
417
			case 'on-hold':
418
				$order_status = 'http://schema.org/OrderProblem';
419
				break;
420
			case 'completed':
421
				$order_status = 'http://schema.org/OrderDelivered';
422
				break;
423
			case 'cancelled':
424
				$order_status = 'http://schema.org/OrderCancelled';
425
				break;
426
			case 'refunded':
427
				$order_status = 'http://schema.org/OrderReturned';
428
				break;
429
			case 'failed':
430
				$order_status = 'http://schema.org/OrderProblem';
431
				break;
432
		}
433
434
		$markup['@type']              = 'Order';
435
		$markup['url']                = $order_url;
436
		$markup['orderStatus']        = $order_status;
437
		$markup['orderNumber']        = $order->get_order_number();
438
		$markup['orderDate']          = date( 'c', $order->get_date_created() );
439
		$markup['acceptedOffer']      = $markup_offers;
440
		$markup['discount']           = $order->get_total_discount();
441
		$markup['discountCurrency']   = $order->get_currency();
442
		$markup['price']              = $order->get_total();
443
		$markup['priceCurrency']      = $order->get_currency();
444
		$markup['priceSpecification'] = array(
445
			'price'                 => $order->get_total(),
446
			'priceCurrency'         => $order->get_currency(),
447
			'valueAddedTaxIncluded' => true,
448
		);
449
		$markup['billingAddress']     = array(
450
			'@type'           => 'PostalAddress',
451
			'name'            => $order->get_formatted_billing_full_name(),
452
			'streetAddress'   => $order->get_billing_address_1(),
453
			'postalCode'      => $order->get_billing_postcode(),
454
			'addressLocality' => $order->get_billing_city(),
455
			'addressRegion'   => $order->get_billing_state(),
456
			'addressCountry'  => $order->get_billing_country(),
457
			'email'           => $order->get_billing_email(),
458
			'telephone'       => $order->get_billing_phone(),
459
		);
460
		$markup['customer']           = array(
461
			'@type' => 'Person',
462
			'name'  => $order->get_formatted_billing_full_name(),
463
		);
464
		$markup['merchant']           = array(
465
			'@type' => 'Organization',
466
			'name'  => get_bloginfo( 'name' ),
467
			'url'   => get_bloginfo( 'url' ),
468
		);
469
		$markup['potentialAction']    = array(
470
			'@type'  => 'ViewAction',
471
			'name'   => 'View Order',
472
			'url'    => $order_url,
473
			'target' => $order_url,
474
		);
475
476
		return $this->set_data( apply_filters( 'woocommerce_structured_data_order', $markup, $sent_to_admin, $order ), true );
477
	}
478
}
479