Repository navigation
Expand file tree
/
Copy pathHelpers.php
More file actions
103 lines (84 loc) · 2.44 KB
/
Copy pathHelpers.php
File metadata and controls
103 lines (84 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
namespace BitApps\WPValidator;
use stdClass;
trait Helpers
{
protected function isEmpty($val): bool
{
return empty($val) && !in_array($val, ['0', 0, 0.0, false], true);
}
protected function getValueLength($value)
{
if (is_string($value)) {
$value = mb_strlen($value, 'UTF-8');
} elseif (is_array($value)) {
$value = count($value);
} elseif (!is_int($value) && !is_float($value)) {
return false;
}
return $value;
}
/**
* Check a value's length against an inclusive range.
*
* A length of 0 is a valid length; only values with no measurable
* length at all (bool, null, object) fail outright. Pass null for
* an open-ended bound.
*/
protected function lengthWithin($value, $min = null, $max = null): bool
{
$length = $this->getValueLength($value);
if ($length === false) {
return false;
}
if ($min !== null && $length < $min) {
return false;
}
return $max === null || $length <= $max;
}
public function setNestedElement(&$data, $keys, $value)
{
$current = &$data;
foreach ($keys as $key) {
if (\is_array($current) && !isset($current[$key])) {
$current[$key] = [];
} elseif (\is_object($current) && !isset($current->{$key})) {
$current->{$key} = new stdClass();
}
$current = &$current[$key] ?? $current->{$key};
}
$current = $value;
return $current;
}
public function getValueFromPath($keys, $data)
{
$counter = 0;
while (count($keys) > $counter) {
$path = $keys[$counter];
if (is_object($data)) {
$data = (array) $data;
}
if (isset($data[$path])) {
$data = $data[$path];
} else {
return null;
}
$counter++;
}
return $data;
}
public function isNestedKeyExists($data, $keys): bool
{
foreach ($keys as $key) {
if (\is_object($data) && isset($data->$key)) {
$data = $data->$key;
}
if (\is_array($data) && \array_key_exists($key, $data)) {
$data = $data[$key];
} else {
return false;
}
}
return true;
}
}