Просмотр файла cvServiceContainer/cvServiceContainer.php

Размер файла: 11.98Kb
<?php

/**
 * cvServiceContainer
 * 
 * Dependency injection main container
 * 
 * @package CYBERVILLE
 * @subpackage DI
 * @author Kochergin Nick <[email protected]>, <http://cyberville-project.ru>
 * @version $Id$
 */
class cvServiceContainer implements ArrayAccess, Iterator {

    protected $parameters = array();
    protected $subcontainers = array();

    protected $serviceIds = array();
    protected $services = array();

    protected $path_subcontainers = null;
    protected $count = 0;
     
    /**
     * Constructor
     * 
     * @param array $parameters An array of parameters
     */
    public function __construct(array $parameters = array()) {
        $this->setParameters($parameters);
        $this->setService('service_container', $this);
    }

    /**
     * Sets the service container parameters.
     * 
     * @param array $parameters An array of parameters
     */
    public function setParameters(array $parameters) {
        $this->parameters = array();
        foreach ($parameters as $key => $value) {
            $this->parameters[strtolower($key)] = $value;
        }
    }

    /**
     * Adds parameters to the service container parameters.
     * 
     * @param array $parameters An array of parameters
     */
    public function addParameters(array $parameters) {
        $this->setParameters(array_merge($this->parameters, $parameters));
    }

    /**
     * Gets the service container parameters.
     * 
     * @return array An array of parameters
     */
    public function getParameters() {
        return $this->parameters;
    }

    /**
     * Gets a service container parameter.
     * 
     * @param string $name The parameter name
     * @return mixed The parameter value
     */
    public function getParameter($name) {
        if (!$this->hasParameter($name)) {
            throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
        }
        $value = $this->parameters[strtolower($name)];
        if (is_object($value) && $value instanceof cvServiceReference) {
            return $this->getService($value->getIdService(), (is_null($value->getIdContainer()))?false:$value->getIdContainer());
        }

        return $value;
    }

    /**
     * Sets a service container parameter.
     * 
     * @param string $name  The parameter name
     * @param mixed  $value The parameter value
     */
    public function setParameter($name, $value) {
        $this->parameters[strtolower($name)] = $value;
    }

    /**
     * Returns true if a parameter name is defined.
     * 
     * @param string $name The parameter name
     * @return Boolean true if the parameter name is defined, false otherwise
     */
    public function hasParameter($name) {
        return array_key_exists(strtolower($name), $this->parameters);
    }

    /**
     * Sets a service.
     * 
     * @param string $id      The service identifier
     * @param object $service The service instance
     */
    public function setService($id, $service) {
        $this->services[$id] = $service;
    }

    /**
     * Returns true if the given service is defined.
     * Performs loading a subcontainer to validate service. 
     * 
     * @param string $id                 The service identifier
     * @param string|bool $subcontainer  The subcontainer identifier
     * 
     * @return Boolean true if the service is defined, false otherwise
     */
    public function hasService($id, $subcontainer = false) {
        if ($subcontainer === false) {
            return isset($this->services[$id]) || method_exists($this, 'get' . static ::camelize($id) . 'Service');
        }

        $subcontainer = (string )$subcontainer;

        return $this->hasContainer($subcontainer) && method_exists($this->subcontainers[$subcontainer], 'get' . static ::camelize($id) . 'Service');

    }

    /**
     * Gets a service.
     * Performs loading a subcontainer
     * 
     * @param string $id                 The service identifier
     * @param string|bool $subcontainer  The subcontainer identifier
     * @return object The associated service
     */
    public function getService($id, $subcontainer = false) {
        if ($subcontainer === false) {
            if (isset($this->services[$id])) {
                return $this->services[$id];
            }
            if (method_exists($this, $method = 'get' . static ::camelize($id) . 'Service')) {
                return $this->$method();
            }
        } else {
            $subcontainer = (string )$subcontainer;

            if ($this->hasContainer($subcontainer) && method_exists($this->subcontainers[$subcontainer], $method = 'get' . static ::camelize($id) . 'Service'))
                return $this->subcontainers[$subcontainer]->$method();
        }

        throw new InvalidArgumentException(sprintf('The service "%s" does not exist.', $id));
    }

    /**
     * Sets a container.
     * 
     * @param string $id The container identifier
     * @param object $container
     */
    public function setContainer($id, cvServiceSubcontainer $container) {
        $this->subcontainers[$id] = $container;
    }

    /**
     * Returns true if the given container is defined.
     * 
     * @param string $container The container identifier
     * @return Boolean true if the container is defined, false otherwise
     */
    public function hasContainer($container) {
        if (!key_exists($container, $this->subcontainers)) {
            try {
                $this->getSubcontainer($container);
            }
            catch (IncorrectPathException $e) {
                return false;
            }
        }
        return true;
    }

    /**
     * Gets a container.
     * 
     * @param string $container The container identifier
     * @return object
     */
    public function getContainer($container) {
        if ($this->hasContainer($container))
            return $this->subcontainers[$container];

        throw new InvalidArgumentException(sprintf('The container "%s" does not exist.', $container));
    }

    /**
     * Set of paths to search for containers 
     * 
     * @param string|array $path
     */
    public function setPaths($path) {
        if (!is_array($path))
            $path = array($path);
        $this->path_subcontainers = $path;
    }

    /**
     * Gets all the loaded service IDs
     * 
     * @return array An array of all defined service IDs
     */
    public function getServiceIds() {
        $ids = array();
        $containers = array_merge($this->subcontainers, array($this));
        foreach ($containers as $id => $sc) {
            $r = new ReflectionClass($sc);
            foreach ($r->getMethods() as $method) {
                if (preg_match('/^get(.+)Service$/', $method->getName(), $match)) {
                    if ($id === 0) {
                        $ids[] = static ::underscore($match[1]);
                    } else {
                        $ids[] = $id . '::' . static ::underscore($match[1]);
                    }
                }
            }
        }

        return array_merge($ids, array_keys($this->services));
    }

    /**
     * Returns true if the parameter name is defined (implements the ArrayAccess interface).
     * 
     * @param  string $name The parameter name
     * @return Boolean true if the parameter name is defined, false otherwise
     */
    public function offsetExists($name) {
        return $this->hasParameter($name);
    }

    /**
     * Gets a service container parameter (implements the ArrayAccess interface).
     * 
     * @param  string $name The parameter name
     * @return mixed  The parameter value
     */
    public function offsetGet($name) {
        return $this->getParameter($name);
    }

    /**
     * Sets a parameter (implements the ArrayAccess interface).
     * 
     * @param string $name  The parameter name
     * @param mixed  $value The parameter value
     */
    public function offsetSet($name, $value) {
        $this->setParameter($name, $value);
    }

    /**
     * Removes a parameter (implements the ArrayAccess interface).
     * 
     * @param string $name The parameter name
     */
    public function offsetUnset($name) {
        unset($this->parameters[$name]);
    }

    /**
     * Returns true if the given service is defined.
     *
     * @param  string $id The service identifier
     *
     * @return Boolean true if the container has a service with the given identifier, false otherwise
     */
    public function __isset($id) {
        return $this->hasService($id);
    }

    /**
     * Gets the service associated with the given identifier.
     *
     * @param  string $id The service identifier
     *
     * @return mixed  The service instance associated with the given identifier
     */
    public function __get($id) {
        return $this->getService($id);
    }

    /**
     * Sets a service.
     *
     * @param string $id      The service identifier
     * @param mixed  $service A service instance
     */
    public function __set($id, $service) {
        $this->setService($id, $service);
    }

    /**
     * Removes a service by identifier.
     *
     * @param string $id The service identifier
     */
    public function __unset($id) {
        throw new LogicException('You can\'t unset a service.');
    }

    /**
     * Gets a container.
     * 
     * @param string $container The container identifier
     * @return object|false
     */
    public function __invoke($container) {
        try {
            return $this->getContainer($container);
        } catch (InvalidArgumentException $e){
            return false;
        }
    }

    /**
     * Resets the service identifiers array to the beginning (implements the Iterator interface).
     */
    public function rewind() {
        $this->serviceIds = $this->getServiceIds();
        $this->count = count($this->serviceIds);
    }

    /**
     * Gets the key associated with the current service (implements the Iterator interface).
     *
     * @return string The service identifier
     */
    public function key() {
        return current($this->serviceIds);
    }

    /**
     * Returns the current service (implements the Iterator interface).
     *
     * @return mixed The service
     */
    public function current() {
        if (preg_match('/^(.+)\:\:(.+)$/', current($this->serviceIds), $match))
            return $this->getService($match[2], $match[1]);

        return $this->getService(current($this->serviceIds));
    }

    /**
     * Moves to the next service (implements the Iterator interface).
     */
    public function next() {
        next($this->serviceIds);

        --$this->count;
    }

    /**
     * Returns true if the current service is valid (implements the Iterator interface).
     *
     * @return boolean The validity of the current service; true if it is valid
     */
    public function valid() {
        return $this->count > 0;
    }
    
    /**
     * Lazy loading subcontainers
     * 
     * @param string $name The container identifier
     */
    public function getSubcontainer($name) {
        $compiler = new cvServiceContainerCompiler();
        $compiler->addPathsForSearch($this->path_subcontainers);
        if (($inc = $compiler->SearchPhpFile($name)) || ($inc = $compiler->SearchFileForCompilation($name))) {
            include_once $inc;
            $n = new $name($this);
            $this->setContainer($name, $n);
        }
    }

    static public function camelize($id) {
        return preg_replace(array('/(^|_|-)+(.)/e', '/\.(.)/e'), array("strtoupper('\\2')", "'_'.strtoupper('\\1')"), $id);
    }

    static public function underscore($id) {
        return strtolower(preg_replace(array('/_/', '/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('.', '\\1_\\2', '\\1_\\2'), $id));
    }

}

?>