91724f43c06c3c9989280e5cf9ee12cdcd7e1436
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / dig44.rb
1 #
2 # dig44.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(
6     :dig44,
7     :type => :rvalue,
8     :arity => -2,
9     :doc => <<-DOC
10     DEPRECATED: This function has been replaced in Puppet 4.5.0.
11
12     Looks up into a complex structure of arrays and hashes and returns a value
13     or the default value if nothing was found.
14
15     Key can contain slashes to describe path components. The function will go down
16     the structure and try to extract the required value.
17
18     $data = {
19       'a' => {
20         'b' => [
21           'b1',
22           'b2',
23           'b3',
24         ]
25       }
26     }
27
28     $value = dig44($data, ['a', 'b', '2'], 'not_found')
29     => $value = 'b3'
30
31     a -> first hash key
32     b -> second hash key
33     2 -> array index starting with 0
34
35     not_found -> (optional) will be returned if there is no value or the path
36     did not match. Defaults to nil.
37
38     In addition to the required "key" argument, the function accepts a default
39     argument. It will be returned if no value was found or a path component is
40     missing. And the fourth argument can set a variable path separator.
41   DOC
42   ) do |arguments|
43     # Two arguments are required
44     raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2
45
46     data, path, default = *arguments
47
48     raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") unless data.is_a?(Hash) || data.is_a?(Array)
49     raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") unless path.is_a? Array
50
51     value = path.reduce(data) do |structure, key|
52       break unless structure.is_a?(Hash) || structure.is_a?(Array)
53       if structure.is_a? Array
54         begin
55           key = Integer key
56         rescue
57           break
58         end
59       end
60       break if structure[key].nil? || structure[key] == :undef
61       structure[key]
62     end
63     value.nil? ? default : value
64   end
65 end