From 8d6cacd808f958abcba45a77aa956cc64b80918e Mon Sep 17 00:00:00 2001 From: Paul Bunkham Date: Sat, 27 Aug 2022 19:37:23 +0100 Subject: [PATCH] Metadata: Allow all metadata to be returned for an object While testing some code that was setting post metadata, I was debugging it by outputting all the metadata for a post with a call to `get_post_meta( $post_id )`. I noticed that the tests started passing but I was still getting an empty array from the `get_post_meta` call. Getting a specific key was working, which led me to look at the Metadata code here, which currently doesn't deal with the case of the key being an empty value. This change refactors the `get` function, but is probably not optimal, as we change the shape of the object's metadata using `array_reduce` on each call. It illustrates the issue, and I'm happy to optimise it if we want to go this route. --- src/Metadata.php | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/src/Metadata.php b/src/Metadata.php index e6a943a..49f7e28 100644 --- a/src/Metadata.php +++ b/src/Metadata.php @@ -70,18 +70,24 @@ public function add( $check, $object_id, $meta_key, $meta_value, $unique ) { } public function get( $check, $object_id, $meta_key, $single ) { - $check = array(); if ( isset( $this->meta[ $object_id ] ) ) { - foreach ( $this->meta[ $object_id ] as $meta ) { - if ( isset( $meta['meta_key'] ) && $meta_key === $meta['meta_key'] ) { - $check[] = maybe_unserialize( $meta['meta_value'] ); - if ( $single ) { - break; - } - } + $obj_meta = array_reduce( + $this->meta[ $object_id ], + function ( $all_meta, $meta ) { + $all_meta[ $meta['meta_key' ] ] = array_merge( $all_meta[ $meta['meta_key'] ] ?? [], [ $meta['meta_value'] ] ); + return $all_meta; + }, + ); + + if ( empty( $meta_key ) ) { + return $obj_meta; + } + + if ( isset( $obj_meta[ $meta_key ] ) ) { + return $single ? array_slice( $obj_meta[ $meta_key ], 0, 1 ) : $obj_meta[ $meta_key ]; } } - if ( empty( $check ) && $single ) { + if ( $single ) { $check = array( '' ); // Ensure an empty string is returned when meta is not found. } return $check;