agent id. */ public const OPTION = 'adafwc_key_bindings'; /** * The agent a key is bound to, or null. * * @param int $key_id WooCommerce key id. */ public function agent_for( int $key_id ): ?int { $bindings = self::all(); return $bindings[ $key_id ] ?? null; } /** * Bind a key to an agent. * * @param int $key_id WooCommerce key id. * @param int $agent_id Agent id. */ public function bind( int $key_id, int $agent_id ): void { $bindings = self::all(); $bindings[ $key_id ] = $agent_id; update_option( self::OPTION, $bindings, false ); } /** * Unbind a key. * * @param int $key_id WooCommerce key id. */ public function unbind( int $key_id ): void { $bindings = self::all(); unset( $bindings[ $key_id ] ); update_option( self::OPTION, $bindings, false ); } /** * Every binding, key_id => agent id. * * @return array */ public static function all(): array { $stored = get_option( self::OPTION, array() ); $bindings = array(); foreach ( is_array( $stored ) ? $stored : array() as $key_id => $agent_id ) { if ( is_numeric( $key_id ) && is_numeric( $agent_id ) ) { $bindings[ (int) $key_id ] = (int) $agent_id; } } return $bindings; } /** * The store's REST API keys, described: never the key or secret, only * the last characters WooCommerce itself shows. * * @return list */ public static function keys(): array { global $wpdb; $rows = $wpdb->get_results( "SELECT key_id, user_id, description, permissions, truncated_key FROM {$wpdb->prefix}woocommerce_api_keys ORDER BY key_id", ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- WooCommerce's own key table, read-only; no API lists keys. return array_values( array_map( static fn( array $row ): array => array( 'key_id' => (int) $row['key_id'], 'user_id' => (int) $row['user_id'], 'description' => (string) $row['description'], 'permissions' => (string) $row['permissions'], 'truncated_key' => (string) $row['truncated_key'], ), is_array( $rows ) ? $rows : array() ) ); } /** * One key, described, or null. * * @param int $key_id WooCommerce key id. * @return array{key_id: int, user_id: int, description: string, permissions: string, truncated_key: string}|null */ public static function key( int $key_id ): ?array { foreach ( self::keys() as $key ) { if ( $key['key_id'] === $key_id ) { return $key; } } return null; } }