Skip to content

Instantly share code, notes, and snippets.

@dlundgren
Created May 27, 2014 13:24
Show Gist options
  • Save dlundgren/86f9ffd45f1fec3ca0a0 to your computer and use it in GitHub Desktop.
Save dlundgren/86f9ffd45f1fec3ca0a0 to your computer and use it in GitHub Desktop.
Zend Framework 1 Configuration ParameterBag for Symfony Dependency Injection
<?php
namespace dlundgren\Symfony\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
/**
* Holds parameters.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author David Lundgren <dlundgren@syberisle.net>
* @api
*/
class ZendFrameworkConfig
extends ParameterBag
{
public function __construct($config = NULL)
{
$this->parameters = array();
if ($config instanceof Zend_Config) {
$this->add($config->toArray());
}
elseif (is_array($config)) {
$this->add($config);
}
else {
throw new RuntimeException("Invalid Configuration options");
}
$this->resolved = false;
}
public function add(array $parameters)
{
// XXX we need to handle subkeys appropriately...
foreach ($parameters as $key => $value) {
$this->set($key, $value);
}
return $this;
}
public function get($name)
{
$nodes = $this->stringToPath($name);
$map =& $this->parameters;
if (is_array($nodes)) {
foreach ($nodes as $node) {
if (array_key_exists($node, $map)) {
$map =& $map[$node];
}
else {
throw new ParameterNotFoundException($name);
}
}
$value = $map;
}
elseif (!array_key_exists($name, $this->parameters)) {
throw new ParameterNotFoundException($name);
}
else {
$value = $this->parameters[$name];
}
return $value;
}
public function set($name, $value)
{
$key = $this->stringToPath($name);
if (is_array($key)) {
$this->setNode($key, $value);
}
else {
$this->parameters[strtolower($key)] = $value;
}
return $this;
}
protected function stringToPath($string)
{
return strpos($string, '.') !== false ? explode('.', strtolower($string)) : $string;
}
protected function setNode($nodes, $value)
{
$map =& $this->parameters;
$count = count($nodes);
for ($i = 0; $i < $count; ++$i) {
$isLast = ($i == ($count - 1));
$node = $nodes[$i];
if (array_key_exists($node, $map) && !$isLast) {
$map =& $map[$node];
}
elseif ($isLast) {
$map[$node] = $value;
}
else {
$map[$node] = array();
$map =& $map[$node];
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment