true, 'sku' => null, 'available' => 0, 'requested' => 0, ); } /** * Check one line. * * @param array $line Line, see evaluate(). * @return array Same shape as evaluate(). */ public static function evaluate_line( array $line ) { $sku = isset( $line['sku'] ) ? (string) $line['sku'] : ''; $requested = isset( $line['quantity'] ) ? (int) $line['quantity'] : 0; $manages = ! empty( $line['manages_stock'] ); $in_stock = ! empty( $line['in_stock'] ); $backorder = isset( $line['backorders'] ) ? (string) $line['backorders'] : 'no'; $available = isset( $line['stock_quantity'] ) && null !== $line['stock_quantity'] ? (int) $line['stock_quantity'] : 0; // Backorders on: the store accepts any quantity for this item. if ( self::backorders_allowed( $backorder ) ) { return self::ok(); } // The store does not count this item. The only signal is the flag. if ( ! $manages ) { return $in_stock ? self::ok() : self::short( $sku, 0, $requested ); } // The store counts this item. It must also not be flagged out of stock, // because a shop manager can force that flag while the count is positive. if ( ! $in_stock ) { return self::short( $sku, max( 0, $available ), $requested ); } if ( $available < $requested ) { return self::short( $sku, max( 0, $available ), $requested ); } return self::ok(); } /** * Whether a backorders setting lets the order through. * * WooCommerce stores 'no', 'notify' or 'yes'. Both 'notify' and 'yes' allow * the sale; 'notify' only adds a note for the shop manager. * * @param string $backorders Setting. * @return bool */ public static function backorders_allowed( $backorders ) { return in_array( $backorders, array( 'yes', 'notify' ), true ); } /** * Sum the requested quantity for each stock unit. * * Two order lines can resolve to the same product or variation. The gate * must compare the sum against the stock, not each line on its own. * * @param array $lines Lines with a 'stock_unit_id' and a 'quantity'. * @return array Lines, one for each stock unit, with the summed quantity. */ public static function merge_by_stock_unit( array $lines ) { $merged = array(); foreach ( $lines as $line ) { $key = isset( $line['stock_unit_id'] ) ? (string) $line['stock_unit_id'] : (string) $line['sku']; if ( isset( $merged[ $key ] ) ) { $merged[ $key ]['quantity'] += (int) $line['quantity']; continue; } $merged[ $key ] = $line; } return array_values( $merged ); } /** * Build a passing answer. * * @return array */ private static function ok() { return array( 'ok' => true, 'sku' => null, 'available' => 0, 'requested' => 0, ); } /** * Build a failing answer. * * @param string $sku SKU that is short. * @param int $available Stock. * @param int $requested Quantity asked for. * @return array */ private static function short( $sku, $available, $requested ) { return array( 'ok' => false, 'sku' => $sku, 'available' => (int) $available, 'requested' => (int) $requested, ); } }