'orders', 'invoice' => 'invoices', 'service' => 'services', 'domain' => 'domains', 'payment' => 'payments', ); /** * Cache group. */ const CACHE_GROUP = 'hostkhata_ownership'; /** * Database object. * * @var wpdb */ private $wpdb; /** * Constructor. * * @param wpdb $wpdb WordPress database object. */ public function __construct( wpdb $wpdb ) { $this->wpdb = $wpdb; } /** * Customer id of a WordPress user, or 0 when the user is not a customer. * * @since 0.1.0 * * @param int $user_id WordPress user id. * @return int */ public function customer_id_for_user( int $user_id ): int { if ( $user_id < 1 ) { return 0; } $cache_key = 'user_' . $user_id; $cached = wp_cache_get( $cache_key, self::CACHE_GROUP ); if ( false !== $cached ) { return (int) $cached; } $table = Tables::name( 'customers' ); $query = $this->wpdb->prepare( "SELECT id FROM {$table} WHERE user_id = %d", $user_id ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name comes from the Tables whitelist. $id = (int) $this->wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Prepared on the previous line; result cached below. wp_cache_set( $cache_key, $id, self::CACHE_GROUP, 300 ); return $id; } /** * Forgets the cached customer id of a user. Call after a customer is created or deleted. * * @since 0.1.0 * * @param int $user_id WordPress user id. * @return void */ public function forget_user( int $user_id ): void { wp_cache_delete( 'user_' . $user_id, self::CACHE_GROUP ); } /** * Customer id that owns an object, or 0 when the object does not exist or the type is unknown. * * @since 0.1.0 * * @param string $type Object type, one of the keys of OWNED_TABLES. * @param int $id Object id. * @return int */ public function owner_customer_id( string $type, int $id ): int { if ( ! isset( self::OWNED_TABLES[ $type ] ) || $id < 1 ) { return 0; } $table = Tables::name( self::OWNED_TABLES[ $type ] ); $query = $this->wpdb->prepare( "SELECT customer_id FROM {$table} WHERE id = %d", $id ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Table name comes from the OWNED_TABLES whitelist. return (int) $this->wpdb->get_var( $query ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared,PluginCheck.Security.DirectDB.UnescapedDBParameter -- Prepared on the previous line; ownership must never be served stale. } }