PluginProbe
WooCommerce / 11.1.0-rc.2
WooCommerce v11.1.0-rc.2
11.1.0 11.1.0-rc.2 11.1.0-rc.1 11.1.0-beta.2 11.1.0-beta.1 11.0.1 11.0.0 11.0.0-rc.3 11.0.0-rc.2 11.0.0-rc.1 11.0.0-beta.2 11.0.0-beta.1 10.9.4 10.9.3 10.9.2 10.9.1 10.9.0 10.9.0-rc.1 10.9.0-beta.2 10.9.0-beta.1 10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 All 648 releases
woocommerce / src / Utilities / MetaDataUtil.php
MetaDataUtil.php
65 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 declare( strict_types = 1 );
3
4 namespace Automattic\WooCommerce\Utilities;
5
6 use WC_Data;
7
8 /**
9 * Utility methods for handling meta data in REST API requests.
10 *
11 * @since 10.8.0
12 */
13 class MetaDataUtil {
14
15 /**
16 * Normalize and process meta data entries from a REST API request.
17 *
18 * Skips entries without a key, applies defaults for missing 'value' and 'id'
19 * fields, then calls update_meta_data on the given WC_Data object
20 * for each valid entry.
21 *
22 * @since 10.8.0
23 *
24 * @param mixed $meta_data Raw meta data from the request (non-array values are ignored).
25 * @param WC_Data $target A WC_Data object to call update_meta_data on.
26 * @param mixed $default_id Default value for 'id' when not provided (default '').
27 */
28 public static function update( $meta_data, WC_Data $target, $default_id = '' ): void {
29 if ( ! is_array( $meta_data ) ) {
30 return;
31 }
32
33 foreach ( self::normalize( $meta_data, $default_id ) as $meta ) {
34 $target->update_meta_data( $meta['key'], $meta['value'], $meta['id'] );
35 }
36 }
37
38 /**
39 * Normalize an array of raw meta data entries from a REST API request.
40 *
41 * Filters out entries without a key and applies default values for
42 * missing 'value' and 'id' fields. Each returned entry is guaranteed
43 * to have 'key', 'value', and 'id' set.
44 *
45 * @since 10.8.0
46 *
47 * @param array $meta_data Raw meta data array from the request.
48 * @param mixed $default_id Default value for 'id' when not provided (default '').
49 * @return array[] Normalized meta data entries.
50 */
51 public static function normalize( array $meta_data, $default_id = '' ): array {
52 $normalized = array();
53 foreach ( $meta_data as $meta ) {
54 if ( is_array( $meta ) && isset( $meta['key'] ) ) {
55 $normalized[] = array(
56 'key' => $meta['key'],
57 'value' => $meta['value'] ?? null,
58 'id' => $meta['id'] ?? $default_id,
59 );
60 }
61 }
62 return $normalized;
63 }
64 }
65