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

WC_Structured_Data::get_data()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 2
eloc 2
c 3
b 1
f 0
nc 2
nop 0
dl 0
loc 3
rs 10
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 $data
48
	 * @param  bool $overwrite (default: false)
0 ignored issues
show
Bug introduced by
There is no parameter named $overwrite. 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...
49
	 * @return bool
50
	 */
51
	public function set_data( $data, $reset = false ) {
52
		if ( ! is_array( $data ) || ! array_key_exists( '@type', $data ) ) {
53
			return false;
54
		}
55
56
		if ( $reset && 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 specific request:
127
	 * 'Product',
128
	 * 'Review',
129
	 * 'BreadcrumbList',
130
	 * 'WebSite',
131
	 * 'Order',
132
	 *
133
	 * @uses   `woocommerce_email_order_details` action hook
134
	 * @param  bool|array $requested_types (default: false)
135
	 * @return bool
136
	 */
137
	public function enqueue_data( $requested_types = false ) {
138
		if ( ! $structured_data = $this->get_structured_data() ) {
139
			return false;
140
		}
141
142
		if ( $requested_types ) {
143
			if ( ! is_array( $requested_types ) ) {
144
				return false;
145
			}
146
147
			foreach ( $structured_data as $type => $value ) {
148
				foreach ( $requested_types as $requested_type ) {
149
					if ( $requested_type === $type ) {
150
						$json[] = $value;
151
					}
152
				}
153
			}
154
155
			if ( ! isset( $json ) ) {
156
				return false;
157
			}
158
		} else {
159
			foreach ( $structured_data as $value ) {
160
				$json[] = $value;
161
			}
162
		}
163
164
		if ( count( $json ) > 1 ) {
165
			$json = array( '@graph' => $json );
166
		} else {
167
			$json = $json[0];
168
		}
169
170
		if ( $json = $this->sanitize_data( $json ) ) {
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
		} else {
177
			return false;
178
		}
179
	}
180
181
	/**
182
	 * Sanitizes, encodes and echoes specific structured data type on scpecific page.
183
	 * 
184
	 * @uses   `wp_footer` action hook
185
	 * @return bool
186
	 */
187
	public function enqueue_page_data() {
188
		$requested_types = apply_filters( 'woocommerce_structured_data_page_request_types', array(
189
			is_shop() && is_front_page() ? 'WebSite' : null,
190
			                               'BreadcrumbList',
191
			                               'Product',
192
			                               'Review',
193
		) );
194
195
		return $this->enqueue_data( $requested_types );
196
	}
197
198
	/**
199
	 * Sanitizes data.
200
	 *
201
	 * @param  array $data
202
	 * @return array
203
	 */
204
	public function sanitize_data( $data ) {
205
		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...
206
			return array();
207
		}
208
209
		foreach ( $data as $key => $value ) {
210
			$sanitized_data[ sanitize_text_field( $key ) ] = is_array( $value ) ? $this->sanitize_data( $value ) : sanitize_text_field( $value );
211
		}
212
213
		return $sanitized_data;
214
	}
215
216
	/**
217
	 * Generates Product structured data.
218
	 *
219
	 * @uses   `woocommerce_single_product_summary` action hook
220
	 * @uses   `woocommerce_shop_loop` action hook
221
	 * @param  bool|object $product (default: false)
222
	 * @return bool
223
	 */
224
	public function generate_product_data( $product = false ) {
225
		if ( ! $product ) {
226
			global $product;
227
		}
228
229
		if ( ! is_object( $product ) ) {
230
			return false;
231
		}
232
233
		if ( $is_multi_variation = count( $product->get_children() ) > 1 ? true : false ) {
234
			$variations = $product->get_available_variations();
235
		} else {
236
			$variations = array( null );
237
		}
238
239
		foreach ( $variations as $variation ) {
240
			$product_variation = $is_multi_variation ? wc_get_product( $variation['variation_id'] ) : $product;
241
			
242
			$markup_offers[] = array(
243
				'@type'         => 'Offer',
244
				'priceCurrency' => get_woocommerce_currency(),
245
				'price'         => $product_variation->get_price(),
246
				'availability'  => 'http://schema.org/' . $stock = ( $product_variation->is_in_stock() ? 'InStock' : 'OutOfStock' ),
247
				'sku'           => $product_variation->get_sku(),
248
				'image'         => wp_get_attachment_url( $product_variation->get_image_id() ),
249
				'description'   => $is_multi_variation ? $product_variation->get_variation_description() : '',
250
				'seller'        => array(
251
					'@type' => 'Organization',
252
					'name'  => get_bloginfo( 'name' ),
253
					'url'   => get_bloginfo( 'url' ),
254
				),
255
			);
256
		}
257
		
258
		if ( $product->is_downloadable() ) {
259
			switch ( $product->download_type ) {
260
				case 'application' :
261
					$type = "SoftwareApplication";
262
					break;
263
				case 'music' :
264
					$type = "MusicAlbum";
265
					break;
266
				default :
267
					$type = "Product";
268
					break;
269
			}
270
		} else {
271
			$type = "Product";
272
		}
273
274
		$markup['@type']       = $type;
275
		$markup['@id']         = get_the_permalink();
276
		$markup['name']        = get_the_title();
277
		$markup['description'] = get_the_excerpt();
278
		$markup['url']         = get_the_permalink();
279
		$markup['offers']      = $markup_offers;
280
		
281
		if ( $product->get_rating_count() ) {
282
			$markup['aggregateRating'] = array(
283
				'@type'       => 'AggregateRating',
284
				'ratingValue' => $product->get_average_rating(),
285
				'ratingCount' => $product->get_rating_count(),
286
				'reviewCount' => $product->get_review_count(),
287
			);
288
		}
289
290
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product', $markup, $product ) );
291
	}
292
293
	/**
294
	 * Generates Product Review structured data.
295
	 *
296
	 * @uses   `woocommerce_review_meta` action hook
297
	 * @param  object $comment
298
	 * @return bool
299
	 */
300
	public function generate_product_review_data( $comment ) {
301
		if ( ! is_object( $comment ) ) {
302
			return false;
303
		}
304
305
		$markup['@type']         = 'Review';
306
		$markup['@id']           = get_the_permalink() . '#li-comment-' . get_comment_ID();
307
		$markup['datePublished'] = get_comment_date( 'c' );
308
		$markup['description']   = get_comment_text();
309
		$markup['itemReviewed']  = array(
310
			'@type' => 'Product',
311
			'name'  => get_the_title(),
312
		);
313
		$markup['reviewRating']  = array(
314
			'@type'       => 'rating',
315
			'ratingValue' => intval( get_comment_meta( $comment->comment_ID, 'rating', true ) ),
316
		);
317
		$markup['author']        = array(
318
			'@type' => 'Person',
319
			'name'  => get_comment_author(),
320
		);
321
		
322
		return $this->set_data( apply_filters( 'woocommerce_structured_data_product_review', $markup, $comment ) );
323
	}
324
325
	/**
326
	 * Generates BreadcrumbList structured data.
327
	 *
328
	 * @uses   `woocommerce_breadcrumb` action hook
329
	 * @param  array $breadcrumb
330
	 * @return bool|void
331
	 */
332
	public function generate_breadcrumb_data( $breadcrumb ) {
333
		if ( ! is_array( $breadcrumb ) ) {
334
			return false;
335
		}
336
		
337
		if ( empty( $breadcrumb = $breadcrumb['breadcrumb'] ) ) {
338
			return;
339
		}
340
341
		$position = 1;
342
343
		foreach ( $breadcrumb as $key => $value ) {
344
			$markup_crumbs[] = array(
345
				'@type'    => 'ListItem',
346
				'position' => $position ++,
347
				'item'     => array(
348
					'@id'  => ! empty( $value[1] ) && sizeof( $breadcrumb ) !== $key + 1 ? $value[1] : '#',
349
					'name' => $value[0],
350
				),
351
			);
352
		}
353
354
		$markup['@type']           = 'BreadcrumbList';
355
		$markup['itemListElement'] = $markup_crumbs;
356
357
		return $this->set_data( apply_filters( 'woocommerce_structured_data_breadcrumb', $markup, $breadcrumb ) );
358
	}
359
360
	/**
361
	 * Generates WebSite structured data.
362
	 *
363
	 * @uses  `woocommerce_before_main_content` action hook
364
	 * @return bool
365
	 */
366
	public function generate_website_data() {
367
		$markup['@type']           = 'WebSite';
368
		$markup['name']            = get_bloginfo( 'name' );
369
		$markup['url']             = get_bloginfo( 'url' );
370
		$markup['potentialAction'] = array(
371
			'@type'       => 'SearchAction',
372
			'target'      => get_bloginfo( 'url' ) . '/?s={search_term_string}&post_type=product',
373
			'query-input' => 'required name=search_term_string',
374
		);
375
376
		return $this->set_data( apply_filters( 'woocommerce_structured_data_website', $markup ) );
377
	}
378
	
379
	/**
380
	 * Generates Email Order structured data.
381
	 *
382
	 * @uses   `woocommerce_email_order_details` action hook
383
	 * @param  object $order
384
	 * @param  bool	$sent_to_admin (default: false)
385
	 * @param  bool	$plain_text (default: false)
386
	 * @return bool|void
387
	 */
388
	public function generate_email_order_data( $order, $sent_to_admin = false, $plain_text = false ) {
389
		if ( ! is_object( $order ) ) {
390
			return false;
391
		}
392
		
393
		if ( $plain_text ) {
394
			return;
395
		}
396
397
		foreach ( $order->get_items() as $item ) {
398
			if ( ! apply_filters( 'woocommerce_order_item_visible', true, $item ) ) {
399
				continue;
400
			}
401
402
			$product        = apply_filters( 'woocommerce_order_item_product', $order->get_product_from_item( $item ), $item );
403
			$product_exists = is_object( $product );
404
			$is_visible     = $product_exists && $product->is_visible();
405
			$order_url      = $sent_to_admin ? admin_url( 'post.php?post=' . absint( $order->id ) . '&action=edit' ) : $order->get_view_order_url();
406
407
			$markup_offers[]  = array(
408
				'@type'              => 'Offer',
409
				'price'              => $order->get_line_subtotal( $item ),
410
				'priceCurrency'      => $order->get_currency(),
411
				'priceSpecification' => array(
412
					'price'            => $order->get_line_subtotal( $item ),
413
					'priceCurrency'    => $order->get_currency(),
414
					'eligibleQuantity' => array(
415
						'@type' => 'QuantitativeValue',
416
						'value' => apply_filters( 'woocommerce_email_order_item_quantity', $item['qty'], $item ),
417
					),
418
				),
419
				'itemOffered'        => array(
420
					'@type' => 'Product',
421
					'name'  => apply_filters( 'woocommerce_order_item_name', $item['name'], $item, $is_visible ),
422
					'sku'   => $product_exists ? $product->get_sku() : '',
423
					'image' => $product_exists ? wp_get_attachment_image_url( $product->get_image_id() ) : '',
424
					'url'   => $is_visible ? get_permalink( $product->get_id() ) : get_home_url(),
425
				),
426
				'seller'             => array(
427
					'@type' => 'Organization',
428
					'name'  => get_bloginfo( 'name' ),
429
					'url'   => get_bloginfo( 'url' ),
430
				),
431
			);
432
		}
433
434
		switch ( $order->get_status() ) {
435
			case 'pending':
436
				$order_status = 'http://schema.org/OrderPaymentDue';
437
				break;
438
			case 'processing':
439
				$order_status = 'http://schema.org/OrderProcessing';
440
				break;
441
			case 'on-hold':
442
				$order_status = 'http://schema.org/OrderProblem';
443
				break;
444
			case 'completed':
445
				$order_status = 'http://schema.org/OrderDelivered';
446
				break;
447
			case 'cancelled':
448
				$order_status = 'http://schema.org/OrderCancelled';
449
				break;
450
			case 'refunded':
451
				$order_status = 'http://schema.org/OrderReturned';
452
				break;
453
			case 'failed':
454
				$order_status = 'http://schema.org/OrderProblem';
455
				break;
456
		}
457
458
		$markup['@type']              = 'Order';
459
		$markup['orderStatus']        = $order_status;
460
		$markup['orderNumber']        = $order->get_order_number();
461
		$markup['orderDate']          = date( 'c', $order->get_date_created() );
462
		$markup['url']                = $order_url;
463
		$markup['acceptedOffer']      = $markup_offers;
464
		$markup['discount']           = $order->get_total_discount();
465
		$markup['discountCurrency']   = $order->get_currency();
466
		$markup['price']              = $order->get_total();
467
		$markup['priceCurrency']      = $order->get_currency();
468
		$markup['priceSpecification'] = array(
469
			'price'                 => $order->get_total(),
470
			'priceCurrency'         => $order->get_currency(),
471
			'valueAddedTaxIncluded' => true,
472
		);
473
		$markup['billingAddress']     = array(
474
			'@type'           => 'PostalAddress',
475
			'name'            => $order->get_formatted_billing_full_name(),
476
			'streetAddress'   => $order->get_billing_address_1(),
477
			'postalCode'      => $order->get_billing_postcode(),
478
			'addressLocality' => $order->get_billing_city(),
479
			'addressRegion'   => $order->get_billing_state(),
480
			'addressCountry'  => $order->get_billing_country(),
481
			'email'           => $order->get_billing_email(),
482
			'telephone'       => $order->get_billing_phone(),
483
		);
484
		$markup['customer']           = array(
485
			'@type' => 'Person',
486
			'name'  => $order->get_formatted_billing_full_name(),
487
		);
488
		$markup['merchant']           = array(
489
			'@type' => 'Organization',
490
			'name'  => get_bloginfo( 'name' ),
491
			'url'   => get_bloginfo( 'url' ),
492
		);
493
		$markup['potentialAction']    = array(
494
			'@type'  => 'ViewAction',
495
			'name'   => 'View Order',
496
			'url'    => $order_url,
497
			'target' => $order_url,
498
		);
499
500
		return $this->set_data( apply_filters( 'woocommerce_structured_data_email_order', $markup, $sent_to_admin, $order ), true );
501
	}
502
}
503