Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / member.rb
1 # TODO(Krzysztof Wilczynski): We need to add support for regular expression ...
2 # TODO(Krzysztof Wilczynski): Support for strings and hashes too ...
3 #
4 # member.rb
5 #
6 module Puppet::Parser::Functions
7   newfunction(:member, :type => :rvalue, :doc => <<-DOC
8     @summary
9       This function determines if a variable is a member of an array.
10
11     The variable can be a string, fixnum, or array.
12
13     > **Note**: This function does not support nested arrays. If the first argument contains
14     nested arrays, it will not recurse through them.
15
16     @example **Usage**
17       member(['a','b'], 'b') # Returns: true
18       member(['a', 'b', 'c'], ['a', 'b']) # Returns: true
19       member(['a','b'], 'c') # Returns: false
20       member(['a', 'b', 'c'], ['d', 'b']) # Returns: false
21
22     > *Note:*
23     Since Puppet 4.0.0 the same can be performed in the Puppet language.
24     For single values the operator `in` can be used:
25     `'a' in ['a', 'b']  # true`
26     For arrays by using operator `-` to compute a diff:
27     `['d', 'b'] - ['a', 'b', 'c'] == []  # false because 'd' is not subtracted`
28     `['a', 'b'] - ['a', 'b', 'c'] == []  # true because both 'a' and 'b' are subtracted`
29
30     @return
31       Returns whether the given value was a member of the array
32
33     > **Note** that since Puppet 5.2.0, the general form to test the content of an array or
34     hash is to use the built-in [`any`](https://puppet.com/docs/puppet/latest/function.html#any)
35     and [`all`](https://puppet.com/docs/puppet/latest/function.html#all) functions.
36     DOC
37              ) do |arguments|
38
39     raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
40
41     array = arguments[0]
42
43     unless array.is_a?(Array)
44       raise(Puppet::ParseError, 'member(): Requires array to work with')
45     end
46
47     unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array)
48       raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array')
49     end
50
51     item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer)
52              [arguments[1]]
53            else
54              arguments[1]
55            end
56
57     raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty?
58
59     result = (item - array).empty?
60
61     return result
62   end
63 end
64
65 # vim: set ts=2 sw=2 et :