Skip to content

Instantly share code, notes, and snippets.

@mgeoffray
Last active November 9, 2021 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgeoffray/96673e80b8eacb551d07bf3c0518642c to your computer and use it in GitHub Desktop.
Save mgeoffray/96673e80b8eacb551d07bf3c0518642c to your computer and use it in GitHub Desktop.
PHP Array Reader
<?php
declare(strict_types=1);
namespace App\Framework\Component\ObjectUtils\Reader;
/**
* Class ArrayReader
*
* @package App\Framework\Component\ObjectUtils\Reader
* @author Mattheo Geoffray <mattheo.geoffray@gmail.com>
* @copyright 2011-present Mattheo Geoffray
* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* @link https://mgeoffray.fr/
*/
class ArrayReader
{
/**
* {@inheritDoc}}
*/
public function get(string $path, array $data = [], $default = null)
{
/** @var array $keys */
$keys = explode('/', $path);
return $this->getValue($keys, $data, null, $default);
}
/**
* Get specific value recursively from array
*
* @param string[] $keys
* @param mixed[] $data
* @param null $key
* @param null $default
*
* @return mixed|null
*/
protected function getValue(array $keys = [], array $data = [], $key = null, $default = null)
{
if ($key === null) {
/** @var mixed $key */
$key = current($keys);
}
if (!isset($data[$key])) {
return $default;
}
if (is_array($data[$key])) {
/** @var mixed $nextKey */
$nextKey = next($keys);
return $nextKey === false ? $data[$key] : $this->getValue($keys, $data[$key], $nextKey, $default);
}
if (is_int($data[$key])) {
return (int)$data[$key];
}
if (is_object($data[$key])) {
return (object)$data[$key];
}
return $this->parseDataTypeBool($data[$key]);
}
/**
* Get boolean value as return
*
* @param mixed $value
*
* @return bool|null
*/
protected function parseDataTypeBool($value)
{
/** @var bool $bool Filter boolean values as string */
$bool = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($bool === null) {
return $value;
}
return $bool;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment