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