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

WC_Structured_Data::set_structured_data()   C

Complexity

Conditions 8
Paths 13

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 8
eloc 19
c 3
b 1
f 0
nc 13
nop 0
dl 0
loc 32
rs 5.3846
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 );
34
		add_action( 'woocommerce_breadcrumb',             array( $this, 'generate_breadcrumb_data' ), 10, 1 );
35
		add_action( 'woocommerce_shop_loop',              array( $this, 'generate_product_data' ), 10 );
36
		add_action( 'woocommerce_single_product_summary', array( $this, 'generate_product_data' ), 60 );
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, 4 );
39
		// Enqueue structured data...
40
		add_action( 'woocommerce_email_order_details',    array( $this, 'enqueue_data' ), 30 );
41
		add_action( 'wp_footer',                          array( $this, 'enqueue_page_data' ) );
42
	}
43
44
	/**
45
	 * Sets `$this->_data`.
46
	 *
47
	 * @param  array $markup
0 ignored issues
show
Bug introduced by
There is no parameter named $markup. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
48
	 * @param  bool $overwrite (default: false)
49
	 * @return bool
50
	 */
51
	public function set_data( $data, $overwrite = false ) {
52
		if ( ! is_array( $data ) || ! array_key_exists( '@type', $data ) ) {
53
			return false;
54
		}
55
56
		if ( $overwrite && 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 ( isset( $this->_structured_data ) || ! $structured_data = $this->get_data() ) {
81
			return false;
82
		}
83
84
		foreach ( $structured_data as $value ) {
85
			$type = $value['@type'];
86
87
			switch ( $type ) {
88
				case 'MusicAlbum':
89
				case 'SoftwareApplication':
90
					$type = 'Product';
91
					break;
92
			}
93
94
			$structured_data[ $type ][] = $value;
95
		}
96
97
		foreach ( $structured_data as $type => $value ) {
98
			if ( count( $value ) > 1 ) {
99
				$structured_data[ $type ] = array( '@graph' => $value );
100
			} else {
101
				$structured_data[ $type ] = $value[0];
102
			}
103
104
			$structured_data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'http://schema.org/' ), $structured_data, $type, $value ) + $structured_data[ $type ];
105
		}
106
107
		$this->_structured_data = $structured_data;
108
109
		return true;
110
	}
111
112
	/**
113
	 * Gets `$this->_structured_data`.
114
	 * 
115
	 * @return array $structured_data
116
	 */
117
	public function get_structured_data() {
118
		$this->set_structured_data();
119
120
		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...
121
	}
122
123
	/**
124
	 * Sanitizes, encodes and echoes structured data.
125
	 * 
126
	 * List of the types available by default for request:
127
	 * 'Product',
128
	 * 'Review',
129
	 * 'BreadcrumbList',
130
	 * 'WebSite',
131
	 * 'Order',
132
	 *
133
	 * @param  bool|array $requested_types (default: false)
134
	 * @return bool
135
	 */
136
	public function enqueue_data( $requested_types = false ) {
137
		if ( ! $structured_data = $this->get_structured_data() ) {
138
			return false;
139
		}
140
141
		if ( $requested_types ) {
142
			if ( ! is_array( $requested_types ) ) {
143
				return false;
144
			}
145
146
			foreach ( $structured_data as $type => $value ) {
147
				foreach ( $requested_types as $requested_type ) {
148
					if ( $requested_type === $type ) {
149
						$json[] = $value;
150
					}
151
				}
152
			}
153
154
			if ( ! isset( $json ) ) {
155
				return false;
156
			}
157
		} else {
158
			foreach ( $structured_data as $value ) {
159
				$json[] = $value;
160
			}
161
		}
162
163
		if ( count( $json ) > 1 ) {
164
			$json = array( '@graph' => $json );
165
		} else {
166
			$json = $json[0];
167
		}
168
169
		$json = $this->sanitize_data( $json );
170
		
171
		// Testing/Debugging
172
		//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...
173
		echo '<script type="application/ld+json">' . wp_json_encode( $json ) . '</script>';
174
175
		return true;
176
	}
177
178
	/**
179
	 * Sanitizes, encodes and echoes structured data.
180
	 * 
181
	 * @uses   `wp_footer` action hook
182
	 * @uses   `woocommerce_email_order_details` action hook
183
	 * @return bool
184
	 */
185
	public function enqueue_page_data() {
186
		$requested_types = apply_filters( 'woocommerce_structured_data_page_requested_types', array(
187
			is_shop() && is_front_page() ? 'WebSite' : null,
188
			                               'BreadcrumbList',
189
			                               'Product',
190
			                               'Review',
191
		) );
192
193
		$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
	 * @param  bool|object $product (default: false)
219
	 * @return bool
220
	 */
221
	public function generate_product_data( $product = false ) {
222
		if ( ! $product ) {
223
			global $product;
224
		}
225
226
		if ( ! is_object( $product ) ) {
227
			return false;
228
		}
229
230
		if ( $is_multi_variation = count( $product->get_children() ) > 1 ? true : false ) {
231
			$variations = $product->get_available_variations();
232
		} else {
233
			$variations = array( null );
234
		}
235
236
		foreach ( $variations as $variation ) {
237
			$product_variation = $is_multi_variation ? wc_get_product( $variation['variation_id'] ) : $product;
238
			
239
			$markup_offers[] = array(
240
				'@type'         => 'Offer',
241
				'priceCurrency' => get_woocommerce_currency(),
242
				'price'         => $product_variation->get_price(),
243
				'availability'  => 'http://schema.org/' . $stock = ( $product_variation->is_in_stock() ? 'InStock' : 'OutOfStock' ),
244
				'sku'           => $product_variation->get_sku(),
245
				'image'         => wp_get_attachment_url( $product_variation->get_image_id() ),
246
				'description'   => $is_multi_variation ? $product_variation->get_variation_description() : '',
247
				'seller'        => array(
248
					'@type' => 'Organization',
249
					'name'  => get_bloginfo( 'name' ),
250
					'url'   => get_bloginfo( 'url' ),
251
				),
252
			);
253
		}
254
		
255
		if ( $product->is_downloadable() ) {
256
			switch ( $product->download_type ) {
257
				case 'application' :
258
					$type = "SoftwareApplication";
259
					break;
260
				case 'music' :
261
					$type = "MusicAlbum";
262
					break;
263
				default :
264
					$type = "Product";
265
					break;
266
			}
267
		} else {
268
			$type = "Product";
269
		}
270
271
		$markup['@type']       = $type;
272
		$markup['@id']         = get_the_permalink();
273
		$markup['name']        = get_the_title();
274
		$markup['description'] = get_the_excerpt();
275
		$markup['url']         = get_the_permalink();
276
		$markup['offers']      = $markup_offers;
277
		
278
		if ( $product->get_rating_count() ) {
279
			$markup['aggregateRating'] = array(
280
				'@type'       => 'AggregateRating',
281
				'ratingValue' => $product->get_average_rating(),
282
				'ratingCount' => $product->get_rating_count(),
283
				'reviewCount' => $product->get_review_count(),
284
			);
285
		}
286
287
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
288
	}
289
290
	/**
291
	 * Generates Product Review structured data.
292
	 *
293
	 * @uses   `woocommerce_review_meta` action hook
294
	 * @param  object|array $comment
295
	 * @return bool
296
	 */
297
	public function generate_product_review_data( $comment ) {
298
		$markup['@type']         = 'Review';
299
		$markup['@id']           = get_the_permalink() . '#li-comment-' . get_comment_ID();
300
		$markup['datePublished'] = get_comment_date( 'c' );
301
		$markup['description']   = get_comment_text();
302
		$markup['itemReviewed']  = array(
303
			'@type' => 'Product',
304
			'name'  => get_the_title(),
305
		);
306
		$markup['reviewRating']  = array(
307
			'@type'       => 'rating',
308
			'ratingValue' => intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ),
309
		);
310
		$markup['author']        = array(
311
			'@type' => 'Person',
312
			'name'  => get_comment_author(),
313
		);
314
		
315
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product_review', $markup, $comment ) );
316
	}
317
318
	/**
319
	 * Generates BreadcrumbList structured data.
320
	 *
321
	 * @uses   `woocommerce_breadcrumb` action hook
322
	 * @param  array $args
323
	 * @return bool
324
	 */
325
	public function generate_breadcrumb_data( $args ) {
326
		if ( empty( $args['breadcrumb'] ) ) {
327
			return;
328
		}
329
330
		$breadcrumb = $args['breadcrumb'];
331
		$position   = 1;
332
333
		foreach ( $breadcrumb as $key => $value ) {
334
			if ( ! empty( $value[1] ) && sizeof( $breadcrumb ) !== $key + 1 ) {
335
				$markup_crumbs_item = array(
336
					'@id'  => $value[1],
337
					'name' => $value[0],
338
				);
339
			} else {
340
				$markup_crumbs_item = array(
341
					'name' => $value[0]
342
				);
343
			}
344
345
			$markup_crumbs[] = array(
346
				'@type'    => 'ListItem',
347
				'position' => $position ++,
348
				'item'     => $markup_crumbs_item,
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  mixed $order
382
	 * @param  bool	$sent_to_admin (default: false)
383
	 * @param  bool	$plain_text (default: false)
384
	 * @return bool
385
	 */
386
	public function generate_email_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
387
		if ( $plain_text ) {
388
			return;
389
		}
390
391
		foreach ( $order->get_items() as $item ) {
392
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
393
				continue;
394
			}
395
396
			$product        = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
397
			$product_exists = is_object( $product );
398
			$is_visible     = $product_exists && $product->is_visible();
399
			$order_url      = $sent_to_admin ? admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) : $order->get_view_order_url();
400
401
			$markup_offers[]  = array(
402
				'@type'              => 'Offer',
403
				'price'              => $order->get_line_subtotal( $item ),
404
				'priceCurrency'      => $order->get_currency(),
405
				'priceSpecification' => array(
406
					'price'            => $order->get_line_subtotal( $item ),
407
					'priceCurrency'    => $order->get_currency(),
408
					'eligibleQuantity' => array(
409
						'@type' => 'QuantitativeValue',
410
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
411
					),
412
				),
413
				'itemOffered'        => array(
414
					'@type' => 'Product',
415
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
416
					'sku'   => $product_exists ? $product->get_sku() : '',
417
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
418
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
419
				),
420
				'seller'             => array(
421
					'@type' => 'Organization',
422
					'name'  => get_bloginfo( 'name' ),
423
					'url'   => get_bloginfo( 'url' ),
424
				),
425
			);
426
		}
427
428
		switch ( $order->get_status() ) {
429
			case 'pending':
430
				$order_status = 'http://schema.org/OrderPaymentDue';
431
				break;
432
			case 'processing':
433
				$order_status = 'http://schema.org/OrderProcessing';
434
				break;
435
			case 'on-hold':
436
				$order_status = 'http://schema.org/OrderProblem';
437
				break;
438
			case 'completed':
439
				$order_status = 'http://schema.org/OrderDelivered';
440
				break;
441
			case 'cancelled':
442
				$order_status = 'http://schema.org/OrderCancelled';
443
				break;
444
			case 'refunded':
445
				$order_status = 'http://schema.org/OrderReturned';
446
				break;
447
			case 'failed':
448
				$order_status = 'http://schema.org/OrderProblem';
449
				break;
450
		}
451
452
		$markup['@type']              = 'Order';
453
		$markup['orderStatus']        = $order_status;
454
		$markup['orderNumber']        = $order->get_order_number();
455
		$markup['orderDate']          = date( 'c', $order->get_date_created() );
456
		$markup['url']                = $order_url;
457
		$markup['acceptedOffer']      = $markup_offers;
458
		$markup['discount']           = $order->get_total_discount();
459
		$markup['discountCurrency']   = $order->get_currency();
460
		$markup['price']              = $order->get_total();
461
		$markup['priceCurrency']      = $order->get_currency();
462
		$markup['priceSpecification'] = array(
463
			'price'                 => $order->get_total(),
464
			'priceCurrency'         => $order->get_currency(),
465
			'valueAddedTaxIncluded' => true,
466
		);
467
		$markup['billingAddress']     = array(
468
			'@type'           => 'PostalAddress',
469
			'name'            => $order->get_formatted_billing_full_name(),
470
			'streetAddress'   => $order->get_billing_address_1(),
471
			'postalCode'      => $order->get_billing_postcode(),
472
			'addressLocality' => $order->get_billing_city(),
473
			'addressRegion'   => $order->get_billing_state(),
474
			'addressCountry'  => $order->get_billing_country(),
475
			'email'           => $order->get_billing_email(),
476
			'telephone'       => $order->get_billing_phone(),
477
		);
478
		$markup['customer']           = array(
479
			'@type' => 'Person',
480
			'name'  => $order->get_formatted_billing_full_name(),
481
		);
482
		$markup['merchant']           = array(
483
			'@type' => 'Organization',
484
			'name'  => get_bloginfo( 'name' ),
485
			'url'   => get_bloginfo( 'url' ),
486
		);
487
		$markup['potentialAction']    = array(
488
			'@type'  => 'ViewAction',
489
			'name'   => 'View Order',
490
			'url'    => $order_url,
491
			'target' => $order_url,
492
		);
493
494
		return $this->set_data( apply_filters( 'woocommerce_structured_data_email_order', $markup, $sent_to_admin, $order ), true );
495
	}
496
}
497