= (float) $p->get_regular_price( 'edit' ) ) { throw new \InvalidArgumentException(I18n::t( 'The sale price must be lower than the regular price. Leave it blank when there is no sale.' )); } $p->set_sale_price( $value ); } $image = absint( $data['image_id'] ?? 0 ); if ( $image ) { Store::require_cap( 'upload_files' ); if ( get_post_type( $image ) !== 'attachment' || !wp_attachment_is_image( $image ) || !current_user_can( 'edit_post', $image ) ) { throw new \InvalidArgumentException(I18n::t( 'Choose an image from your media library.' )); } $p->set_image_id( $image ); } $barcode = Store::text( $data, 'barcode' ); // Only a real GTIN also becomes WooCommerce's GTIN (the Google feed publishes it); every other code, a POS or shelf code // or an ISBN-10, stays in the barcode field only (0.62 review). $digits = str_replace( '-', '', $barcode ); if ( $barcode !== '' && self::gtin( $digits ) && method_exists( $p, 'set_global_unique_id' ) ) { if ( function_exists( 'wc_get_product_id_by_global_unique_id' ) && wc_get_product_id_by_global_unique_id( $digits ) ) { throw new \InvalidArgumentException(I18n::t( 'This GTIN is already used by another product.' )); } $p->set_global_unique_id( $digits ); } } /** The barcode as a GTIN (digits only) when it is a valid one, otherwise ''. */ public static function as_gtin( string $barcode ) : string { $digits = str_replace( '-', '', $barcode ); return ( $barcode !== '' && self::gtin( $digits ) ? $digits : '' ); } /** A GTIN-8, -12, -13 or -14 with a correct check digit, outside the ranges shops number their own goods with. */ private static function gtin( string $digits ) : bool { if ( !preg_match( '/^(?:\\d{8}|\\d{12,14})$/D', $digits ) ) { return false; } $len = strlen( $digits ); if ( $len === 13 && $digits[0] === '2' || $len === 12 && in_array( $digits[0], array('2', '4'), true ) || $len === 8 && in_array( $digits[0], array('0', '2'), true ) || $len === 14 && $digits[1] === '2' ) { return false; } $sum = 0; for ($i = $len - 2, $w = 3; $i >= 0; $i--, $w = 4 - $w) { $sum += (int) $digits[$i] * $w; } return (10 - $sum % 10) % 10 === (int) $digits[$len - 1]; } public static function log( \WC_Product $p, float $qty ) : void { if ( !$qty ) { return; } } }