*/ private $values; /** * @param array $values Normalised values. */ private function __construct( array $values ) { $this->values = $values; } /** * Build a line item. * * @param string $item_id Product or SKU id. * @param string $item_name Product name. * @param float $price Unit price, excluding the line discount. * @param float $quantity Units ordered. * @param array $extra Optional category, brand, variant, discount. * @return self */ public static function create( string $item_id, string $item_name, float $price, float $quantity, array $extra = array() ): self { $values = array( 'item_id' => sanitize_text_field( $item_id ), 'item_name' => sanitize_text_field( $item_name ), 'price' => round( $price, 4 ), // A zero quantity would make the line's revenue zero; ingest already defaults it to one, and // matching that here keeps the payload and the stored row telling the same story. 'quantity' => $quantity > 0 ? round( $quantity, 4 ) : 1.0, ); foreach ( array( 'category', 'brand', 'variant' ) as $key ) { if ( isset( $extra[ $key ] ) && is_scalar( $extra[ $key ] ) ) { $text = sanitize_text_field( (string) $extra[ $key ] ); if ( '' !== $text ) { $values[ $key ] = $text; } } } if ( isset( $extra['discount'] ) && is_numeric( $extra['discount'] ) ) { $discount = round( (float) $extra['discount'], 4 ); if ( $discount > 0 ) { $values['discount'] = $discount; } } return new self( $values ); } /** * The contract shape. * * @return array */ public function to_array(): array { return $this->values; } }