Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / parser / functions / try_get_value.rb
1 #
2 # try_get_value.rb
3 #
4 module Puppet::Parser::Functions
5   newfunction(
6     :try_get_value,
7     :type => :rvalue,
8     :arity => -2,
9     :doc => <<-DOC
10       @summary
11         **DEPRECATED:** this function is deprecated, please use dig() instead.
12
13       @return
14         Looks up into a complex structure of arrays and hashes and returns a value
15         or the default value if nothing was found.
16
17       Key can contain slashes to describe path components. The function will go down
18       the structure and try to extract the required value.
19       ``
20       $data = {
21         'a' => {
22           'b' => [
23             'b1',
24             'b2',
25             'b3',
26           ]
27         }
28       }
29
30       $value = try_get_value($data, 'a/b/2', 'not_found', '/')
31       => $value = 'b3'
32       ```
33       ```
34       a -> first hash key
35       b -> second hash key
36       2 -> array index starting with 0
37
38       not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil.
39       / -> (optional) path delimiter. Defaults to '/'.
40       ```
41
42       In addition to the required "key" argument, "try_get_value" accepts default
43       argument. It will be returned if no value was found or a path component is
44       missing. And the fourth argument can set a variable path separator.
45     DOC
46   ) do |args|
47     warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.')
48     data = args[0]
49     path = args[1] || ''
50     default = args[2]
51
52     if !(data.is_a?(Hash) || data.is_a?(Array)) || path == ''
53       return default || data
54     end
55
56     separator = args[3] || '/'
57     path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key }
58     function_dig([data, path, default])
59   end
60 end