Merge pull request #25178 from woocommerce/fix/24956-3

Raise exception when WC_Product_Variation is instantiated with the wrong ID
This commit is contained in:
Claudio Sanches 2019-12-05 17:14:07 -03:00 committed by GitHub
commit 07424c3bac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 3 deletions

View File

@ -48,10 +48,14 @@ class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT impl
$post_object = get_post( $product->get_id() );
if ( ! $post_object || ! in_array( $post_object->post_type, array( 'product', 'product_variation' ), true ) ) {
if ( ! $post_object ) {
return;
}
if ( 'product_variation' !== $post_object->post_type ) {
throw new Exception( 'Invalid product type: passed ID does not correspond to a product variation.' );
}
$product->set_props(
array(
'name' => $post_object->post_title,
@ -116,7 +120,7 @@ class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT impl
*/
public function create( &$product ) {
if ( ! $product->get_date_created() ) {
$product->set_date_created( current_time( 'timestamp', true ) );
$product->set_date_created( time() );
}
$new_title = $this->generate_product_title( $product );
@ -186,7 +190,7 @@ class WC_Product_Variation_Data_Store_CPT extends WC_Product_Data_Store_CPT impl
$product->save_meta_data();
if ( ! $product->get_date_created() ) {
$product->set_date_created( current_time( 'timestamp', true ) );
$product->set_date_created( time() );
}
$new_title = $this->generate_product_title( $product );

View File

@ -77,4 +77,18 @@ class WC_Tests_Product_Variation extends WC_Unit_Test_Case {
$this->assertEquals( 'parent', $variation->get_tax_class( 'edit' ) );
$this->assertEquals( 'zero-rate', $variation->get_tax_class( 'view' ) );
}
/**
* Test that WC_Product_Variation throws an exception
* when called with a product ID that belongs to a product
* of a different type.
*
* Ticket: https://github.com/woocommerce/woocommerce/issues/24956
*/
public function test_product_variation_should_throw_exception_when_instantiated_with_invalid_id() {
$this->expectExceptionMessage( 'Invalid product type: passed ID does not correspond to a product variation.' );
$variable_product = WC_Helper_Product::create_variation_product();
new WC_Product_Variation( $variable_product->get_id() );
}
}