Update puppetlabs/stdlib module
[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       DEPRECATED: this function is deprecated, please use dig() instead.
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 = try_get_value($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 did not match. Defaults to nil.
36       / -> (optional) path delimiter. Defaults to '/'.
37
38       In addition to the required "key" argument, "try_get_value" accepts 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 |args|
43     warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.')
44     data = args[0]
45     path = args[1] || ''
46     default = args[2]
47
48     if !(data.is_a?(Hash) || data.is_a?(Array)) || path == ''
49       return default || data
50     end
51
52     separator = args[3] || '/'
53     path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key }
54     function_dig([data, path, default])
55   end
56 end