db = $db; $this->table = $db->prefix . 'profit_engine_product_settings'; } /** * Get settings for a purchasable unit. * * @param int $product_id Purchasable-unit ID. * @return array|null */ public function get( int $product_id ): ?array { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $row = $this->db->get_row( $this->db->prepare( "SELECT * FROM {$this->table} WHERE product_id = %d", $product_id ), ARRAY_A ); return $row ?: null; } /** * Bulk-fetch settings for many units, keyed by product_id. * * @param int[] $product_ids Purchasable-unit IDs. * @return array> */ public function get_many( array $product_ids ): array { $product_ids = array_values( array_unique( array_map( 'intval', $product_ids ) ) ); if ( empty( $product_ids ) ) { return array(); } $placeholders = implode( ',', array_fill( 0, count( $product_ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared $rows = $this->db->get_results( $this->db->prepare( "SELECT * FROM {$this->table} WHERE product_id IN ({$placeholders})", $product_ids ), ARRAY_A ); $out = array(); foreach ( $rows ?: array() as $row ) { $out[ (int) $row['product_id'] ] = $row; } return $out; } /** * All enabled product settings rows (the units the merchant manages). * * @param int $limit Max rows. * @param int $offset Offset for batching. * @return array> */ public function enabled( int $limit = 500, int $offset = 0 ): array { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $rows = $this->db->get_results( $this->db->prepare( "SELECT * FROM {$this->table} WHERE enabled = 1 ORDER BY product_id ASC LIMIT %d OFFSET %d", $limit, $offset ), ARRAY_A ); return $rows ?: array(); } /** * Count enabled product settings rows. */ public function count_enabled(): int { // phpcs:ignore WordPress.DB.DirectDatabaseQuery return (int) $this->db->get_var( "SELECT COUNT(*) FROM {$this->table} WHERE enabled = 1" ); } /** * Delete a unit's settings (e.g. when the product is deleted). * * @param int $product_id Purchasable-unit ID. */ public function delete( int $product_id ): void { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->db->delete( $this->table, array( 'product_id' => $product_id ) ); } /** * Insert or update settings for a purchasable unit. * * @param int $product_id Purchasable-unit ID. * @param array $data Column data. */ public function upsert( int $product_id, array $data ): void { $data['updated_at'] = gmdate( 'Y-m-d H:i:s' ); if ( $this->get( $product_id ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->db->update( $this->table, $data, array( 'product_id' => $product_id ) ); return; } $data['product_id'] = $product_id; // phpcs:ignore WordPress.DB.DirectDatabaseQuery $this->db->insert( $this->table, $data ); } }