diff --git a/src/Integration/WPCOMProxy.php b/src/Integration/WPCOMProxy.php index 74912f1f1c..5109bbd4b7 100644 --- a/src/Integration/WPCOMProxy.php +++ b/src/Integration/WPCOMProxy.php @@ -193,7 +193,7 @@ function ( $response, $handler, $request ) { $response->set_data( array_values( $data ) ); } - $response->set_data( $this->prepare_data( $response->get_data() ) ); + $response->set_data( $this->prepare_data( $response->get_data(), $request ) ); return $response; }, 10, @@ -204,17 +204,18 @@ function ( $response, $handler, $request ) { /** * Prepares the data converting the empty arrays in objects for consistency. * - * @param array $data The response data to parse + * @param array $data The response data to parse + * @param WP_REST_Request $request The request object. * @return mixed */ - public function prepare_data( $data ) { + public function prepare_data( $data, $request ) { if ( ! is_array( $data ) ) { return $data; } - foreach ( array_keys( $data ) as $key ) { - if ( is_array( $data[ $key ] ) && empty( $data[ $key ] ) ) { - $data[ $key ] = (object) $data[ $key ]; + foreach ( $data as $key => $value ) { + if ( preg_match( '/^\/wc\/v3\/shipping\/zones\/\d+\/methods/', $request->get_route() ) && isset( $value['settings'] ) && empty( $value['settings'] ) ) { + $data[ $key ]['settings'] = (object) $value['settings']; } } diff --git a/tests/Unit/Integration/WPCOMProxyTest.php b/tests/Unit/Integration/WPCOMProxyTest.php index 80bb1667ad..8af32bf0c2 100644 --- a/tests/Unit/Integration/WPCOMProxyTest.php +++ b/tests/Unit/Integration/WPCOMProxyTest.php @@ -14,6 +14,7 @@ use Automattic\WooCommerce\GoogleListingsAndAds\Vendor\Psr\Container\ContainerInterface; use WC_Meta_Data; use WP_REST_Response; +use WP_REST_Request; /** @@ -458,13 +459,15 @@ public function test_get_settings_with_gla_syncable_param() { $this->assertArrayHasKey( 'gla_shipping_times', $response_mapped ); } - public function test_get_empty_data_as_object() { + public function test_get_empty_settings_for_shipping_zone_methods_as_object() { + $request = new WP_REST_Request( 'GET', '/wc/v3/shipping/zones/4/methods' ); + // dummy data $data = [ - 'foo' => 'bar', - 'var' => [], - 'baz' => null, - 'bool' => false, + [ + 'id' => '1', + 'settings' => [], + ], ]; $proxy = new WPCOMProxy( @@ -474,12 +477,25 @@ public function test_get_empty_data_as_object() { $this->assertEquals( [ - 'foo' => 'bar', - 'var' => (object) [], - 'baz' => null, - 'bool' => false, + [ + 'id' => '1', + 'settings' => (object) [], + ], + ], + $proxy->prepare_data( $data, $request ) + ); + + // If the request is not for shipping zone methods, the data should not be modified. + $request = new WP_REST_Request( 'GET', '/wc/v3/products' ); + + $this->assertEquals( + [ + [ + 'id' => '1', + 'settings' => [], + ], ], - $proxy->prepare_data( $data ) + $proxy->prepare_data( $data, $request ) ); } }