<?php
namespace Cake\Utility;
use ArrayAccess;
use InvalidArgumentException;
use RuntimeException;
class Hash
{
public static function get($data, $path, $default = null)
{
if (!(is_array($data) || $data instanceof ArrayAccess)) {
throw new InvalidArgumentException(
'Invalid data type, must be an array or \ArrayAccess instance.'
);
}
if (empty($data) || $path === null) {
return $default;
}
if (is_string($path) || is_numeric($path)) {
$parts = explode('.', $path);
} else {
if (!is_array($path)) {
throw new InvalidArgumentException(sprintf(
'Invalid Parameter %s, should be dot separated path or array.',
$path
));
}
$parts = $path;
}
switch (count($parts)) {
case 1:
return isset($data[$parts[0]]) ? $data[$parts[0]] : $default;
case 2:
return isset($data[$parts[0]][$parts[1]]) ? $data[$parts[0]][$parts[1]] : $default;
case 3:
return isset($data[$parts[0]][$parts[1]][$parts[2]]) ? $data[$parts[0]][$parts[1]][$parts[2]] : $default;
default:
foreach ($parts as $key) {
if ((is_array($data) || $data instanceof ArrayAccess) && isset($data[$key])) {
$data = $data[$key];
} else {
return $default;
}
}
}
return $data;
}
/**
* Gets the values from an array matching the $path expression.
* The path expression is a dot separated expression, that can contain a set
* of patterns and expressions:
*
* - `{n}` Matches any numeric key, or integer.
* - `{s}` Matches any string key.
* - `{*}` Matches any value.
* - `Foo` Matches any key with the exact same value.
*
* There are a number of attribute operators:
*
* - `=`, `!=` Equality.
* - `>`, `<`, `>=`, `<=` Value comparison.
* - `=/.../` Regular expression pattern match.
*
* Given a set of User array data, from a `$User->find('all')` call:
*
* - `1.User.name` Get the name of the user at index 1.
* - `{n}.User.name` Get the name of every user in the set of users.
* - `{n}.User[id].name` Get the name of every user with an id key.
* - `{n}.User[id>=2].name` Get the name of every user with an id key greater than or equal to 2.
* - `{n}.User[username=/^paul/]` Get User elements with username matching `^paul`.
* - `{n}.User[id=1].name` Get the Users name with id matching `1`.
*
* @param array|\ArrayAccess $data The data to extract from.
* @param string $path The path to extract.
* @return array|\ArrayAccess An array of the extracted values. Returns an empty array
* if there are no matches.
* @link https://book.cakephp.org/3.0/en/core-libraries/hash.html#Cake\Utility\Hash::extract
*/
public static function extract($data, $path)
{
if (!(is_array($data) || $data instanceof ArrayAccess)) {
throw new InvalidArgumentException(
'Invalid data type, must be an array or \ArrayAccess instance.'
);
}
if (empty($path)) {
return $data;
}
if (!preg_match('/[{\[]/', $path)) {
$data = static::get($data, $path);
if ($data !== null && !(is_array($data) || $data instanceof ArrayAccess)) {
return [$data];
}
return $data !== null ? (array)$data : [];
}
if (strpos($path, '[') === false) {
$tokens = explode('.', $path);
} else {
$tokens = Text::tokenize($path, '.', '[', ']');
}
$_key = '__set_item__';
$context = [$_key => [$data]];
foreach ($tokens as $token) {
$next = [];
list($token, $conditions) = self::_splitConditions($token);
foreach ($context[$_key] as $item) {
if (is_object($item) && method_exists($item, 'toArray')) {
$item = $item->toArray();
}
foreach ((array)$item as $k => $v) {
if (static::_matchToken($k, $token)) {
$next[] = $v;
}
}
}
if ($conditions) {
$filter = [];
foreach ($next as $item) {
if ((is_array($item) || $item instanceof ArrayAccess) &&
static::_matches($item, $conditions)
) {
$filter[] = $item;
}
}
$next = $filter;
}
$context = [$_key => $next];
}
return $context[$_key];
}
protected static function _splitConditions($token)
{
$conditions = false;
$position = strpos($token, '[');
if ($position !== false) {
$conditions = substr($token, $position);
$token = substr($token, 0, $position);
}
return [$token, $conditions];
}
protected static function _matchToken($key, $token)
{
switch ($token) {
case '{n}':
return is_numeric($key);
case '{s}':
return is_string($key);
case '{*}':
return true;
default:
return is_numeric($token) ? ($key == $token) : $key === $token;
}
}
protected static function _matches($data, $selector)
{
preg_match_all(
'/(\[ (?P<attr>[^=><!]+?) (\s* (?P<op>[><!]?[=]|[><]) \s* (?P<val>(?:\/.*?\/ | [^\]]+)) )? \])/x',
$selector,
$conditions,
PREG_SET_ORDER
);
foreach ($conditions as $cond) {
$attr = $cond['attr'];
$op = isset($cond['op']) ? $cond['op'] : null;
$val = isset($cond['val']) ? $cond['val'] : null;
if (empty($op) && empty($val) && !isset($data[$attr])) {
return false;
}
if (!(isset($data[$attr]) || array_key_exists($attr, $data))) {
return false;
}
$prop = null;
if (isset($data[$attr])) {
$prop = $data[$attr];
}
$isBool = is_bool($prop);
if ($isBool && is_numeric($val)) {
$prop = $prop ? '1' : '0';
} elseif ($isBool) {
$prop = $prop ? 'true' : 'false';
} elseif (is_numeric($prop)) {
$prop = (string)$prop;
}
if ($op === '=' && $val && $val[0] === '/') {
if (!preg_match($val, $prop)) {
return false;
}
} elseif (($op === '=' && $prop != $val) ||
($op === '!=' && $prop == $val) ||
($op === '>' && $prop <= $val) ||
($op === '<' && $prop >= $val) ||
($op === '>=' && $prop < $val) ||
($op === '<=' && $prop > $val)
) {
return false;
}
}
return true;
}
public static function insert(array $data, $path, $values = null)
{
$noTokens = strpos($path, '[') === false;
if ($noTokens && strpos($path, '.') === false) {
$data[$path] = $values;
return $data;
}
if ($noTokens) {
$tokens = explode('.', $path);
} else {
$tokens = Text::tokenize($path, '.', '[', ']');
}
if ($noTokens && strpos($path, '{') === false) {
return static::_simpleOp('insert', $data, $tokens, $values);
}
$token = array_shift($tokens);
$nextPath = implode('.', $tokens);
list($token, $conditions) = static::_splitConditions($token);
foreach ($data as $k => $v) {
if (static::_matchToken($k, $token)) {
if (!$conditions || static::_matches($v, $conditions)) {
$data[$k] = $nextPath
? static::insert($v, $nextPath, $values)
: array_merge($v, (array)$values);
}
}
}
return $data;
}
protected static function _simpleOp($op, $data, $path, $values = null)
{
$_list =& $data;
$count = count($path);
$last = $count - 1;
foreach ($path as $i => $key) {
if ($op === 'insert') {
if ($i === $last) {
$_list[$key] = $values;
return $data;
}
if (!isset($_list[$key])) {
$_list[$key] = [];
}
$_list =& $_list[$key];
if (!is_array($_list)) {
$_list = [];
}
} elseif ($op === 'remove') {
if ($i === $last) {
if (is_array($_list)) {
unset($_list[$key]);
}
return $data;
}
if (!isset($_list[$key])) {
return $data;
}
$_list =& $_list[$key];
}
}
}
public static function remove(array $data, $path)
{
$noTokens = strpos($path, '[') === false;
$noExpansion = strpos($path, '{') === false;
if ($noExpansion && $noTokens && strpos($path, '.') === false) {
unset($data[$path]);
return $data;
}
$tokens = $noTokens ? explode('.', $path) : Text::tokenize($path, '.', '[', ']');
if ($noExpansion && $noTokens) {
return static::_simpleOp('remove', $data, $tokens);
}
$token = array_shift($tokens);
$nextPath = implode('.', $tokens);
list($token, $conditions) = self::_splitConditions($token);
foreach ($data as $k => $v) {
$match = static::_matchToken($k, $token);
if ($match && is_array($v)) {
if ($conditions) {
if (static::_matches($v, $conditions)) {
if ($nextPath !== '') {
$data[$k] = static::remove($v, $nextPath);
} else {
unset($data[$k]);
}
}
} else {
$data[$k] = static::remove($v, $nextPath);
}
if (empty($data[$k])) {
unset($data[$k]);
}
} elseif ($match && $nextPath === '') {
unset($data[$k]);
}
}
return $data;
}
public static function combine(array $data, $keyPath, $valuePath = null, $groupPath = null)
{
if (empty($data)) {
return [];
}
if (is_array($keyPath)) {
$format = array_shift($keyPath);
$keys = static::format($data, $keyPath, $format);
} else {
$keys = static::extract($data, $keyPath);
}
if (empty($keys)) {
return [];
}
$vals = null;
if (!empty($valuePath) && is_array($valuePath)) {
$format = array_shift($valuePath);
$vals = static::format($data, $valuePath, $format);
} elseif (!empty($valuePath)) {
$vals = static::extract($data, $valuePath);
}
if (empty($vals)) {
$vals = array_fill(0, count($keys), null);
}
if (count($keys) !== count($vals)) {
throw new RuntimeException(
'Hash::combine() needs an equal number of keys + values.'
);
}
if ($groupPath !== null) {
$group = static::extract($data, $groupPath);
if (!empty($group)) {
$c = count($keys);
$out = [];
for ($i = 0; $i < $c; $i++) {
if (!isset($group[$i])) {
$group[$i] = 0;
}
if (!isset($out[$group[$i]])) {
$out[$group[$i]] = [];
}
$out[$group[$i]][$keys[$i]] = $vals[$i];
}
return $out;
}
}
if (empty($vals)) {
return [];
}
return array_combine($keys, $vals);
}
public static function format(array $data, array $paths, $format)
{
$extracted = [];
$count = count($paths);
if (!$count) {
return null;
}
for ($i = 0; $i < $count; $i++) {
$extracted[] = static::extract($data, $paths[$i]);
}
$out = [];
$data = $extracted;
$count = count($data[0]);
$countTwo = count($data);
for ($j = 0; $j < $count; $j++) {
$args = [];
for ($i = 0; $i < $countTwo; $i++) {
if (array_key_exists($j, $data[$i])) {
$args[] = $data[$i][$j];
}
}
$out[] = vsprintf($format, $args);
}
return $out;
}
public static function contains(array $data, array $needle)
{
if (empty($data) || empty($needle)) {
return false;
}
$stack = [];
while (!empty($needle)) {
$key = key($needle);
$val = $needle[$key];
unset($needle[$key]);
if (array_key_exists($key, $data) && is_array($val)) {
$next = $data[$key];
unset($data[$key]);
if (!empty($val)) {
$stack[] = [$val, $next];
}
} elseif (!array_key_exists($key, $data) || $data[$key] != $val) {
return false;
}
if (empty($needle) && !empty($stack)) {
list($needle, $data) = array_pop($stack);
}
}
return true;
}
public static function check(array $data, $path)
{
$results = static::extract($data, $path);
if (!is_array($results)) {
return false;
}
return count($results) > 0;
}
public static function filter(array $data, $callback = ['self', '_filter'])
{
foreach ($data as $k => $v) {
if (is_array($v)) {
$data[$k] = static::filter($v, $callback);
}
}
return array_filter($data, $callback);
}
protected static function _filter($var)
{
return $var === 0 || $var === 0.0 || $var === '0' || !empty($var);
}
public static function flatten(array $data, $separator = '.')
{
$result = [];
$stack = [];
$path = null;
reset($data);
while (!empty($data)) {
$key = key($data);
$element = $data[$key];
unset($data[$key]);
if (is_array($element) && !empty($element)) {
if (!empty($data)) {
$stack[] = [$data, $path];
}
$data = $element;
reset($data);
$path .= $key . $separator;
} else {
$result[$path . $key] = $element;
}
if (empty($data) && !empty($stack)) {
list($data, $path) = array_pop($stack);
reset($data);
}
}
return $result;
}
public static function expand(array $data, $separator = '.')
{
$result = [];
foreach ($data as $flat => $value) {
$keys = explode($separator, $flat);
$keys = array_reverse($keys);
$child = [
$keys[0] => $value
];
array_shift($keys);
foreach ($keys as $k) {
$child = [
$k => $child
];
}
$stack = [[$child, &$result]];
static::_merge($stack, $result);
}
return $result;
}
public static function merge(array $data, $merge)
{
$args = array_slice(func_get_args(), 1);
$return = $data;
$stack = [];
foreach ($args as &$curArg) {
$stack[] = [(array)$curArg, &$return];
}
unset($curArg);
static::_merge($stack, $return);
return $return;
}
protected static function _merge($stack, &$return)
{
while (!empty($stack)) {
foreach ($stack as $curKey => &$curMerge) {
foreach ($curMerge[0] as $key => &$val) {
$isArray = is_array($curMerge[1]);
if ($isArray && !empty($curMerge[1][$key]) && (array)$curMerge[1][$key] === $curMerge[1][$key] && (array)$val === $val) {
$stack[] = [&$val, &$curMerge[1][$key]];
} elseif ((int)$key === $key && $isArray && isset($curMerge[1][$key])) {
$curMerge[1][] = $val;
} else {
$curMerge[1][$key] = $val;
}
}
unset($stack[$curKey]);
}
unset($curMerge);
}
}
public static function numeric(array $data)
{
if (empty($data)) {
return false;
}
return $data === array_filter($data, 'is_numeric');
}
public static function dimensions(array $data)
{
if (empty($data)) {
return 0;
}
reset($data);
$depth = 1;
while ($elem = array_shift($data)) {
if (is_array($elem)) {
$depth++;
$data = $elem;
} else {
break;
}
}
return $depth;
}
public static function maxDimensions(array $data)
{
$depth = [];
if (is_array($data) && !empty($data)) {
foreach ($data as $value) {
if (is_array($value)) {
$depth[] = static::maxDimensions($value) + 1;
} else {
$depth[] = 1;
}
}
}
return empty($depth) ? 0 : max($depth);
}
public static function map(array $data, $path, $function)
{
$values = (array)static::extract($data, $path);
return array_map($function, $values);
}
public static function reduce(array $data, $path, $function)
{
$values = (array)static::extract($data, $path);
return array_reduce($values, $function);
}
public static function apply(array $data, $path, $function)
{
$values = (array)static::extract($data, $path);
return call_user_func($function, $values);
}
public static function sort(array $data, $path, $dir = 'asc', $type = 'regular')
{
if (empty($data)) {
return [];
}
$originalKeys = array_keys($data);
$numeric = is_numeric(implode('', $originalKeys));
if ($numeric) {
$data = array_values($data);
}
$sortValues = static::extract($data, $path);
$dataCount = count($data);
$missingData = count($sortValues) < $dataCount;
if ($missingData && $numeric) {
$itemPath = substr($path, 4);
foreach ($data as $key => $value) {
$sortValues[$key] = static::get($value, $itemPath);
}
} elseif ($missingData) {
$sortValues = array_pad($sortValues, $dataCount, null);
}
$result = static::_squash($sortValues);
$keys = static::extract($result, '{n}.id');
$values = static::extract($result, '{n}.value');
$dir = strtolower($dir);
$ignoreCase = false;
if (is_array($type)) {
$type += ['ignoreCase' => false, 'type' => 'regular'];
$ignoreCase = $type['ignoreCase'];
$type = $type['type'];
}
$type = strtolower($type);
if ($dir === 'asc') {
$dir = \SORT_ASC;
} else {
$dir = \SORT_DESC;
}
if ($type === 'numeric') {
$type = \SORT_NUMERIC;
} elseif ($type === 'string') {
$type = \SORT_STRING;
} elseif ($type === 'natural') {
$type = \SORT_NATURAL;
} elseif ($type === 'locale') {
$type = \SORT_LOCALE_STRING;
} else {
$type = \SORT_REGULAR;
}
if ($ignoreCase) {
$values = array_map('mb_strtolower', $values);
}
array_multisort($values, $dir, $type, $keys, $dir, $type);
$sorted = [];
$keys = array_unique($keys);
foreach ($keys as $k) {
if ($numeric) {
$sorted[] = $data[$k];
continue;
}
if (isset($originalKeys[$k])) {
$sorted[$originalKeys[$k]] = $data[$originalKeys[$k]];
} else {
$sorted[$k] = $data[$k];
}
}
return $sorted;
}
protected static function _squash(array $data, $key = null)
{
$stack = [];
foreach ($data as $k => $r) {
$id = $k;
if ($key !== null) {
$id = $key;
}
if (is_array($r) && !empty($r)) {
$stack = array_merge($stack, static::_squash($r, $id));
} else {
$stack[] = ['id' => $id, 'value' => $r];
}
}
return $stack;
}
public static function diff(array $data, array $compare)
{
if (empty($data)) {
return (array)$compare;
}
if (empty($compare)) {
return (array)$data;
}
$intersection = array_intersect_key($data, $compare);
while (($key = key($intersection)) !== null) {
if ($data[$key] == $compare[$key]) {
unset($data[$key], $compare[$key]);
}
next($intersection);
}
return $data + $compare;
}
public static function mergeDiff(array $data, array $compare)
{
if (empty($data) && !empty($compare)) {
return $compare;
}
if (empty($compare)) {
return $data;
}
foreach ($compare as $key => $value) {
if (!array_key_exists($key, $data)) {
$data[$key] = $value;
} elseif (is_array($value)) {
$data[$key] = static::mergeDiff($data[$key], $compare[$key]);
}
}
return $data;
}
public static function normalize(array $data, $assoc = true)
{
$keys = array_keys($data);
$count = count($keys);
$numeric = true;
if (!$assoc) {
for ($i = 0; $i < $count; $i++) {
if (!is_int($keys[$i])) {
$numeric = false;
break;
}
}
}
if (!$numeric || $assoc) {
$newList = [];
for ($i = 0; $i < $count; $i++) {
if (is_int($keys[$i])) {
$newList[$data[$keys[$i]]] = null;
} else {
$newList[$keys[$i]] = $data[$keys[$i]];
}
}
$data = $newList;
}
return $data;
}
public static function nest(array $data, array $options = [])
{
if (!$data) {
return $data;
}
$alias = key(current($data));
$options += [
'idPath' => "{n}.$alias.id",
'parentPath' => "{n}.$alias.parent_id",
'children' => 'children',
'root' => null
];
$return = $idMap = [];
$ids = static::extract($data, $options['idPath']);
$idKeys = explode('.', $options['idPath']);
array_shift($idKeys);
$parentKeys = explode('.', $options['parentPath']);
array_shift($parentKeys);
foreach ($data as $result) {
$result[$options['children']] = [];
$id = static::get($result, $idKeys);
$parentId = static::get($result, $parentKeys);
if (isset($idMap[$id][$options['children']])) {
$idMap[$id] = array_merge($result, (array)$idMap[$id]);
} else {
$idMap[$id] = array_merge($result, [$options['children'] => []]);
}
if (!$parentId || !in_array($parentId, $ids)) {
$return[] =& $idMap[$id];
} else {
$idMap[$parentId][$options['children']][] =& $idMap[$id];
}
}
if (!$return) {
throw new InvalidArgumentException('Invalid data array to nest.');
}
if ($options['root']) {
$root = $options['root'];
} else {
$root = static::get($return[0], $parentKeys);
}
foreach ($return as $i => $result) {
$id = static::get($result, $idKeys);
$parentId = static::get($result, $parentKeys);
if ($id !== $root && $parentId != $root) {
unset($return[$i]);
}
}
return array_values($return);
}
}