Skip to content

Commit

Permalink
feat: add array util methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Jul 9, 2023
1 parent 83b2ae9 commit debc228
Showing 1 changed file with 89 additions and 2 deletions.
91 changes: 89 additions & 2 deletions src/Anchor.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public static function sanitize($data)

/**
* Get an item or items from an array of data.
*
*
* @param array $dataSource An array of data to search through
* @param string|array $item The items to return
*/
Expand All @@ -83,9 +83,96 @@ public static function deepGet($dataSource, $item = null)
return $output;
}

/**
* Deep get an item or items from an array of data using dot notation.
*
* @param array $dataSource An array of data to search through
* @param string|array $item The items to return
*/
public static function deepGetDot($dataSource, $item = null)
{
if (!$item) {
return $dataSource;
}

$output = [];

if (is_array($item)) {
foreach ($item as $dataItem) {
$output[$dataItem] = static::deepGetDot($dataSource, $dataItem);
}
} else {
$items = explode('.', $item);

if (count($items) > 1) {
$output = static::deepGetDot($dataSource[$items[0]] ?? null, $items[1]);
} else {
$output = $dataSource[$item] ?? null;
}
}

return $output;
}

/**
* Deep set an item or items in an array of data using dot notation.
*
* @param array $dataSource An array of data to search through
* @param string|array $item The items to set
* @param mixed $value The value to set
*/
public static function deepSetDot($dataSource, $item, $value = null)
{
if (is_array($item)) {
foreach ($item as $dataItem => $dataValue) {
$dataSource = static::deepSetDot($dataSource, $dataItem, $dataValue);
}
} else {
$items = explode('.', $item);

if (count($items) > 2) {
trigger_error('Nested config can\'t be more than 1 level deep at ' . $item);
}

if (count($items) > 1) {
$dataSource[$items[0]] = static::deepSetDot($dataSource[$items[0]] ?? null, $items[1], $value);
} else {
$dataSource[$item] = $value;
}
}

return $dataSource;
}

/**
* Deep unset an item or items in an array of data using dot notation.
*/
public static function deepUnsetDot($dataSource, $item)
{
if (is_array($item)) {
foreach ($item as $dataItem) {
$dataSource = static::deepUnsetDot($dataSource, $dataItem);
}
} else {
$items = explode('.', $item);

if (count($items) > 2) {
trigger_error('Nested config can\'t be more than 1 level deep at ' . $item);
}

if (count($items) > 1) {
$dataSource[$items[0]] = static::deepUnsetDot($dataSource[$items[0]] ?? null, $items[1]);
} else {
unset($dataSource[$item]);
}
}

return $dataSource;
}

/**
* Convert string to boolean. Created due to inconsistencies in PHP's boolval and (bool)
*
*
* @param string $value The value to convert
* @return bool
*/
Expand Down

0 comments on commit debc228

Please sign in to comment.