RecursiveStructureAccess   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 89
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
eloc 36
dl 0
loc 89
rs 10
c 1
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A _recursiveHas() 0 14 4
A getArrayPath() 0 10 3
A ensureArrayIsArray() 0 12 4
A recursiveGet() 0 16 4
A recursiveHas() 0 4 1
1
<?php
2
3
namespace Kir\MySQL\Builder\Helpers;
4
5
use ArrayObject;
6
7
class RecursiveStructureAccess {
8
	/**
9
	 * @param object|array<string, mixed> $structure
10
	 * @param string|string[] $path
11
	 * @return bool
12
	 */
13
	public static function recursiveHas($structure, $path): bool {
14
		$arrayPath = self::getArrayPath($path);
15
16
		return self::_recursiveHas($structure, $arrayPath);
17
	}
18
19
	/**
20
	 * @param object|array<string, mixed> $structure
21
	 * @param string|string[] $path
22
	 * @param mixed $default
23
	 * @return mixed
24
	 */
25
	public static function recursiveGet($structure, $path, $default) {
26
		$arrayPath = self::getArrayPath($path);
27
		$data = self::ensureArrayIsArray($structure);
28
		$count = count($arrayPath);
29
		if(!$count) {
30
			return $default;
31
		}
32
		foreach($arrayPath as $idxValue) {
33
			$part = $idxValue;
34
			if(!array_key_exists($part, $data)) {
35
				return $default;
36
			}
37
			$data = $data[$part];
38
		}
39
40
		return $data;
41
	}
42
43
	/**
44
	 * @param mixed $structure
45
	 * @param string[] $path
46
	 * @return bool
47
	 */
48
	private static function _recursiveHas($structure, array $path): bool {
49
		$data = self::ensureArrayIsArray($structure);
50
		if($data === null) {
51
			return false;
52
		}
53
		if(!count($path)) {
54
			return false;
55
		}
56
		$key = array_shift($path);
57
		if(count($path)) {
58
			return self::_recursiveHas($data[$key] ?? null, $path);
59
		}
60
61
		return array_key_exists($key, $data);
62
	}
63
64
	/**
65
	 * @param string|string[] $path
66
	 * @return string[]
67
	 */
68
	private static function getArrayPath($path): array {
69
		if(is_array($path)) {
70
			return $path;
71
		}
72
		$parts = preg_split('{(?<!\\x5C)(?:\\x5C\\x5C)*\\.}', $path);
73
		if($parts === false) {
74
			return [$path];
75
		}
76
77
		return $parts;
78
	}
79
80
	/**
81
	 * @param mixed $array
82
	 * @return array<mixed, mixed>
83
	 */
84
	private static function ensureArrayIsArray($array): ?array {
85
		if($array instanceof ArrayObject) {
86
			return $array->getArrayCopy();
87
		}
88
		if(is_object($array)) {
89
			return (array) $array;
90
		}
91
		if(is_array($array)) {
92
			return $array;
93
		}
94
95
		return null;
96
	}
97
}
98