Completed
Pull Request — master (#11455)
by
unknown
13:20
created

WC_Structured_Data::sanitize_data()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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