WebCollage/src/Config.php

73 lines
1.4 KiB
PHP

<?php
namespace Shikiryu\WebGobbler;
class Config
{
protected $data = null;
protected $cache = [];
/**
* Config constructor.
* @throws \JsonException
* @throws \Exception
*/
public function __construct($config_file)
{
if (!is_readable($config_file)) {
throw new \Exception('Config file doesn\'t exist or is unreadable.');
}
$this->data = json_decode(file_get_contents($config_file), true, 512, JSON_THROW_ON_ERROR);
}
/**
* @param $key
* @param null $default
*
* @return mixed|null
*/
public function get($key, $default = null)
{
if ($this->has($key)) {
return $this->cache[$key];
}
return $default;
}
/**
* @param string $key
*
* @return bool
*/
public function has($key)
{
// Check if already cached
if (isset($this->cache[$key])) {
return true;
}
$segments = explode('.', $key);
$root = $this->data;
// nested case
foreach ($segments as $segment) {
if (array_key_exists($segment, $root)) {
$root = $root[$segment];
continue;
}
return false;
}
// Set cache for the given key
$this->cache[$key] = $root;
return true;
}
}