# frozen_string_literal: true require_relative 'user' module LeapSalesforce # Where test users are defined module Users @list = [] class << self # @return [Array] List of test users attr_accessor :list # @param [LeapSalesforce::User, Array] user Test user to add to leap salesforce def add(user) return @list << user if user.is_a? LeapSalesforce::User unless user.is_a? Array raise LeapSalesforce::UserError, "Incorrect type #{user.class} for user. Expected either " \ 'type LeapSalesforce::User or Array' end @list << User.new(*user) end # @param [Symbol, Hash, String, Regexp, LeapSalesforce::User] filter Filter to find users by # @param [Boolean] all Whether to return all users matching criteria, not just first # @return [LeapSalesforce::User, Array] A user that meets the criteria def where(filter, all: false) @all = all case filter when :default then list.first # Will then use first user defined when Hash then match_params filter when String then match_params(username: filter) when Symbol then match_params(key: filter) when Regexp then match_params(description: filter) when User then filter else raise UserError, "Unable to find user using class #{filter.class}" end end # Iterate through each user, narrowing on filter if provided def each(filter = nil) if filter where(filter, all: true).each { yield } else list.each { yield } end end # @return [LeapSalesforce::User, Array] A user that meets the criteria def match_params(hash_filter) lookup_key, lookup_value = hash_filter.first users = list.find_all { |user_queried| user_queried.match?(lookup_key, lookup_value) } if users.empty? raise UserError, "Unable to find user based on filer #{hash_filter}. " \ "Users are: #{list}" end @all ? users : users.first end # Execute block as user matching filter if that user is present # If user is not present the current user will be used # @return [Object] Result of block def execute_as_if_present(filter) raise ArgumentError, 'Pass block to :execute_as_if_present method' unless block_given? current_user = LeapSalesforce.api_user if any? filter LeapSalesforce.api_user = LeapSalesforce::Users.where filter result = yield LeapSalesforce.api_user = current_user result else LeapSalesforce.logger.warn "No user found user filter #{filter}, using '#{current_user}'" yield end end # @return [Boolean] Whether any user matches filter def any?(filter) where(filter) true rescue LeapSalesforce::UserError false end end end end