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

WC_Structured_Data::generate_breadcrumb_data()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 5
eloc 20
c 3
b 1
f 0
nc 4
nop 1
dl 0
loc 32
rs 8.439
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_shop_data' ), 30 );
34
		add_action( 'woocommerce_breadcrumb',             array( $this, 'generate_breadcrumb_data' ), 10, 1 );
35
		add_action( 'woocommerce_before_shop_loop_item',  array( $this, 'generate_product_category_data' ), 20 );
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_data' ) );
42
	}
43
44
	/**
45
	 * Sets `$this->_data`.
46
	 *
47
	 * @param  array $json
48
	 * @param  bool  $overwrite (default: false)
49
	 * @return bool
50
	 */
51
	public function set_data( $json, $overwrite = false ) {
52
		if ( ! is_array( $json ) || ! array_key_exists( '@type', $json ) ) {
53
			return false;
54
		}
55
56
		if ( $overwrite && isset( $this->_data ) ) {
57
			unset( $this->_data );
58
		}
59
		
60
		$this->_data[] = $json;
61
62
		return true;
63
	}
64
	
65
	/**
66
	 * Gets `$this->_data`.
67
	 *
68
	 * @return array $data
69
	 */
70
	public function get_data() {
71
		$data = isset( $this->_data ) ? $this->_data : array();
72
			
73
		return $data;
74
	}
75
76
	/**
77
	 * Sets `$this->_structured_data`.
78
	 *
79
	 * @return bool
80
	 */
81
	public function set_structured_data() {
82
		if ( ! $this->get_data() ) {
83
			return false;
84
		}
85
86
		foreach ( $this->get_data() as $value ) {
87
			$type = $value['@type'];
88
89
			switch ( $type ) {
90
				case 'MusicAlbum':
91
				case 'SoftwareApplication':
92
					$type = 'Product';
93
					break;
94
			}
95
96
			$data[ $type ][] = $value;
97
		}
98
99
		foreach ( $data as $type => $value ) {
100
			if ( count( $value ) > 1 ) {
101
				$data[ $type ] = array( '@graph' => $value );
102
			} else {
103
				$data[ $type ] = $value[0];
104
			}
105
106
			$data[ $type ] = apply_filters( 'woocommerce_structured_data_context', array( '@context' => 'http://schema.org/' ), $data, $type, $value ) + $data[ $type ];
107
		}
108
109
		$this->_structured_data = $data;
110
111
		return true;
112
	}
113
114
	/**
115
	 * Gets `$this->_structured_data`.
116
	 * 
117
	 * List of the types available by default for request:
118
	 * 'Product',
119
	 * 'Review',
120
	 * 'BreadcrumbList',
121
	 * 'WebSite',
122
	 * 'Order',
123
	 *
124
	 * @param  bool|array $requested_types (default: false)
125
	 * @return array
126
	 */
127
	public function get_structured_data( $requested_types = false ) {
128
		if ( ! $this->set_structured_data() ) {
129
			return array();
130
		}
131
132
		if ( $requested_types ) {
133
			if ( ! is_array( $requested_types ) ) {
134
				return array();
135
			}
136
137
			foreach ( $this->_structured_data as $type => $value ) {
0 ignored issues
show
Bug introduced by
The expression $this->_structured_data of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
138
				foreach ( $requested_types as $requested_type ) {
139
					if ( $requested_type === $type ) {
140
						$structured_data[] = $value;
141
					}
142
				}
143
			}
144
145
			if ( ! isset( $structured_data ) ) {
146
				return array();
147
			}
148
		} else {
149
			foreach ( $this->_structured_data as $value ) {
0 ignored issues
show
Bug introduced by
The expression $this->_structured_data of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

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