Skip to content

Instantly share code, notes, and snippets.

@mgeoffray
Last active Nov 9, 2021
Embed
What would you like to do?
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