<?php
/**
 * Http front controller.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Mvc
 * @subpackage Http
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Mvc\Http;

use Ding\Mvc\IViewRender;
use Ding\HttpSession\HttpSession;
use Ding\Mvc\IMapper;
use Ding\Mvc\Exception\MvcException;
use Ding\Mvc\ModelAndView;
use Ding\Mvc\RedirectModelAndView;
use Ding\Mvc\ForwardModelAndView;
use Ding\Container\Impl\ContainerImpl;

/**
 * Http front controller.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Mvc
 * @subpackage Http
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class HttpFrontController
{
    /**
     * Log4PHP Logger or own dummy implementation.
     * @var Logger
     */
    private static $_logger;

    public static function dispatch(
        HttpDispatcher $dispatcher,
        HttpViewResolver $viewResolver,
        HttpAction $action,
        IMapper $mapper,
        IViewRender $render
    ) {
        $dispatchInfo = $mapper->map($action);
        if ($dispatchInfo === false) {
            throw new MvcException(
            	'No suitable controller for: ' . $action->getId()
            );
        }
        $controller = $dispatchInfo->handler;
        $actionHandler = $dispatchInfo->method;

        self::$_logger->debug(
        	'Found mapped controller: ' . get_class($controller)
            . ' with action: ' . $actionHandler
        );
        $modelAndView = $dispatcher->dispatch($dispatchInfo);
        if ($modelAndView instanceof ForwardModelAndView) {
            self::$_logger->debug(
              	'Forwarding ModelAndView: ' . $modelAndView->getName()
            );
            $newAction = new HttpAction($modelAndView->getName(), $modelAndView->getModel());
            $newAction->getMethod($action->getMethod());
            self::dispatch($dispatcher, $viewResolver, $newAction, $mapper, $render);
        } else if ($modelAndView instanceof RedirectModelAndView) {
            header('HTTP/1.1 302 Moved');
            $location = $modelAndView->getName();
            if (!$modelAndView->isEmpty()) {
                $location .= '?' . http_build_query($modelAndView->getModel());
            }
            header('Location: ' . $location);
            self::$_logger->debug(
               	'Redirecting ModelAndView: ' . $modelAndView->getName()
                . " -> $location"
            );
        } else if ($modelAndView instanceof ModelAndView) {
            self::$_logger->debug(
               	'Using ModelAndView: ' . $modelAndView->getName()
            );
            $view = $viewResolver->resolve($modelAndView);
            $render->render($view);
        }
    }
    /**
     * Handles the request. This will instantiate the container with the given
     * properties (via static method configure(), see below). Then it will
     * getBean(HttpDispatcher) and call dispatch() on it with an Action created
     * based on the request uri and method parameters (get, post, etc).
     *
     * @return void
     */
    public static function handle(array $properties = array(), $baseUrl = '/')
    {
        $exceptionThrown = null;
        $filtersPassed = true;
        $session = HttpSession::getSession();
        $container = ContainerImpl::getInstance($properties);
        self::$_logger = \Logger::getLogger(__CLASS__);
        $baseUrlLen = strlen($baseUrl);
        ob_start();
        $exceptionMapper = $render = $dispatcher = $viewResolver = false;
        $interceptors = array();
        try
        {
            $dispatcher = $container->getBean('HttpDispatcher');
            $viewResolver = $container->getBean('HttpViewResolver');
            $exceptionMapper = $container->getBean('HttpExceptionMapper');
            $render = $container->getBean('HttpViewRender');
            $method = strtolower($_SERVER['REQUEST_METHOD']);
            $url = $_SERVER['REQUEST_URI'];
            $urlStart = strpos($url, $baseUrl);

            self::$_logger->debug('Trying to match: ' . $url);
            if ($urlStart === false || $urlStart > 0) {
                throw new MvcException($url . ' is not a base url.');
            }
            $url = substr($url, $baseUrlLen);
            $variables = array();
            if (!empty($_GET)) {
                $variables = array_merge($variables, $_GET);
            }
            if (!empty($_POST)) {
                $variables = array_merge($variables, $_POST);
            }
            $action = new HttpAction($url, $variables);
            $action->setMethod($method);
            $mapper = $container->getBean('HttpUrlMapper');
            self::dispatch($dispatcher, $viewResolver, $action, $mapper, $render);
        } catch(\Exception $exception) {
            $exceptionThrown = $exception;
            self::$_logger->debug('Got Exception: ' . $exception);
            ob_end_clean();
            ob_start();
            if ($exceptionMapper === false) {
                header('HTTP/1.1 500 Error.');
            } else {
                $action = new HttpAction(
                    get_class($exception), array('exception' => $exception)
                );
                self::dispatch($dispatcher, $viewResolver, $action, $exceptionMapper, $render);
            }
        }
        ob_end_flush();
    }

}


<?php
/**
 * Simple dummy cache implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Impl
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Cache\Impl;
use Ding\Cache\ICache;

/**
 * Simple dummy cache implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Impl
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class DummyCacheImpl implements ICache
{
    /**
     * Holds current instance.
     * @var DummyCacheImpl
     */
    private static $_instance = false;

    /**
     * Returns a cached value.
     *
     * @param string  $name    Key to look for.
     * @param boolean &$result True on success, false otherwise.
     *
     * @return mixed
     */
    public function fetch($name, &$result)
    {
        $result = false;
        return false;
    }

    /**
     * Stores a key/value.
     *
     * @param string $name  Key to use.
     * @param mixed  $value Value.
     *
     * @return boolean
     */
    public function store($name, $value)
    {
        return false;
    }

    /**
     * Empties the cache.
     *
	 * @return boolean
     */
    public function flush()
    {
        return false;
    }

    /**
     * Removes a key from the cache.
     *
     * @param string $name Key to remove.
     *
     * @return boolean
     */
    public function remove($name)
    {
        return false;
    }

    /**
     * Returns an instance of a cache.
     *
     * @param array $options Options for the cache backend.
     *
     * @return DummyCacheImpl
     */
    public static function getInstance($options = array())
    {
        if (self::$_instance == false) {
            self::$_instance = new DummyCacheImpl;
        }
        return self::$_instance;
    }

    /**
     * Constructor.
     *
	 * @return void
     */
    private function __construct()
    {
    }
}


<?php
/**
 * PAMI Helper. Will call your own handler and manage ami connection.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Pami
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Helpers\Pami;

use PAMI\Client\Impl\ClientImpl;
use PAMI\Listener\IEventListener;
use PAMI\Message\Event\EventMessage;
use PAMI\Message\Action\ActionMessage;

/**
 * PAMI Helper. Will call your own handler and manage ami connection.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Pami
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class PamiHelper implements IEventListener
{
    /**
     * AMI Host.
     * @var string
     */
    private $_host;

    /**
     * AMI Port.
     * @var integer
     */
    private $_port;

    /**
     * AMI Username.
     * @var string
     */
    private $_user;

    /**
     * AMI Password.
     * @var string
     */
    private $_pass;

    /**
     * AMI Connect timeout
     * @var integer
     */
    private $_connect_timeout;

    /**
     * AMI Read timeout
     * @var integer
     */
    private $_read_timeout;

    /**
     * Handler.
     * @var IPamiEventHandler
     */
    private $_handler;

    /**
     * Internally used to manage initialization.
     * @var boolean
     */
    private $_init;

    /**
     * PAMI object.
     * @var ClientImpl
     */
    private $_ami;

    /**
     * Sets ami host
     *
     * @param string $host Host name or ip address.
     *
     * @return void
     */
    public function setHost($host)
    {
        $this->_host = $host;
    }

    /**
     * Sets ami port.
     *
     * @param integer $port AMI Port.
     *
     * @return void
     */
    public function setPort($port)
    {
        $this->_port = intval($port);
    }

    /**
     * Sets ami username.
     *
     * @param string $user AMI Username.
     *
     * @return void
     */
    public function setUsername($user)
    {
        $this->_user = $user;
    }

    /**
     * Sets ami password.
     *
     * @param string $pass AMI Password.
     *
     * @return void
     */
    public function setPassword($pass)
    {
        $this->_pass = $pass;
    }

    /**
     * Sets ami connect timeout.
     *
     * @param integer $time AMI Connect timeout in milliseconds.
     *
     * @return void
     */
    public function setConnectTimeout($time)
    {
        $this->_connect_timeout = $time;
    }

    /**
     * Sets ami read timeout.
     *
     * @param integer $time AMI Read timeout in milliseconds.
     *
     * @return void
     */
    public function setReadTimeout($time)
    {
        $this->_read_timeout = $time;
    }

    /**
     * Sets handler.
     *
     * @param IPamiEventHandler $handler Handler to call.
     *
     * @return void
     */
    public function setHandler(IPamiEventHandler $handler)
    {
        $this->_handler = $handler;
    }

    /**
     * Our own handler, will call yours.
     *
     * @param EventMessage $event Incoming event.
     *
     * @return void
     */
    public function handle(EventMessage $event)
    {
        $this->_handler->handlePamiEvent($event);
    }

    /**
     * Loads pami and initializes everything.
     *
     * @return void
     */
    private function _load()
    {
        $options = array(
            'host' => $this->_host,
            'port' => $this->_port,
            'username' => $this->_user,
            'secret' => $this->_pass,
            'connect_timeout' => $this->_connect_timeout,
            'read_timeout' => $this->_read_timeout
        );
        $this->_ami = new ClientImpl($options);
        $this->_init = true;
    }

    /**
     * Opens the connection to ami. Also calls _load if it has to.
     *
     * @return void
     */
    public function open()
    {
        if (!$this->_init) {
            $this->_load();
        }
	    $this->_ami->registerEventListener($this);
	    $this->_ami->open();
    }

    /**
     * Process all incoming messages. Call this one from your own loop.
     *
     * @return void
     */
    public function process()
    {
        $this->_ami->process();
    }

    /**
     * Sends a message to ami.
     *
     * @param ActionMessage $message AMI Command.
     *
     * @return Response
     */
    public function send(ActionMessage $message)
    {
        return $this->_ami->send($message);
    }

    /**
     * Closes the connection to ami.
     *
     * return void
     */
    public function close()
    {
        $this->_ami->close();
    }

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct()
    {
        $this->_init = false;
        $this->_connect_timeout = 0;
        $this->_read_timeout = 0;
    }
}


<?php
/**
 * This driver will search for @Resource setter methods.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Bean\Factory\Driver;

use Ding\Logger\ILoggerAware;
use Ding\Reflection\IReflectionFactory;
use Ding\Reflection\IReflectionFactoryAware;
use Ding\Container\IContainerAware;
use Ding\Container\IContainer;
use Ding\Bean\Factory\Exception\BeanFactoryException;
use Ding\Bean\BeanPropertyDefinition;
use Ding\Bean\Lifecycle\IAfterDefinitionListener;
use Ding\Bean\Lifecycle\IAfterCreateListener;
use Ding\Bean\BeanDefinition;

/**
 * This driver will search for @Resource setter methods.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class AnnotationResourceDriver
    implements IAfterDefinitionListener, IContainerAware, IReflectionFactoryAware
{
    /**
     * Container.
     * @var IContainer
     */
    private $_container;

    /**
     * A ReflectionFactory implementation.
     * @var IReflectionFactory
     */
    protected $reflectionFactory;

    /**
     * (non-PHPdoc)
     * @see Ding\Reflection.IReflectionFactoryAware::setReflectionFactory()
     */
    public function setReflectionFactory(IReflectionFactory $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Container.IContainerAware::setContainer()
     */
    public function setContainer(IContainer $container)
    {
        $this->_container = $container;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Bean\Lifecycle.IAfterDefinitionListener::afterDefinition()
     */
    public function afterDefinition(BeanDefinition $bean)
    {
        $class = $bean->getClass();
        $rClass = $this->reflectionFactory->getClass($class);
        $properties = $bean->getProperties();
        foreach ($rClass->getMethods() as $method) {
            $methodName = $method->getName();
            if (strpos($methodName, 'set') !== 0) {
                continue;
            }
            $annotations = $this->reflectionFactory->getMethodAnnotations($class, $methodName);
            if (!$annotations->contains('resource')) {
                continue;
            }
            $propName = lcfirst(substr($methodName, 3));
            $name = $propName;
            $annotation = $annotations->getSingleAnnotation('resource');
            if ($annotation->hasOption('name')) {
                $name = $annotation->getOptionSingleValue('name');
            }
            $properties[$propName] = new BeanPropertyDefinition(
                $propName, BeanPropertyDefinition::PROPERTY_BEAN, $name
            );
        }
        foreach ($rClass->getProperties() as $property) {
            $propertyName = $property->getName();
            $annotations = $this->reflectionFactory->getPropertyAnnotations($class, $propertyName);
            if (!$annotations->contains('resource')) {
                continue;
            }
            $annotation = $annotations->getSingleAnnotation('resource');
            $name = $propertyName;
            if ($annotation->hasOption('name')) {
                $name = $annotation->getOptionSingleValue('name');
            }
            $properties[$propertyName] = new BeanPropertyDefinition(
                $propertyName, BeanPropertyDefinition::PROPERTY_BEAN, $name
            );
        }
        $bean->setProperties($properties);
        return $bean;
    }
}


<?php
/**
 * Cache Locator. This singleton is used througout the ding architecture in
 * order to find caches for different subsystems.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Locator
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Cache\Locator;

use Ding\Cache\Exception\CacheException;
use Ding\Cache\Impl\ApcCacheImpl;
use Ding\Cache\Impl\ZendCacheImpl;
use Ding\Cache\Impl\FileCacheImpl;
use Ding\Cache\Impl\MemcachedCacheImpl;
use Ding\Cache\Impl\DummyCacheImpl;

/**
 * Cache Locator. This singleton is used througout the ding architecture in
 * order to find caches for different subsystems.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Locator
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class CacheLocator
{
    /**
     * Default options.
     * @var array
     */
    private static $_options = array(
    	'proxy' => array('impl' => 'dummy'),
        'bdef' => array('impl' => 'dummy'),
        'beans' => array('impl' => 'dummy'),
        'aspect' => array('impl' => 'dummy'),
        'annotations' => array('impl' => 'dummy')
    );

    /**
     * Factory for cache implementations.
     *
     * @param array $options Cache options.
     *
     * @throws CacheException
     * @return ICache
     */
    private static function _returnCacheFromImpl($options)
    {
        switch ($options['impl'])
        {
        case 'file':
            return FileCacheImpl::getInstance($options);
        case 'apc':
            return ApcCacheImpl::getInstance($options);
        case 'dummy':
            return DummyCacheImpl::getInstance($options);
        case 'zend':
            return ZendCacheImpl::getInstance($options['zend']);
        case 'memcached':
            return MemcachedCacheImpl::getInstance($options['memcached']);
        default:
            throw new CacheException('Invalid cache impl requested');
        }
    }

    /**
     * The container will call this one, in order to setup options. If any
     * option is missing, we use our default options as fallback.
     *
     * @param array $options Cache options.
     *
     * @see CacheLocator::$_options
     * @return void
     */
    public static function configure(array $options)
    {
        self::$_options = array_replace_recursive(self::$_options, $options);
    }

    /**
     * Returns a cache for auto generated proxy classes.
	 *
     * @return ICache
     */
    public static function getProxyCacheInstance()
    {
        return self::_returnCacheFromImpl(self::$_options['proxy']);
    }

    /**
     * Returns a cache for bean definitions.
	 *
     * @return ICache
     */
    public static function getDefinitionsCacheInstance()
    {
        return self::_returnCacheFromImpl(self::$_options['bdef']);
    }

    /**
     * Returns a cache for beans.
	 *
     * @return ICache
     */
    public static function getBeansCacheInstance()
    {
        return self::_returnCacheFromImpl(self::$_options['beans']);
    }

    /**
     * Returns a cache for annotations.
	 *
     * @return ICache
     */
    public static function getAnnotationsCacheInstance()
    {
        return self::_returnCacheFromImpl(self::$_options['annotations']);
    }

    /**
     * Returns a cache for aspects.
	 *
     * @return ICache
     */
    public static function getAspectCacheInstance()
    {
        return self::_returnCacheFromImpl(self::$_options['aspect']);
    }
}


<?php
/**
 * The lifecycle manager for the container.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Lifecycle
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Bean\Lifecycle;
use Ding\Bean\Lifecycle\IAfterConfigListener;
use Ding\Bean\Lifecycle\IAfterDefinitionListener;
use Ding\Bean\Lifecycle\IBeforeCreateListener;
use Ding\Bean\Lifecycle\IAfterCreateListener;
use Ding\Bean\Lifecycle\IBeforeAssembleListener;
use Ding\Bean\Lifecycle\IAfterAssembleListener;
use Ding\Bean\BeanDefinition;

/**
 * The lifecycle manager for the container.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Lifecycle
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class BeanLifecycleManager
{
    /**
     * Lifecycle handlers for beans.
     * @var ILifecycleListener
     */
    private $_lifecyclers;

    /**
     * Serialization
     *
     * @return array
     */
    public function __sleep()
    {
        return array('_lifecyclers');
    }

    /**
     * Adds a lifecycler to the AfterConfig point.
     *
     * @param IAfterConfigListener $listener Listener to add
     *
     * @return void
     */
    public function addAfterConfigListener(IAfterConfigListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::AfterConfig][] = $listener;
    }

    /**
     * Adds a lifecycler to the AfterDefinition point.
     *
     * @param IAfterDefinitionListener $listener Listener to add
     *
     * @return void
     */
    public function addAfterDefinitionListener(IAfterDefinitionListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::AfterDefinition][] = $listener;
    }

    /**
     * Adds a lifecycler to the BeforeCreate point.
     *
     * @param IBeforeCreateListener $listener Listener to add
     *
     * @return void
     */
    public function addBeforeCreateListener(IBeforeCreateListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::BeforeCreate][] = $listener;
    }

    /**
     * Adds a lifecycler to the AfterCreate point.
     *
     * @param IAfterCreateListener $listener Listener to add
     *
     * @return void
     */
    public function addAfterCreateListener(IAfterCreateListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::AfterCreate][] = $listener;
    }

    /**
     * Adds a lifecycler to the BeforeAssemble point.
     *
     * @param IBeforeAssembleListener $listener Listener to add
     *
     * @return void
     */
    public function addBeforeAssembleListener(IBeforeAssembleListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::BeforeAssemble][] = $listener;
    }

    /**
     * Adds a lifecycler to the AfterAssemble point.
     *
     * @param IAfterAssembleListener $listener Listener to add
     *
     * @return void
     */
    public function addAfterAssembleListener(IAfterAssembleListener $listener)
    {
        $this->_lifecyclers[BeanLifecycle::AfterAssemble][] = $listener;
    }

    /**
     * Runs the AfterDefinition point of the lifecycle.
     *
     * @param string         $beanName Bean name.
     * @param BeanDefinition $bean     Actual definition.
     *
     * @return BeanDefinition
     */
    public function afterDefinition(BeanDefinition $bean)
    {
        $return = $bean;
        foreach ($this->_lifecyclers[BeanLifecycle::AfterDefinition] as $lifecycleListener) {
            $return = $lifecycleListener->afterDefinition($return);
        }
        return $return;
    }

    /**
     * Runs the BeforeCreate point of the lifecycle.
     *
     * @param BeanDefinition $beanDefinition Actual definition.
     *
     * @return void
     */
    public function beforeCreate(BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::BeforeCreate] as $lifecycleListener) {
            $lifecycleListener->beforeCreate($beanDefinition);
        }
    }

    /**
     * Runs the AfterCreate point of the lifecycle.
     *
     * @param string         $beanName Bean name.
     * @param BeanDefinition $bean     Actual definition.
     *
     * @return void
     */
    public function afterCreate($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::AfterCreate] as $lifecycleListener) {
            $lifecycleListener->afterCreate($bean, $beanDefinition);
        }
    }

    /**
     * Runs the BeforeAssemble point of the lifecycle.
     *
     * @param string         $beanName Bean name.
     * @param BeanDefinition $bean     Actual definition.
     *
     * @return BeanDefinition
     */
    public function beforeAssemble($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::BeforeAssemble] as $lifecycleListener) {
            $lifecycleListener->beforeAssemble($bean, $beanDefinition);
        }
    }

    /**
     * Runs the AfterAssemble point of the lifecycle.
     *
     * @param object         $bean           Bean.
     * @param BeanDefinition $beanDefinition Actual definition.
     *
     * @return void
     */
    public function afterAssemble($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::AfterAssemble] as $lifecycleListener) {
            $lifecycleListener->afterAssemble($bean, $beanDefinition);
        }
    }

    /**
     * Runs the AfterConfig point of the lifecycle.
     *
     * @return void
     */
    public function afterConfig()
    {
        foreach ($this->_lifecyclers[BeanLifecycle::AfterConfig] as $lifecycleListener) {
            $lifecycleListener->afterConfig();
        }
    }

/*
    public function setListeners(array $listeners = array())
    {
        $this->_lifecyclers[BeanLifecycle::BeforeConfig] = $listeners[BeanLifecycle::BeforeConfig];
        $this->_lifecyclers[BeanLifecycle::AfterConfig] = $listeners[BeanLifecycle::AfterConfig];
        $this->_lifecyclers[BeanLifecycle::AfterDefinition] = $listeners[BeanLifecycle::AfterDefinition];
        $this->_lifecyclers[BeanLifecycle::BeforeCreate] = $listeners[BeanLifecycle::BeforeCreate];
        $this->_lifecyclers[BeanLifecycle::AfterCreate] = $listeners[BeanLifecycle::AfterCreate];
        $this->_lifecyclers[BeanLifecycle::BeforeAssemble] = $listeners[BeanLifecycle::BeforeAssemble];
        $this->_lifecyclers[BeanLifecycle::AfterAssemble] = $listeners[BeanLifecycle::AfterAssemble];
    }
*/
    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct()
    {
        $soullessArray = array();
        $this->_lifecyclers = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::AfterConfig] = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::AfterDefinition] = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::BeforeCreate] = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::AfterCreate] = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::BeforeAssemble] = $soullessArray;
        $this->_lifecyclers[BeanLifecycle::AfterAssemble] = $soullessArray;
    }
}


<?php
/**
 * Http view render.
 *
 * PHP Version 5
 *
 * @category Ding
 * @package  Mvc
 * @author   Marcelo Gornstein <marcelog@gmail.com>
 * @license  http://marcelog.github.com/ Apache License 2.0
 * @link     http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Mvc\Http;

use Ding\HttpSession\HttpSession;

use Ding\MessageSource\IMessageSource;

use Ding\MessageSource\IMessageSourceAware;
use Ding\Mvc\IViewRender;
use Ding\Mvc\View;

/**
 * Http view render.
 *
 * PHP Version 5
 *
 * @category Ding
 * @package  Mvc
 * @author   Marcelo Gornstein <marcelog@gmail.com>
 * @license  http://marcelog.github.com/ Apache License 2.0
 * @link     http://marcelog.github.com/
 */
class HttpViewRender implements IViewRender, IMessageSourceAware
{
    /**
     * @var IMessageSource
     */
    protected $messageSource;

    public function setMessageSource(IMessageSource $messageSource)
    {
        $this->messageSource = $messageSource;
    }

    public function translate($bundle, $message, $arguments = array())
    {
        $session = HttpSession::getSession();
        if (!$session->hasAttribute('LANGUAGE')) {
            return $this->messageSource->getMessage(
                $bundle, $message, $arguments
            );
        } else {
            return $this->messageSource->getMessage(
                $bundle, $message, $arguments, $session->getAttribute('LANGUAGE')
            );
        }
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Mvc.IViewRender::render()
     */
    public function render(View $view)
    {
        /**
         * @todo is there a better way to do this?
         */
        global $modelAndView;
        $modelAndView = $view->getModelAndView();
        /**
         * @todo render headers: does this belong here?
         */
        $objects = $modelAndView->getModel();
        if (isset($objects['headers'])) {
            foreach ($objects['headers'] as $header) {
                header($header);
            }
        }
        // Now render everything else.
        if (file_exists($view->getPath())) {
            include_once $view->getPath();
        }
    }
}


<?php
/**
 * This will map an extension to a specific application (bean).
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Pagi
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Helpers\Pagi;

/**
 * This will map an extension to a specific application (bean).
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Pagi
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class PagiExtensionMapper
{
    /**
     * Extensions/Applications map.
     * @var array
     */
    private $_map;

    /**
     * Sets the map to use.
     *
     * @param array $map Map to set.
     *
     * @return void
     */
    public function setMap(array $map)
    {
        $this->_map = $map;
    }

    /**
     * Resolve extension to application (bean).
     *
     * @param string $extension Extension to map.
     *
     * @return PAGIApplication
     */
    public function resolve($extension)
    {
        if (is_array($this->_map)) {
            foreach ($this->_map as $map) {
                if (isset($map['extension']) && $map['extension'] == $extension) {
                    return $map['application'];
                }
            }
        }
        return $this->_map['default']['application'];
    }

    /**
     * Consctructor.
     *
     * @return void
     */
    public function __construct()
    {
    }
}


<?php
/**
 * Syslog helper.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Syslog
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Helpers\Syslog;

/**
 * Syslog helper.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Syslog
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class SyslogHelper
{
    /**
     * Holds current ident used.
     * @var string
     */
    private $_ident;

    /**
     * Holds current syslog options.
     * @var integer
     */
    private $_options;

    /**
     * Holds current facility used.
     * @var integer
     */
    private $_facility;

    /**
     * Sets ident.
     *
     * @param string $ident Ident to use when logging.
     *
     * @return void
     */
    public function setIdent($ident)
    {
        $this->_ident = $ident;
    }

    /**
     * Sets syslog options.
     *
     * @param integer $options Syslog options. See php constants for these.
     *
     * @return void
     */
    public function setOptions($options)
    {
        $this->_options = $options;
    }

    /**
     * Sets syslog facility. See php constants for these.
     *
     * @param integer $facility Facility to use.
     *
     * @return void
     */
    public function setFacility($facility)
    {
        $this->_facility = $facility;
    }

    /**
     * Logs a LOG_EMERG message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function emerg($message)
    {
        $this->log(LOG_EMERG, $message);
    }

    /**
     * Logs a LOG_ALERT message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function alert($message)
    {
        $this->log(LOG_ALERT, $message);
    }

    /**
     * Logs a LOG_CRIT message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function critical($message)
    {
        $this->log(LOG_CRIT, $message);
    }

    /**
     * Logs a LOG_ERR message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function error($message)
    {
        $this->log(LOG_ERR, $message);
    }

    /**
     * Logs a LOG_WARNING message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function warning($message)
    {
        $this->log(LOG_WARNING, $message);
    }

    /**
     * Logs a LOG_NOTICE message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function notice($message)
    {
        $this->log(LOG_NOTICE, $message);
    }

    /**
     * Logs a LOG_INFO message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function info($message)
    {
        $this->log(LOG_INFO, $message);
    }

    /**
     * Logs a LOG_DEBUG message.
     *
     * @param string $message Message to log.
     *
     * @return void
     */
    public function debug($message)
    {
        $this->log(LOG_DEBUG, $message);
    }

    /**
     * Used internally to log whatever kind of message.
     *
     * @param integer $priority Priority to use.
     * @param string  $message  Message to log.
     *
     * @return void
     */
    protected function log($priority, $message)
    {
        syslog($priority, $message);
    }

    /**
     * Opens syslog.
     *
     * @return void
     */
    public function open()
    {
        openlog($this->_ident, intval($this->_options), intval($this->_facility));
    }

    /**
     * Closes syslog.
     *
     * @return void
     */
    public function close()
    {
        closelog();
    }

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct()
    {
    }
}


<?php
/**
 * This is a bean definition provider used by the container when it's
 * bootstrapping. Will provide all the basic needed beans.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Provider
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Bean\Provider;

use Ding\Bean\BeanConstructorArgumentDefinition;
use Ding\Bean\BeanPropertyDefinition;
use Ding\Bean\BeanDefinition;
use Ding\Bean\IBeanDefinitionProvider;

/**
 * This is a bean definition provider used by the container when it's
 * bootstrapping. Will provide all the basic needed beans.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Provider
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class Core implements IBeanDefinitionProvider
{
    /**
     * Container options.
     * @var string[]
     */
    protected $options;

    /**
     * (non-PHPdoc)
     * @see Ding\Bean.IBeanDefinitionProvider::get()
     */
    public function getBeanDefinition($name)
    {
        $bean = null;
        switch ($name)
        {
        case 'dingAnnotationParser':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Annotation\Parser');
            break;
        case 'dingAnnotationsCache':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Cache\Locator\CacheLocator');
            $bean->setFactoryMethod('getAnnotationsCacheInstance');
            break;
        case 'dingBeanCache':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Cache\Locator\CacheLocator');
            $bean->setFactoryMethod('getBeansCacheInstance');
            break;
        case 'dingDefinitionsCache':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Cache\Locator\CacheLocator');
            $bean->setFactoryMethod('getDefinitionsCacheInstance');
            break;
        case 'dingProxyCache':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Cache\Locator\CacheLocator');
            $bean->setFactoryMethod('getProxyCacheInstance');
            break;
        case 'dingAspectCache':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Cache\Locator\CacheLocator');
            $bean->setFactoryMethod('getAspectCacheInstance');
            break;
        case 'dingAspectManager':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Aspect\AspectManager');
            $bean->setProperties(array(
                new BeanPropertyDefinition(
                	'cache', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingAspectCache'
                )
            ));
            break;
        case 'dingXmlBeanDefinitionProvider':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Provider\Xml');
            $bean->setArguments(array(
                new BeanConstructorArgumentDefinition(
                    BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                    $this->options['bdef']['xml']
                )
            ));
            break;
        case 'dingAnnotationBeanDefinitionProvider':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Provider\Annotation');
            $bean->setArguments(array(
                new BeanConstructorArgumentDefinition(
                    BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                    $this->options['bdef']['annotation']
                )
            ));
            $bean->setInitMethod('init');
            $bean->setProperties(array(
                new BeanPropertyDefinition(
                	'cache', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingAnnotationsCache'
                )
            ));
            break;
        case 'dingYamlBeanDefinitionProvider':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Provider\Yaml');
            $bean->setArguments(array(
                new BeanConstructorArgumentDefinition(
                    BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                    $this->options['bdef']['yaml']
                )
            ));
            break;
        case 'dingAspectCallDispatcher':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Aspect\Interceptor\DispatcherImpl');
            break;
        case 'dingAnnotationInitDestroyMethodDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationInitDestroyMethodDriver');
            break;
        case 'dingAnnotationValueDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationValueDriver');
            break;
        case 'dingMvcAnnotationDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\MvcAnnotationDriver');
            break;
        case 'dingAnnotationRequiredDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationRequiredDriver');
            break;
        case 'dingAnnotationDiscovererDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationDiscovererDriver');
            $bean->setProperties(array(
                new BeanPropertyDefinition(
                	'cache', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingAnnotationsCache'
                )
            ));
            $bean->setInitMethod('parse');
            $bean->setArguments(array(
                new BeanConstructorArgumentDefinition(
                    BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                    $this->options['bdef']['annotation']['scanDir']
                )
            ));
            break;
        case 'dingAnnotationResourceDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationResourceDriver');
            break;
        case 'dingAnnotationInjectDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\AnnotationInjectDriver');
            break;
        case 'dingPropertiesDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\PropertiesDriver');
            break;
        case 'dingLifecycleManager':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Lifecycle\BeanLifecycleManager');
            break;
        case 'dingMethodInjectionDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\MethodInjectionDriver');
            break;
        case 'dingMessageSourceDriver':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Bean\Factory\Driver\MessageSourceDriver');
            break;
        case 'dingReflectionFactory':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Reflection\ReflectionFactory');
            $bean->setArguments(array(
                new BeanConstructorArgumentDefinition(
                    BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                    isset($this->options['bdef']['annotation'])
                )
            ));
            $bean->setProperties(array(
                new BeanPropertyDefinition(
                	'cache', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingAnnotationsCache'
                ),
                new BeanPropertyDefinition(
                	'annotationParser', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingAnnotationParser'
                )
            ));
            break;
        case 'dingProxyFactory':
            $bean = new BeanDefinition($name);
            $bean->setClass('\Ding\Aspect\Proxy');
            $bean->setProperties(array(
                new BeanPropertyDefinition(
                	'cache', BeanPropertyDefinition::PROPERTY_BEAN,
                	'dingProxyCache'
                )
            ));
            break;
        default:
            break;
        }
        return $bean;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Bean.IBeanDefinitionProvider::getBeansListeningOn()
     */
    public function getBeansListeningOn($eventName)
    {
        return array();
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Bean.IBeanDefinitionProvider::getByClass()
     */
    public function getBeansByClass($class)
    {
        return array();
    }

    public function __construct($options = array())
    {
        $this->options = $options;
    }
}


<?php
/**
 * Aspect dispatcher implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Aspect
 * @subpackage Interceptor
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Aspect\Interceptor;
use Ding\Reflection\IReflectionFactoryAware;
use Ding\Reflection\IReflectionFactory;
use Ding\Aspect\MethodInvocation;

/**
 * Aspect dispatcher implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Aspect
 * @subpackage Interceptor
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class DispatcherImpl implements IDispatcher, IReflectionFactoryAware
{
    /**
     * A ReflectionFactory implementation
     * @var IReflectionFactory
     */
    protected $reflectionFactory;

    /**
     * Associated array for methods intercepted.
     * @var object[]
     */
    private $_methodsIntercepted;

    /**
     * Associated array for methods intercepted for exceptions.
     * @var object[]
     */
    private $_methodsExceptionIntercepted;

    /**
     * Interceptor classes.
     * @var string[]
     */
    private $_interceptorClasses;

    /**
     * (non-PHPdoc)
     * @see Ding\Aspect\Interceptor.IDispatcher::hasMethodsIntercepted()
     */
    public function hasMethodsIntercepted()
    {
        return
            count($this->_methodsExceptionIntercepted) > 0
            || count($this->_methodsIntercepted) > 0
        ;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Aspect\Interceptor.IDispatcher::getMethodsIntercepted()
     */
    public function getMethodsIntercepted()
    {
        return array_keys(array_merge(
            $this->_methodsExceptionIntercepted,
            $this->_methodsIntercepted
        ));
    }
    /**
     * (non-PHPdoc)
     * @see Ding\Reflection.IReflectionFactoryAware::setReflectionFactory()
     */
    public function setReflectionFactory(IReflectionFactory $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Aspect\Interceptor.IDispatcher::addMethodInterceptor()
     */
    public function addMethodInterceptor($method, $interceptor, $interceptorMethod)
    {
        $this->_methodsIntercepted[$method][] = new AdviceDefinition(
            $method, $interceptor, $interceptorMethod
        );
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Aspect\Interceptor.IDispatcher::addExceptionInterceptor()
     */
    public function addExceptionInterceptor($method, $interceptor, $interceptorMethod)
    {
        $this->_methodsExceptionIntercepted[$method][] = new AdviceDefinition(
            $method, $interceptor, $interceptorMethod
        );
    }

    /**
     * Returns interceptors for a given method name or false if none was set.
     *
     * @param string $method Method to check for.
     *
     * @return object[]
     */
    public function getInterceptors($method)
    {
        if (!isset($this->_methodsIntercepted[$method])) {
            return false;
        }
        return $this->_methodsIntercepted[$method];
    }

    /**
     * Returns exception interceptors for a given method name or
     * false if none was set.
     *
     * @param string $method Method to check for.
     *
     * @return object[]
     */
    public function getExceptionInterceptors($method)
    {
        if (!isset($this->_methodsExceptionIntercepted[$method])) {
            return false;
        }
        return $this->_methodsExceptionIntercepted[$method];
    }

    /**
     * Will chain and return the result of the chained call of interceptors.
     *
     * @param MethodInvocation $invocation   Original invocation to preserve.
     * @param object[]         $interceptors Array of interceptors.
     *
     * @return mixed
     */
    private function _callInterceptors(
        MethodInvocation $invocation, array $interceptors
    ) {
        $total = count($interceptors) - 1;
        $invocationChain = $invocation;
        for ($i = $total; $i >= 0; $i--) {
            $newInvocation = new MethodInvocation(
                get_class($interceptors[$i]->getInterceptor()),
                $interceptors[$i]->getInterceptorMethod(),
                array($invocationChain),
                $interceptors[$i]->getInterceptor(),
                $this->reflectionFactory,
                $invocation
            );
            $invocationChain = $newInvocation;
        }
        return $invocationChain->proceed();
    }

    /**
     * The proxy will call this method when an aspected method throws an
     * exception.
     *
     * @param MethodInvocation $invocation Method invocation "descriptor".
     *
     * @return void
     */
    public function invokeException(MethodInvocation $invocation)
    {
        $interceptors = $this->getExceptionInterceptors($method = $invocation->getMethod());
        if ($interceptors != false && !empty($interceptors)) {
            return $this->_callInterceptors($invocation, $interceptors);
        }
        throw $invocation->getException();
    }

    /**
     * The proxy will call this method when an aspected method is called.
     *
     * @param MethodInvocation $invocation Method invocation "descriptor".
     *
     * @return void
     */
    public function invoke(MethodInvocation $invocation)
    {
        $interceptors = $this->getInterceptors($invocation->getMethod());
        if ($interceptors != false) {
            return $this->_callInterceptors($invocation, $interceptors);
        }
        return $invocation->proceed();
    }

    /**
     * Constructor.
     *
     * @return void
     */
    public function __construct()
    {
        $this->_methodsIntercepted = array();
        $this->_methodsExceptionIntercepted = array();
    }
}


<?php
/**
 * Tcp Client helper. You need to declare(ticks) in your own source code or
 * manually call process() in an infinite loop from your software.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Tcp
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Helpers\Tcp;

use Ding\Helpers\Tcp\Exception\TcpException;

/**
 * Tcp Client helper. You need to declare(ticks) in your own source code or
 * manually call process() in an infinite loop from your software.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Helpers
 * @subpackage Tcp
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class TcpClientHelper
{
    /**
     * Target port
     * @var integer
     */
    private $_port;

    /**
     * Target host or ip address.
     * @var string
     */
    private $_address;

    /**
     * Socket resource.
     * @var socket
     */
    private $_socket;

    /**
     * Handler for this connection (your class).
     * @var ITcpClientHandler
     */
    private $_handler;

    /**
     * Minimum needed bytes in the socket before calling data() on the handler.
     * @var integer
     */
    private $_readLen;

    /**
     * Read timeout in milliseconds.
     * @var integer
     */
    private $_rTo;

    /**
     * Connection timeout in milliseconds.
     * @var integer
     */
    private $_cTo;

    /**
     * Internal flag in order to know if the socket is connected.
     * @var boolean
     */
    private $_connected;

    /**
     * Time for last data received. Used to control read timeout.
     * @var float
     */
    private $_lastDataReadTime;

    /**
     * Wether to reuse or not the binding of the socket.
     * @var boolean
     */
    private $_reuse;

    /**
     * Call this to close the connection.
     *
     * @return void
     */
    public function close()
    {
        $this->_connected = false;
        $this->_handler->disconnect();
        socket_close($this->_socket);
        $this->_socket = false;
    }

    /**
     * Call this to read data from the server. Returns the number of bytes read.
     *
     * @param string  $buffer Where to store the read data.
     * @param integer $length Maximum length of data to read.
     * @param boolean $peek   If true, will not remove the data from the socket.
     *
     * @return integer
     */
    public function read(&$buffer, $length, $peek = false)
    {
        $length = socket_recv($this->_socket, $buffer, $length, $peek ? MSG_PEEK : 0);
        return $length;
    }

    /**
     * Call this to send data to the server. Returns the number of bytes
     * sent.
     *
     * @param string $what What to send.
     *
     * @return integer
     */
    public function write($what)
    {
        return socket_send($this->_socket, $what, strlen($what), 0);
    }

    /**
     * Call this to open the connection to the server. Will also set the
     * socket non blocking and control the connection timeout.
     *
     * @param string  $address Optional output ip address.
     * @param integer $port    Optional output port.
     *
     * @throws TcpException
     * @return void
     */
    public function open($address = false, $port = false)
    {
        $this->_connected = false;
        $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        if ($this->_socket === false) {
            throw new TcpException(
            	'Error opening socket: ' . socket_strerror(socket_last_error())
            );
        }
        if ($this->_reuse) {
            socket_set_option ($this->_socket, SOL_SOCKET, SO_REUSEADDR, 1);
        }
        if ($address !== false) {
            if (!@socket_bind($this->_socket, $address, $port)) {
                throw new TcpException(
                	'Error binding socket: ' . socket_strerror(socket_last_error())
                );
            }
        }
        if ($this->_cTo > 0) {
            socket_set_nonblock($this->_socket);
            $timer = 0;
        } else {
            socket_set_block($this->_socket);
            $timer = -1;
        }
        $result = false;
        $this->_handler->beforeConnect();
        for(; $timer < $this->_cTo; $timer++)
        {
            $result = @socket_connect(
                $this->_socket, $this->_address, intval($this->_port)
            );
            if ($result === true) {
                break;
            }
            $error = socket_last_error();
            if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
                socket_close($this->_socket);
                $error = socket_strerror($error);
                $this->_socket = false;
                throw new TcpException('Could not connect: ' . $error);
            }
            // Use the select() as a sleep.
            $read = array($this->_socket);
            $write = null;
            $ex = null;
            $result = @socket_select($read, $write, $ex, 0, 650);
        }
        if (!$result) {
            $this->_handler->connectTimeout();
            socket_close($this->_socket);
            $this->_socket = false;
            return;
        }
        socket_set_nonblock($this->_socket);
        $this->_lastDataReadTime = $this->getMicrotime();
        $this->_connected = true;
        $this->_handler->connect();
        register_tick_function(array($this, 'process'));
    }

    /**
     * From php examples. Returns time including millseconds.
     *
     * @todo duplicated code, where can this go?
     * @return float
     */
    protected function getMicrotime()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }

    /**
     * Main reading loop. Call this in your own infinite loop or declare(ticks)
     * in your software. This routine will call your client handler when there
     * is data available to read. Will always detect when the other side closed
     * the connection.
     *
     * @return void
     */
    public function process()
    {
        if ($this->_socket === false || !$this->_connected) {
            return;
        }
        $read = array($this->_socket);
        $write = null;
        $ex = null;
        $result = @socket_select($read, $write, $ex, 0, 1);
        if ($result === false) {
            throw new TcpException(
            	'Error selecting from socket: '
                . socket_strerror(socket_last_error($this->_socket))
            );
        }
        if ($result > 0) {
            if (in_array($this->_socket, $read)) {
                $buffer = '';
                $len = 1;
                $len = $this->read($buffer, $len, true);
                if ($len > 0) {
                    if ($len >= $this->_readLen) {
                        $this->_lastDataReadTime = $this->getMicrotime();
                        $this->_handler->data();
                        return;
                    }
                } else {
                    $this->close();
                    return;
                }
            }
        }
        $now = $this->getMicrotime();
        if (($now - $this->_lastDataReadTime) > $this->_rTo) {
            if ($this->_rTo > 0) {
                $this->_handler->readTimeout();
            }
            $this->_lastDataReadTime = $now;
        }
    }

    /**
     * Minimum needed bytes available in the socket before calling data() on the
     * client handler.
     *
     * @param integer $rLen Minimum data needed in socket.
     *
     * @return void
     */
    public function setReadMinLength($rLen)
    {
        $this->_readLen = intval($rLen);
    }

    /**
     * Sets the read timeout in milliseconds. 0 to disable.
     *
     * @param integer $rTo Read timeout.
     *
     * @return void
     */
    public function setReadTimeout($rTo)
    {
        $this->_rTo = (float)($rTo / 1000);
    }

    /**
     * Sets connection timeout in milliseconds. 0 to disable.
     *
     * @param integer $cTo Connection timeout.
     *
     * @return void
     */
    public function setConnectTimeout($cTo)
    {
        $this->_cTo = intval($cTo);
    }

    /**
     * Sets the tcp client handler.
     *
     * @param ITcpClientHandler $handler Client handler to use for callbacks.
     *
     * @return void
     */
    public function setHandler(ITcpClientHandler $handler)
    {
        $this->_handler = $handler;
        $handler->setClient($this);
    }

    /**
     * Sets server port.
     *
     * @param integer $port Server port.
     *
     * @return void
     */
    public function setPort($port)
    {
        $this->_port = $port;
    }

    /**
     * Sets server host or ip address.
     *
     * @param string $address Server host or ip address.
     *
     * @return void
     */
    public function setAddress($address)
    {
        $this->_address = $address;
    }

    /**
     * Sets wether to reuse or not the socket bind.
     *
     * @param boolean $reuse True to reuse the binding address.
     *
     * @return void
     */
    public function setReuse($reuse)
    {
        $this->_reuse = $reuse;
    }

    /**
     * Constructor. Not much to see here. Will register a tick function(),
     * process().
     *
     * @return void
     */
    public function __construct()
    {
        $this->_handler = false;
        $this->_socket = false;
        $this->_address = false;
        $this->_port = false;
        $this->_cTo = 0;
        $this->_rTo = 0;
        $this->_rLen = 1;
        $this->_connected = false;
        $this->_reuse = false;
    }
}


<?php
/**
 * This driver will search for @Value
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Bean\Factory\Driver;

use Ding\Annotation\Collection;
use Ding\Bean\BeanConstructorArgumentDefinition;
use Ding\Logger\ILoggerAware;
use Ding\Reflection\IReflectionFactory;
use Ding\Reflection\IReflectionFactoryAware;
use Ding\Container\IContainerAware;
use Ding\Container\IContainer;
use Ding\Bean\Factory\Exception\BeanFactoryException;
use Ding\Bean\BeanPropertyDefinition;
use Ding\Bean\Lifecycle\IAfterDefinitionListener;
use Ding\Bean\Lifecycle\IAfterCreateListener;
use Ding\Bean\BeanDefinition;

/**
 * This driver will search for @Resource setter methods.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class AnnotationValueDriver
    implements IAfterDefinitionListener, IContainerAware, IReflectionFactoryAware
{
    /**
     * Container.
     * @var IContainer
     */
    private $_container;

    /**
     * A ReflectionFactory implementation.
     * @var IReflectionFactory
     */
    protected $reflectionFactory;

    /**
     * (non-PHPdoc)
     * @see Ding\Reflection.IReflectionFactoryAware::setReflectionFactory()
     */
    public function setReflectionFactory(IReflectionFactory $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;
    }

    /**
     * (non-PHPdoc)
     * @see Ding\Container.IContainerAware::setContainer()
     */
    public function setContainer(IContainer $container)
    {
        $this->_container = $container;
    }

    private function _applyToConstructor(Collection $annotations, BeanDefinition $bean)
    {
        $constructorArguments = $bean->getArguments();
        if ($annotations->contains('value')) {
            foreach ($annotations->getAnnotations('value') as $annotation) {
                if ($annotation->hasOption('value')) {
                    foreach ($annotation->getOptionValues('value') as $value) {
                        $argName = false;
                        if ($annotation->hasOption('name')) {
                            $argName = $annotation->getOptionSingleValue('name');
                        }
                        $constructorArguments[] = new BeanConstructorArgumentDefinition(
                            BeanConstructorArgumentDefinition::BEAN_CONSTRUCTOR_VALUE,
                            $value, $argName
                        );
                    }
                }
            }
        }
        $bean->setArguments($constructorArguments);
    }
    /**
     * (non-PHPdoc)
     * @see Ding\Bean\Lifecycle.IAfterDefinitionListener::afterDefinition()
     */
    public function afterDefinition(BeanDefinition $bean)
    {
        $properties = $bean->getProperties();
        $class = $bean->getClass();
        $rClass = $this->reflectionFactory->getClass($class);
        foreach ($rClass->getProperties() as $rProperty) {
            $propertyName = $rProperty->getName();
            $annotations = $this->reflectionFactory->getPropertyAnnotations($class, $propertyName);
            if ($annotations->contains('value')) {
                $annotation = $annotations->getSingleAnnotation('value');
                if ($annotation->hasOption('value')) {
                    $value = $annotation->getOptionSingleValue('value');
                    $properties[$propertyName] = new BeanPropertyDefinition(
                        $propertyName, BeanPropertyDefinition::PROPERTY_SIMPLE, $value
                    );
                }
            }
        }
        $bean->setProperties($properties);
        if ($bean->isCreatedWithFactoryBean()) {
            $factoryMethod = $bean->getFactoryMethod();
            $factoryBean = $bean->getFactoryBean();
            $def = $this->_container->getBeanDefinition($factoryBean);
            $annotations = $this->reflectionFactory->getMethodAnnotations(
                $def->getClass(), $factoryMethod
            );
            $this->_applyToConstructor($annotations, $bean);
        } else if ($bean->isCreatedByConstructor()) {
            $class = $bean->getClass();
            $rClass = $this->reflectionFactory->getClass($bean->getClass());
            $rMethod = $rClass->getConstructor();
            if ($rMethod) {
                $annotations = $this->reflectionFactory->getMethodAnnotations(
                    $class, $rMethod->getName()
                );
                $this->_applyToConstructor($annotations, $bean);
            }
        }
        return $bean;
    }
}


<?php
/**
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Bean\Factory\Driver;

use Ding\Reflection\IReflectionFactoryAware;
use Ding\Bean\IBeanDefinitionProvider;
use Ding\Container\IContainerAware;
use Ding\Mvc\Http\HttpUrlMapper;
use Ding\Bean\Lifecycle\IAfterConfigListener;
use Ding\Bean\BeanDefinition;
use Ding\Container\IContainer;
use Ding\Reflection\IReflectionFactory;

/**
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Bean
 * @subpackage Factory.Driver
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class MvcAnnotationDriver
    implements IAfterConfigListener, IContainerAware, IReflectionFactoryAware
{
    /**
     * Container.
     * @var IContainer
     */
    private $_container;
    /**
     * A ReflectionFactory implementation.
     * @var IReflectionFactory
     */
    protected $reflectionFactory;

    /**
     * (non-PHPdoc)
     * @see Ding\Reflection.IReflectionFactoryAware::setReflectionFactory()
     */
    public function setReflectionFactory(IReflectionFactory $reflectionFactory)
    {
        $this->reflectionFactory = $reflectionFactory;
    }
    /**
     * (non-PHPdoc)
     * @see Ding\Container.IContainerAware::setContainer()
     */
    public function setContainer(IContainer $container)
    {
        $this->_container = $container;
    }
    /**
     * Will call HttpUrlMapper::addAnnotatedController to add new mappings
     * from the @Controller annotated classes. Also, creates a new bean
     * definition for every one of them.
     *
     * (non-PHPdoc)
     * @see Ding\Bean\Lifecycle.ILifecycleListener::afterConfig()
     */
    public function afterConfig()
    {
        foreach ($this->reflectionFactory->getClassesByAnnotation('controller') as $controller) {
            foreach ($this->_container->getBeansByClass($controller) as $name) {
                $annotations = $this->reflectionFactory->getClassAnnotations($controller);
                if (!$annotations->contains('requestmapping')) {
                    continue;
                }
                $requestMappings = $annotations->getAnnotations('requestmapping');
                foreach ($requestMappings as $map) {
                    if ($map->hasOption('url')) {
                        foreach ($map->getOptionValues('url') as $url) {
                            HttpUrlMapper::addAnnotatedController($url, $name);
                        }
                    }
                }
            }
        }
    }
}


<?php
/**
 * This class handles the mapping between the view and model.
 *
 * PHP Version 5
 *
 * @category Ding
 * @package  Mvc
 * @author   Marcelo Gornstein <marcelog@gmail.com>
 * @license  http://marcelog.github.com/ Apache License 2.0
 * @link     http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Mvc;

/**
 * This class handles the mapping between the view and model.
 *
 * PHP Version 5
 *
 * @category Ding
 * @package  Mvc
 * @author   Marcelo Gornstein <marcelog@gmail.com>
 * @license  http://marcelog.github.com/ Apache License 2.0
 * @link     http://marcelog.github.com/
 */
class ModelAndView
{
    /**
     * Objects from the model.
     * @var mixed[]
     */
    private $_objects;

    /**
     * Model-View name. This will get used to find the view name.
     * @var string
     */
    private $_name;

    /**
     * Add model objects.
     *
     * @param array $objects Key = object name (string), value is mixed.
     *
     * @return void
     */
    public function add(array $objects)
    {
        foreach ($objects as $name => $value) {
            $this->_objects[$name] = $value;
        }
    }

    /**
     * Returns the model. Intended to be used from the view.
     * Key = object name (string), value is mixed.
     *
     * @return array
     */
    public function getModel()
    {
        return $this->_objects;
    }

    /**
     * Returns the corresponding view name for this model-view.
     *
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * True if this model has no objects.
     *
	 * @return boolean
     */
    public function isEmpty()
    {
        return count($this->_objects) == 0;
    }
    /**
     * Constructor.
     *
     * @param string $name    Model-View name.
     * @param array  $options Model-View objects.
     *
     * @return void
     */
    public function __construct($name, array $options = array())
    {
        $this->_objects = $options;
        $this->_name = $name;
    }
}


<?php
/**
 * Simple file cache implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Impl
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 *
 * Copyright 2011 Marcelo Gornstein <marcelog@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
namespace Ding\Cache\Impl;
use Ding\Cache\ICache;
use Ding\Cache\Exception\FileCacheException;

/**
 * Simple file cache implementation.
 *
 * PHP Version 5
 *
 * @category   Ding
 * @package    Cache
 * @subpackage Impl
 * @author     Marcelo Gornstein <marcelog@gmail.com>
 * @license    http://marcelog.github.com/ Apache License 2.0
 * @link       http://marcelog.github.com/
 */
class FileCacheImpl implements ICache
{
    /**
     * Holds current instances.
     * @var FileCacheImpl[]
     */
    private static $_instances = false;

    /**
     * Current assigned directory.
     * @var string
     */
    private $_directory;

    /**
     * Returns a cached value.
     *
     * @param string  $name    Key to look for.
     * @param boolean &$result True on success, false otherwise.
     *
     * @return mixed
     */
    public function fetch($name, &$result)
    {
        $result = false;
        $filename = $this->_directory . $this->_sanitize($name);
        clearstatcache(false, $filename);
        if (!@file_exists($filename)) {
            return false;
        }
        $result = true;
        $data = @file_get_contents($filename);
        $data = unserialize($data);
        return $data;
    }

    /**
     * Converts a cache key name into a string that can be saved into a
     * filesystem.
     *
     * @param string $name
     *
     * @return string
     */
    private function _sanitize($name)
    {
        return str_replace('/', '_', str_replace('\\', '_', $name));
    }

    /**
     * Stores a key/value.
     *
     * @param string $name  Key to use.
     * @param mixed  $value Value.
     *
     * @return boolean
     */
    public function store($name, $value)
    {
        $value = serialize($value);
        $name = $this->_sanitize($name);
        return @file_put_contents($this->_directory . $name, $value);
    }

    /**
     * Empties the cache.
     *
     * @todo implement this
	 * @return boolean
     */
    public function flush()
    {
        foreach (glob($this->_directory . '/[^.]*') as $file) {
            @unlink($file);
        }
    }

    /**
     * Removes a key from the cache.
     *
     * @param string $name Key to remove.
     *
     * @return boolean
     */
    public function remove($name)
    {
        return @unlink($this->_directory . $name);
    }

    /**
     * Returns an instance of a cache.
     *
     * @param array $options Options for the cache backend.
     *
     * @return DummyCacheImpl
     */
    public static function getInstance($options = array())
    {
        $dir = $options['directory'];
        if (!isset(self::$_instances[$dir])) {
            $ret = new FileCacheImpl($options);
            self::$_instances[$dir] = $ret;
            $ret->_init();
        } else {
            $ret = self::$_instances[$dir];
        }
        return $ret;
    }

    /**
     * Initializes this cache (creates directories, etc).
     *
     * @throws FileCacheException
     * @return void
     */
    private function _init()
    {
        if (!file_exists($this->_directory)) {
            if (@mkdir($this->_directory, 0750, true) === false) {
                throw new FileCacheException(
                    'Could not create: ' . $this->_directory
                );
            }
        }
    }

    /**
     * Constructor.
     *
	 * @return void
     */
    private function __construct(array $options)
    {
        $this->_directory = $options['directory'];
        if ($this->_directory[strlen($this->_directory) - 1] !== '/') {
            $this->_directory .= '/';
        }
    }
}


<?php

/*
 * This file is part of Laravel Whoops Editor.
 *
 * (c) Anton Komarev <a.komarev@cybercog.su>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Cog\Laravel\WhoopsEditor\Providers;

use Illuminate\Support\ServiceProvider;

/**
 * Class WhoopsEditorServiceProvider.
 *
 * @package Cog\Laravel\WhoopsEditor\Providers
 */
class WhoopsEditorServiceProvider extends ServiceProvider
{
    /**
     * @var \Illuminate\Contracts\Config\Repository
     */
    private $config;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPublishes();
        $this->overwriteAppConfig();
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->configure();
    }

    /**
     * Setup the configuration for Whoops Editor.
     *
     * @return void
     */
    protected function configure()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/../../config/whoops-editor.php', 'whoops-editor'
        );
    }

    /**
     * Setup the resource publishing groups for Whoops Editor.
     *
     * @return void
     */
    protected function registerPublishes()
    {
        $this->publishes([
            __DIR__ . '/../../config/whoops-editor.php' => config_path('whoops-editor.php'),
        ], 'config');
    }

    /**
     * Build URI for editor based on file path and line.
     *
     * @param string $uri
     * @param string $filePath
     * @param int $line
     * @return string
     */
    protected function buildUri(string $uri, string $filePath, int $line): string
    {
        $uri = str_replace('%file', $filePath, $uri);
        $uri = str_replace('%line', $line, $uri);

        return $uri;
    }

    /**
     * Overwrite application editor config with Whoops Editor.
     *
     * @return void
     */
    protected function overwriteAppConfig()
    {
        $this->config = $this->app->make('config');
        $editor = $this->resolveEditor();
        $editorConfig = $this->config->get('whoops-editor.editors.' . $editor);
        if (!$editorConfig) {
            $this->overwriteAppEditor($editor);

            return;
        }

        $this->overwriteAppEditor(function ($filePath, $line) use ($editorConfig) {
            $filePath = $this->resolveFilePath($filePath);

            if (is_string($editorConfig)) {
                return $this->buildUri($editorConfig, $filePath, $line);
            }

            $editorConfig['url'] = $this->buildUri($editorConfig['url'], $filePath, $line);

            return $editorConfig;
        });
    }

    /**
     * Overwrite application editor configuration value.
     *
     * @param string|\Closure $editor
     */
    protected function overwriteAppEditor($editor)
    {
        $this->config->set('app.editor', $editor);
    }

    /**
     * Resolve code editor.
     *
     * @return mixed
     */
    protected function resolveEditor()
    {
        return $this->config->get('app.editor', $this->config->get('whoops-editor.editor'));
    }

    /**
     * Resolve file path when using Homestead.
     *
     * @param string $filePath
     * @return string
     */
    protected function resolveFilePath(string $filePath): string
    {
        $localPath = $this->config->get('whoops-editor.local-projects-path');
        $homesteadPath = $this->config->get('whoops-editor.homestead-projects-path');

        if (!$localPath || !$homesteadPath) {
            return $filePath;
        }

        $local = rtrim($localPath, '/');
        $homestead = rtrim($homesteadPath, '/');

        return str_replace("{$homestead}/", "{$local}/", $filePath);
    }
}


<?php

namespace bupy7\pages\models;

use Yii;
use bupy7\pages\Module;
use yii\behaviors\SluggableBehavior;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;

/**
 * This is the model class for table "{{%pages}}".
 *
 * @property integer $id
 * @property string $title
 * @property boolean $display_title
 * @property string $alias
 * @property integer $published
 * @property string|null $content
 * @property string|null $title_browser
 * @property string|null $meta_keywords
 * @property string|null $meta_description
 * @property string $created_at
 * @property string $updated_at
 *
 * @since 1.4.0 Added the $display_title property
 *
 * @author Belosludcev Vasilij <bupy765@gmail.com>
 * @since 1.0.0
 */
class Page extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'sluggable' => [
                'class' => SluggableBehavior::class,
                'attribute' => 'title',
                'slugAttribute' => 'alias',
                'immutable' => true,
            ],
            'timestamp' => [
                'class' => TimestampBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
                'value' => new Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return Yii::$app->getModule('pages')->tableName;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title'], 'required'],
            [['display_title', 'published'], 'boolean'],
            [['content'], 'string', 'max' => 65535],
            [['title', 'alias', 'title_browser'], 'string', 'max' => 255],
            [['meta_keywords'], 'string', 'max' => 200],
            [['meta_description'], 'string', 'max' => 160],
            [['alias'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Module::t('ID'),
            'title' => Module::t('TITLE'),
            'display_title' => Module::t('DISPLAY_TITLE'),
            'alias' => Module::t('ALIAS'),
            'published' => Module::t('PUBLISHED'),
            'content' => Module::t('CONTENT'),
            'title_browser' => Module::t('TITLE_BROWSER'),
            'meta_keywords' => Module::t('META_KEYWORDS'),
            'meta_description' => Module::t('META_DESCRIPTION'),
            'created_at' => Module::t('CREATED_AT'),
            'updated_at' => Module::t('UPDATED_AT'),
        ];
    }

    /**
     * List values of field 'published' with label.
     * @return array
     */
    public static function publishedDropDownList()
    {
        $formatter = Yii::$app->formatter;
        return [
            false => $formatter->asBoolean(false),
            true => $formatter->asBoolean(true),
        ];
    }
}


<?php

/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\Links\Api\Controller;

use Flarum\User\AssertPermissionTrait;
use Flarum\Http\Controller\ControllerInterface;
use Sijad\Links\Link;
use Psr\Http\Message\ServerRequestInterface;
use Zend\Diactoros\Response\EmptyResponse;

class OrderLinksController implements ControllerInterface
{
    use AssertPermissionTrait;

    /**
     * {@inheritdoc}
     */
    public function handle(ServerRequestInterface $request)
    {
        $this->assertAdmin($request->getAttribute('actor'));

        $order = array_get($request->getParsedBody(), 'order');

        foreach ($order as $i => $link) {
            Link::where('id', $link['id'])->update(['position' => $i]);
        }

        return new EmptyResponse(204);
    }
}


<?php

namespace bupy7\pages\controllers;

use yii\web\Controller;
use bupy7\pages\models\Page;
use yii\web\NotFoundHttpException;
use bupy7\pages\Module;

/**
 * View pages of module.
 *
 * @author Belosludcev Vasilij http://mihaly4.ru
 * @since 1.0.0
 */
class DefaultController extends Controller
{

    /**
     * View of page by alias.
     * @param string $page Alias of page.
     * @return string
     * @see Page::$alias
     */
    public function actionIndex($page)
    {
        $model = $this->findModel($page);
        return $this->render('index', [
            'model' => $model,
        ]);
    }

    /**
     * Finds the Page model based on alias value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $alias
     * @return Page the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($alias)
    {
        $model = Page::find()->where([
            'alias' => $alias,
            'published' => true,
        ])->one();
        if ($model !== null) {
            return $model;
        }
        throw new NotFoundHttpException(Module::t('PAGE_NOT_FOUND'));
    }
}


<?php

/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\Links\Api\Serializer;

use Flarum\Api\Serializer\AbstractSerializer;
use Flarum\Api\Serializer\DiscussionSerializer;

class LinkSerializer extends AbstractSerializer
{
    /**
     * {@inheritdoc}
     */
    protected $type = 'links';

    /**
     * {@inheritdoc}
     */
    protected function getDefaultAttributes($link)
    {
        $attributes = [
            'id'         => $link->id,
            'title'      => $link->title,
            'url'        => $link->url,
            'position'   => $link->position,
            'isInternal' => $link->is_internal,
            'isNewtab'   => $link->is_newtab,
        ];

        return $attributes;
    }
}


<?php

namespace bupy7\pages\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * PageSearch represents the model behind the search form about `bupy7\pages\models\Page`.
 *
 * @author Belosludcev Vasilij <bupy765@gmail.com>
 * @since 1.0.0
 */
class PageSearch extends Page
{
    /**
     * @inheritdoc
     * @since 1.3.0
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        unset($behaviors['sluggable']);
        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'published'], 'integer'],
            [['title', 'alias'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Page::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'published' => $this->published,
        ]);

        $query->andFilterWhere(['like', 'title', $this->title])
            ->andFilterWhere(['like', 'alias', $this->alias]);

        return $dataProvider;
    }
}


<?php

/*
 * (c) Sajjad Hashemian <wolaws@gmail.com>
 */

namespace Sijad\Links;

use Flarum\Database\AbstractModel;

class Link extends AbstractModel
{
    /**
     * {@inheritdoc}
     */
    protected $table = 'links';

    /**
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'is_internal' => 'boolean',
        'is_newtab' => 'boolean',
    ];

    /**
     * Create a new link.
     *
     * @param string $name
     * @param string $url
     * @param bool $isInternal
     * @param bool $isNewtab
     * @return static
     */
    public static function build($name, $url, $isInternal, $isNewtab)
    {
        $link = new static;

        $link->title               = $name;
        $link->url                 = $url;
        $link->is_internal         = (bool) $isInternal;
        $link->is_newtab           = (bool) $isNewtab;

        return $link;
    }
}