prepare()'d // query is the only way to use them (see Orders\OrderBuilder, which // uses the identical pattern for order-creation idempotency). $this->lock = $lock ?? static function ( string $key ): bool { global $wpdb; return 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching }; $this->unlock = $unlock ?? static function ( string $key ): void { global $wpdb; $wpdb->query( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching }; $this->findExisting = $findExisting ?? static function ( string $posOrderId ): ?array { return ( new StockSyncRepository() )->findByPosOrderId( $posOrderId ); }; $this->recordSync = $recordSync ?? static function ( string $posOrderId, array $productUpdates ): void { ( new StockSyncRepository() )->create( $posOrderId, $productUpdates ); }; $this->applyProductStock = $applyProductStock ?? static function ( int $productId, int $quantity ): void { wc_update_product_stock( $productId, $quantity, 'set' ); }; $this->tagProductMeta = $tagProductMeta ?? static function ( int $productId, string $posOrderId ): void { $product = wc_get_product( $productId ); if ( ! $product ) { return; } $synced = (array) $product->get_meta( StockSyncBuilder::SYNCED_ORDERS_META_KEY ); $synced = array_slice( array_merge( [ $posOrderId ], $synced ), 0, StockSyncBuilder::MAX_SYNCED_ORDERS_PER_PRODUCT ); $product->update_meta_data( StockSyncBuilder::SYNCED_ORDERS_META_KEY, $synced ); $product->save(); }; } /** * @return array{pos_order_id:string, applied:bool} applied=false means * this pos_order_id was already synced — nothing was re-applied. * @throws RuntimeException if another request for the same pos_order_id * is already in progress. */ public function build( StockSyncPayload $payload ): array { $lockKey = 'akantio_pos_stock_sync:' . $payload->posOrderId(); if ( ! ( $this->lock )( $lockKey ) ) { throw new RuntimeException( 'Another stock sync for this order is already in progress.' ); } try { return $this->buildLocked( $payload ); } finally { ( $this->unlock )( $lockKey ); } } private function buildLocked( StockSyncPayload $payload ): array { $existing = ( $this->findExisting )( $payload->posOrderId() ); if ( null !== $existing ) { return [ 'pos_order_id' => $payload->posOrderId(), 'applied' => false ]; } foreach ( $payload->productUpdates() as $update ) { ( $this->applyProductStock )( $update['product_id'], $update['stock_quantity'] ); ( $this->tagProductMeta )( $update['product_id'], $payload->posOrderId() ); } ( $this->recordSync )( $payload->posOrderId(), $payload->productUpdates() ); return [ 'pos_order_id' => $payload->posOrderId(), 'applied' => true ]; } }