Skip to content

Instantly share code, notes, and snippets.

@yusukezzz
Created April 10, 2014 04:28
Show Gist options
  • Save yusukezzz/10342582 to your computer and use it in GitHub Desktop.
Save yusukezzz/10342582 to your computer and use it in GitHub Desktop.
<?php namespace Yusukezzz;
use Illuminate\Filesystem\Filesystem;
class Config implements \ArrayAccess
{
/**
* @var array
*/
protected $items = [];
/**
* @var array
*/
protected $parsed = [];
/**
* @var string
*/
protected $environment;
/**
* @var string
*/
protected $configDir;
/**
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
public function __construct($environment, $configDir, Filesystem $files = null)
{
$this->environment = $environment;
$this->configDir = $configDir;
$this->files = $files ?: new Filesystem;
}
public function has($key)
{
$default = microtime(true);
return $this->get($key, $default) !== $default;
}
public function get($key, $default = null)
{
list($group, $item) = $this->parseKey($key);
$items = $this->load($group);
return array_get($items, $item, $default);
}
public function parseKey($key)
{
if (isset($this->parsed[$key])) {
return $this->parsed[$key];
}
$segments = explode('.', $key);
$group = array_shift($segments);
$items = (count($segments) === 0) ? null : implode('.', $segments);
$parsed = [$group, $items];
return $this->parsed[$key] = $parsed;
}
protected function load($group)
{
if (isset($this->items[$group])) {
return $this->items[$group];
}
$items = [];
$env = $this->environment;
$file = "{$this->configDir}/{$group}.php";
if ($this->files->exists($file)) {
$items = $this->files->getRequire($file);
}
$file = "{$this->configDir}/{$env}/{$group}.php";
if ($this->files->exists($file)) {
$items = $this->mergeEnvironment($items, $file);
}
return $this->items[$group] = $items;
}
protected function mergeEnvironment(array $items, $file)
{
return array_replace_recursive($items, $this->files->getRequire($file));
}
public function offsetExists($key)
{
return $this->has($key);
}
public function offsetGet($key)
{
return $this->get($key);
}
public function offsetSet($offset, $value)
{
throw new \LogicException('config is read only.');
}
public function offsetUnset($offset)
{
throw new \LogicException('config is read only.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment