ArrayUtil.php
1 year ago
CallbackUtil.php
5 months ago
DiscountsUtil.php
2 years ago
FeaturesUtil.php
5 months ago
I18nUtil.php
3 years ago
LoggingUtil.php
1 year ago
MetaDataUtil.php
2 months ago
NumberUtil.php
11 months ago
OrderUtil.php
7 months ago
PluginUtil.php
4 weeks ago
RestApiUtil.php
7 months ago
ShippingUtil.php
1 year ago
StringUtil.php
2 years ago
TimeUtil.php
2 years ago
MetaDataUtil.php
65 lines
| 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 |