1<?php
2
3namespace dokuwiki\plugin\oauthgeneric;
4
5/**
6 * Dot notation access to arrays
7 *
8 * @see https://stackoverflow.com/a/39118759/172068
9 */
10class DotAccess
11{
12
13    /**
14     * Get an item from an array using "dot" notation.
15     *
16     * @param \ArrayAccess|array $array
17     * @param string $key
18     * @param mixed $default
19     * @return mixed
20     */
21    public static function get($array, $key, $default = null)
22    {
23        $key = trim($key, '.');
24
25        if (!static::accessible($array)) {
26            return $default;
27        }
28        if (is_null($key)) {
29            return $array;
30        }
31        if (static::exists($array, $key)) {
32            return $array[$key];
33        }
34        if (strpos($key, '.') === false) {
35            return $array[$key] ?? $default;
36        }
37        foreach (explode('.', $key) as $segment) {
38            if (static::accessible($array) && static::exists($array, $segment)) {
39                $array = $array[$segment];
40            } else {
41                return $default;
42            }
43        }
44        return $array;
45    }
46
47    /**
48     * Determine whether the given value is array accessible.
49     *
50     * @param mixed $value
51     * @return bool
52     */
53    protected static function accessible($value)
54    {
55        return is_array($value) || $value instanceof \ArrayAccess;
56    }
57
58    /**
59     * Determine if the given key exists in the provided array.
60     *
61     * @param \ArrayAccess|array $array
62     * @param string|int $key
63     * @return bool
64     */
65    protected static function exists($array, $key)
66    {
67        if ($array instanceof \ArrayAccess) {
68            return $array->offsetExists($key);
69        }
70        return array_key_exists($key, $array);
71    }
72}
73