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

WC_Structured_Data::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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