Update stdlib and concat to 6.1.0 both
[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     @summary
11       **DEPRECATED**: Looks up into a complex structure of arrays and hashes and returns a value
12       or the default value if nothing was found.
13
14     Key can contain slashes to describe path components. The function will go down
15     the structure and try to extract the required value.
16
17     ```
18     $data = {
19       'a' => {
20         'b' => [
21           'b1',
22           'b2',
23           'b3',
24         ]
25       }
26     }
27
28     $value = dig44($data, ['a', 'b', 2])
29     # $value = 'b3'
30
31     # with all possible options
32     $value = dig44($data, ['a', 'b', 2], 'not_found')
33     # $value = 'b3'
34
35     # using the default value
36     $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found')
37     # $value = 'not_found'
38     ```
39
40     > **Note:* **Deprecated** This function has been replaced with a built-in
41       [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of
42       Puppet 4.5.0.
43
44     @return [String] 'not_found' will be returned if nothing is found
45     @return [Any] the value that was searched for
46   DOC
47   ) do |arguments|
48     # Two arguments are required
49     raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2
50
51     data, path, default = *arguments
52
53     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)
54     raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") unless path.is_a? Array
55
56     value = path.reduce(data) do |structure, key|
57       break unless structure.is_a?(Hash) || structure.is_a?(Array)
58       if structure.is_a? Array
59         begin
60           key = Integer key
61         rescue
62           break
63         end
64       end
65       break if structure[key].nil? || structure[key] == :undef
66       structure[key]
67     end
68     value.nil? ? default : value
69   end
70 end