<?php
class Core_Yadif_Container extends Yadif_Container implements Core_Yadif_Container_Interface
{
    const CONFIG_AUTOCREATE  = 'autocreate';
    const CONFIG_ORIGINAL    = 'original';

    public function __construct($components = array(), Zend_Config $config=null)
    {
        $this->setConfig($config);
        $this->addComponents($components);
    }

    public function hasComponent($name)
    {
        return array_key_exists(strtolower($name), $this->_container);
    }

    public function addComponent($name = null, array $config = null)
    {
        $config[self::CONFIG_ORIGINAL] = $name;
        
        // do we wish to auto-create this component?
        $autoCreate = false;
        if (isset($config[self::CONFIG_AUTOCREATE])) {
            $autoCreate = (bool) $config[self::CONFIG_AUTOCREATE];
            // unset ($config[self::CONFIG_AUTOCREATE]);
        }

        // first we add the component as usual
        parent::addComponent($name, $config);

        // if it's specified to auto-create this component, do it
        // just by fetching it
        if ($autoCreate) {
            $this->getComponent($name);
        }
        return $this;
    }

    public function setComponent($name, $component)
    {
        $this->_instances[strtolower($name)] = $component;
    }

    public function getParam($param, $component = null)
    {
        $param = parent::getParam($param, $component);
        if (is_array($param)) {
            array_walk_recursive($param, array($this, '_processParam'));
        } else {
            $this->_processParam($param);
        }
        return $param;
    }
    
    public function getConfig()
    {
        return $this->_container;
    }

    protected function _processParam(&$param)
    {
        if (0 === strpos($param, self::CHAR_CONFIG_VALUE)) {
            // requested to inject component
            $param = $this->getComponent(substr($param, 1));
        }
    }
}
