8154f3b03df6dc4f5d0ea83a05ab700d417e4906
[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     This function determines if a variable is a member of an array.
9     The variable can be a string, fixnum, or array.
10
11     *Examples:*
12
13         member(['a','b'], 'b')
14
15     Would return: true
16
17         member(['a', 'b', 'c'], ['a', 'b'])
18
19     would return: true
20
21         member(['a','b'], 'c')
22
23     Would return: false
24
25         member(['a', 'b', 'c'], ['d', 'b'])
26
27     would return: false
28
29     Note: Since Puppet 4.0.0 the same can be performed in the Puppet language. For single values
30     the operator `in` can be used:
31
32         'a' in ['a', 'b']  # true
33
34     And for arrays by using operator `-` to compute a diff:
35
36         ['d', 'b'] - ['a', 'b', 'c'] == []  # false because 'd' is not subtracted
37         ['a', 'b'] - ['a', 'b', 'c'] == []  # true because both 'a' and 'b' are subtracted
38
39     Also note that since Puppet 5.2.0 the general form of testing content of an array or hash is to use the built-in
40     `any` and `all` functions.
41     DOC
42              ) do |arguments|
43
44     raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
45
46     array = arguments[0]
47
48     unless array.is_a?(Array)
49       raise(Puppet::ParseError, 'member(): Requires array to work with')
50     end
51
52     unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array)
53       raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array')
54     end
55
56     item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer)
57              [arguments[1]]
58            else
59              arguments[1]
60            end
61
62     raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty?
63
64     result = (item - array).empty?
65
66     return result
67   end
68 end
69
70 # vim: set ts=2 sw=2 et :