public function getBeanDefinition($name)
    {
        if (isset($this->_beanAliases[$name])) {
            $name = $this->_beanAliases[$name];
        }
        if (isset($this->_beanDefs[$name])) {
            return $this->_beanDefs[$name];
        }
        $beanDefinition = null;
        if ($this->_beanDefCache !== null) {
            $beanDefinition = $this->_beanDefCache->fetch($name, $result);
        }
        if ($beanDefinition) {
            $this->_beanDefs[$name] = $beanDefinition;
            return $beanDefinition;
        }
        foreach ($this->_beanDefinitionProviders as $provider) {
            $beanDefinition = $provider->getBeanDefinition($name);
            if ($beanDefinition) {
                $beanDefinition->setClass($this->_searchAndReplaceProperties(
                    $beanDefinition->getClass()
                ));
                break;
            }
        }
        if (!$beanDefinition) {
            throw new BeanFactoryException('Unknown bean: ' . $name);
        }
        $beanDefinition = $this->_lifecycleManager->afterDefinition($beanDefinition);
        $this->_beanDefs[$name] = $beanDefinition;
        $this->_beanDefCache->store($name, $beanDefinition);
        foreach ($beanDefinition->getAliases() as $alias) {
            $this->_beanAliases[$alias] = $name;
        }
        return $beanDefinition;
    }

public
function
getBeanDefinition
(
$
name
)
{
if
(
isset
(
$
this
->
_beanAliases
[
$
name
]
)
)
{
$
name
=
$
this
->
_beanAliases
[
$
name
]
;
}
if
(
isset
(
$
this
->
_beanDefs
[
$
name
]
)
)
{
return
$
this
->
_beanDefs
[
$
name
]
;
}
$
beanDefinition
=
;
if
(
$
this
->
_beanDefCache
!==
)
{
$
beanDefinition
=
$
this
->
_beanDefCache
->
fetch
(
$
name
,
$
result
)
;
}
if
(
$
beanDefinition
)
{
$
this
->
_beanDefs
[
$
name
]
=
$
beanDefinition
;
return
$
beanDefinition
;
}
foreach
(
$
this
->
_beanDefinitionProviders
as
$
provider
)
{
$
beanDefinition
=
$
provider
->
getBeanDefinition
(
$
name
)
;
if
(
$
beanDefinition
)
{
$
beanDefinition
->
setClass
(
$
this
->
_searchAndReplaceProperties
(
$
beanDefinition
->
getClass
(
)
)
)
;
break
;
}
}
if
(
!
$
beanDefinition
)
{
throw
new
BeanFactoryException
(
'Unknown bean: '
.
$
name
)
;
}
$
beanDefinition
=
$
this
->
_lifecycleManager
->
afterDefinition
(
$
beanDefinition
)
;
$
this
->
_beanDefs
[
$
name
]
=
$
beanDefinition
;
$
this
->
_beanDefCache
->
store
(
$
name
,
$
beanDefinition
)
;
foreach
(
$
beanDefinition
->
getAliases
(
)
as
$
alias
)
{
$
this
->
_beanAliases
[
$
alias
]
=
$
name
;
}
return
$
beanDefinition
;
}

Returns a bean definition.

@param string $name Bean name.

@return BeanDefinition
@throws BeanFactoryException


private function _searchAndReplaceProperties($value)
    {
        if (is_string($value)) {
            foreach ($this->_properties as $k => $v) {
                if (strpos($value, $k) !== false) {
                    if (is_string($v)) {
                        $value = str_replace($k, $v, $value);
                    } else {
                        $value = $v;
                        // Assigned value is not a string, so we cant use
                        // strpos anymore on it (i.e: cant continue replacing)
                        break;
                    }
                }
            }
        }
        return $value;
    }

Will try to search and replace the properties found in the given
value.

@param string $value

@return string

Will try to search and replace the properties found in the given value .


private function _getConstructorValuesForDefinition($definition)
    {
        $args = array();
        foreach ($definition->getArguments() as $argument) {
            $value = $this->_getValueFromDefinition($argument);
            if ($argument->hasName()) {
                $name = $argument->getName();
                $args[$name] = $value;
            } else {
                $args[] = $value;
            }
        }
        return $args;
    }

private function _getConstructorValuesForDefinition ( $ definition ) { $ args = array ( ) ; foreach ( $ definition -> getArguments ( ) as $ argument ) { $ value = $ this -> _getValueFromDefinition ( $ argument ) ; if ( $ argument -> hasName ( ) ) { $ name = $ argument -> getName ( ) ; $ args [ $ name ] = $ value ; } else { $ args [ ] = $ value ; } } return $ args ; }

Resolves all values for constructor arguments definitions in a
bean definition.

@param BeanDefinition $definition

@return object

Resolves all values for constructor arguments definitions in a bean definition .


private function _instantiateByConstructor(BeanDefinition $definition)
    {
        $class = $definition->getClass();
        if ($definition->hasProxyClass()) {
            $class = $definition->getProxyClassName();
        }
        $rClass = $this->_reflectionFactory->getClass($class);
        $factoryMethod = $rClass->getConstructor();
        if ($factoryMethod !== null) {
            $args = $this->_sortArgsWithNames($definition, $factoryMethod);
            if (empty($args)) {
                return $rClass->newInstanceArgs();
            } else {
                return $rClass->newInstanceArgs($args);
            }
        } else {
            return $rClass->newInstanceArgs();
        }
    }

private function _instantiateByConstructor ( BeanDefinition $ definition ) { $ class = $ definition -> getClass ( ) ; if ( $ definition -> hasProxyClass ( ) ) { $ class = $ definition -> getProxyClassName ( ) ; } $ rClass = $ this -> _reflectionFactory -> getClass ( $ class ) ; $ factoryMethod = $ rClass -> getConstructor ( ) ; if ( $ factoryMethod !== null ) { $ args = $ this -> _sortArgsWithNames ( $ definition , $ factoryMethod ) ; if ( empty ( $ args ) ) { return $ rClass -> newInstanceArgs ( ) ; } else { return $ rClass -> newInstanceArgs ( $ args ) ; } } else { return $ rClass -> newInstanceArgs ( ) ; } }

Instantiates a bean using the constructor.

@param BeanDefinition $definition

@return object

Instantiates a bean using the constructor .


private function _instantiateByFactoryClass(BeanDefinition $definition)
    {
        $class = $definition->getClass();
        $rClass = $this->_reflectionFactory->getClass($class);
        $factoryMethodName = $definition->getFactoryMethod();
        $factoryMethod = $rClass->getMethod($factoryMethodName);
        $args = $this->_sortArgsWithNames($definition, $factoryMethod);
        return forward_static_call_array(array($class, $factoryMethodName), $args);
    }

private function _instantiateByFactoryClass ( BeanDefinition $ definition ) { $ class = $ definition -> getClass ( ) ; $ rClass = $ this -> _reflectionFactory -> getClass ( $ class ) ; $ factoryMethodName = $ definition -> getFactoryMethod ( ) ; $ factoryMethod = $ rClass -> getMethod ( $ factoryMethodName ) ; $ args = $ this -> _sortArgsWithNames ( $ definition , $ factoryMethod ) ; return forward_static_call_array ( array ( $ class , $ factoryMethodName ) , $ args ) ; }

Instantiates a bean using a factory class.

@param BeanDefinition $definition

@return object

Instantiates a bean using a factory class .


private function _instantiateByFactoryBean(BeanDefinition $definition)
    {
        $factoryBean = $this->getBean($definition->getFactoryBean());
        $refObject = new \ReflectionObject($factoryBean);
        $factoryMethod = $refObject->getMethod($definition->getFactoryMethod());
        $args = $this->_sortArgsWithNames($definition, $factoryMethod);
        return $factoryMethod->invokeArgs($factoryBean, $args);
    }

private function _instantiateByFactoryBean ( BeanDefinition $ definition ) { $ factoryBean = $ this -> getBean ( $ definition -> getFactoryBean ( ) ) ; $ refObject = new \ ReflectionObject ( $ factoryBean ) ; $ factoryMethod = $ refObject -> getMethod ( $ definition -> getFactoryMethod ( ) ) ; $ args = $ this -> _sortArgsWithNames ( $ definition , $ factoryMethod ) ; return $ factoryMethod -> invokeArgs ( $ factoryBean , $ args ) ; }

Instantiates a bean using a factory bean.

@param BeanDefinition $definition

@return object

Instantiates a bean using a factory bean .


private function _instantiate(BeanDefinition $definition)
    {
        if ($definition->isCreatedByConstructor()) {
            return $this->_instantiateByConstructor($definition);
        } else if ($definition->isCreatedWithFactoryBean()) {
            return $this->_instantiateByFactoryBean($definition);
        } else {
            return $this->_instantiateByFactoryClass($definition);
        }
    }

private function _instantiate ( BeanDefinition $ definition ) { if ( $ definition -> isCreatedByConstructor ( ) ) { return $ this -> _instantiateByConstructor ( $ definition ) ; } else if ( $ definition -> isCreatedWithFactoryBean ( ) ) { return $ this -> _instantiateByFactoryBean ( $ definition ) ; } else { return $ this -> _instantiateByFactoryClass ( $ definition ) ; } }

Instantiates a bean.

@param BeanDefinition $definition

@return object


private function _createBeanDependencies(BeanDefinition $definition)
    {
        foreach ($definition->getDependsOn() as $depBean) {
            $this->getBean(trim($depBean));
        }
    }

private function _createBeanDependencies ( BeanDefinition $ definition ) { foreach ( $ definition -> getDependsOn ( ) as $ depBean ) { $ this -> getBean ( trim ( $ depBean ) ) ; } }

Creates whatever beans this definition depends on.

@return void

Creates whatever beans this definition depends on .


private function _applyAspect(
        $targetClass, AspectDefinition $aspectDefinition, IDispatcher $dispatcher
    ) {
        $rClass = $this->_reflectionFactory->getClass($targetClass);
        $aspect = $this->getBean($aspectDefinition->getBeanName());
        foreach ($aspectDefinition->getPointcuts() as $pointcutName) {
            $pointcut = $this->_aspectManager->getPointcut($pointcutName);
            if ($pointcut === false) {
                throw new BeanFactoryException('Could not find pointcut: ' . $pointcutName);
            }
            $expression = $pointcut->getExpression();
            foreach  ($rClass->getMethods() as $method) {
                $methodName = $method->getName();
                if (preg_match('/' . $expression . '/', $methodName) === 0) {
                    continue;
                }
                if (
                    $aspectDefinition->getType() == AspectDefinition::ASPECT_METHOD
                ) {
                    $dispatcher->addMethodInterceptor($methodName, $aspect, $pointcut->getMethod());
                } else {
                    $dispatcher->addExceptionInterceptor($methodName, $aspect, $pointcut->getMethod());
                }
            }
        }
    }

private
function
_applyAspect
(
$
targetClass
,
AspectDefinition
$
aspectDefinition
,
IDispatcher
$
dispatcher
)
{
$
rClass
=
$
this
->
_reflectionFactory
->
getClass
(
$
targetClass
)
;
$
aspect
=
$
this
->
getBean
(
$
aspectDefinition
->
getBeanName
(
)
)
;
foreach
(
$
aspectDefinition
->
getPointcuts
(
)
as
$
pointcutName
)
{
$
pointcut
=
$
this
->
_aspectManager
->
getPointcut
(
$
pointcutName
)
;
if
(
$
pointcut
===
false
)
{
throw
new
BeanFactoryException
(
'Could not find pointcut: '
.
$
pointcutName
)
;
}
$
expression
=
$
pointcut
->
getExpression
(
)
;
foreach
(
$
rClass
->
getMethods
(
)
as
$
method
)
{
$
methodName
=
$
method
->
getName
(
)
;
if
(
preg_match
(
'/'
.
$
expression
.
'/'
,
$
methodName
)
===
0
)
{
continue
;
}
if
(
$
aspectDefinition
->
getType
(
)
==
AspectDefinition
::
ASPECT_METHOD
)
{
$
dispatcher
->
addMethodInterceptor
(
$
methodName
,
$
aspect
,
$
pointcut
->
getMethod
(
)
)
;
}
else
{
$
dispatcher
->
addExceptionInterceptor
(
$
methodName
,
$
aspect
,
$
pointcut
->
getMethod
(
)
)
;
}
}
}
}

Will inject into the given dispatcher the necessary information to
aspects will be run correctly.

@throws BeanFactoryException
@return void

Will inject into the given dispatcher the necessary information to aspects will be run correctly .


private function _applySpecificAspects(BeanDefinition $definition, IDispatcher $dispatcher)
    {
        if ($definition->hasAspects()) {
            foreach ($definition->getAspects() as $aspect) {
                $this->_applyAspect($definition->getClass(), $aspect, $dispatcher);
            }
        }
    }

private function _applySpecificAspects ( BeanDefinition $ definition , IDispatcher $ dispatcher ) { if ( $ definition -> hasAspects ( ) ) { foreach ( $ definition -> getAspects ( ) as $ aspect ) { $ this -> _applyAspect ( $ definition -> getClass ( ) , $ aspect , $ dispatcher ) ; } } }

Applies all aspects specifically defined for this bean definition.

@param BeanDefinition $definition
@param IDispatcher $dispatcher

@return void

Applies all aspects specifically defined for this bean definition .


private function _applyGlobalAspects(BeanDefinition $definition, IDispatcher $dispatcher)
    {
        $class = $definition->getClass();
        $rClass = $this->_reflectionFactory->getClass($class);
        foreach ($this->_aspectManager->getAspects() as $aspect) {
            $expression = $aspect->getExpression();
            if (preg_match('/' . $expression . '/', $class) === 0) {
                $parentClass = $rClass->getParentClass();
                while($parentClass !== false) {
                    if (preg_match('/' . $expression . '/', $parentClass->getName()) > 0) {
                        $this->_applyAspect($class, $aspect, $dispatcher);
                    }
                    $parentClass = $parentClass->getParentClass();
                }
            } else {
                $this->_applyAspect($class, $aspect, $dispatcher);
            }
        }
    }

private function _applyGlobalAspects ( BeanDefinition $ definition , IDispatcher $ dispatcher ) { $ class = $ definition -> getClass ( ) ; $ rClass = $ this -> _reflectionFactory -> getClass ( $ class ) ; foreach ( $ this -> _aspectManager -> getAspects ( ) as $ aspect ) { $ expression = $ aspect -> getExpression ( ) ; if ( preg_match ( '/' . $ expression . '/' , $ class ) === 0 ) { $ parentClass = $ rClass -> getParentClass ( ) ; while ( $ parentClass !== false ) { if ( preg_match ( '/' . $ expression . '/' , $ parentClass -> getName ( ) ) > 0 ) { $ this -> _applyAspect ( $ class , $ aspect , $ dispatcher ) ; } $ parentClass = $ parentClass -> getParentClass ( ) ; } } else { $ this -> _applyAspect ( $ class , $ aspect , $ dispatcher ) ; } } }

Looks for any global aspects that may apply to this bean and applies them.

@param BeanDefinition $definition
@param IDispatcher $dispatcher

@return void

Looks for any global aspects that may apply to this bean and applies them .


private function _applyAspects(BeanDefinition $definition)
    {
        $class = $definition->getClass();
        $dispatcher = clone $this->_dispatcherTemplate;
        $this->_applySpecificAspects($definition, $dispatcher);
        $this->_applyGlobalAspects($definition, $dispatcher);
        if ($dispatcher->hasMethodsIntercepted()) {
            $definition->setProxyClassName(
                $this->_proxyFactory->create($class, $dispatcher)
            );
        }
    }

private function _applyAspects ( BeanDefinition $ definition ) { $ class = $ definition -> getClass ( ) ; $ dispatcher = clone $ this -> _dispatcherTemplate ; $ this -> _applySpecificAspects ( $ definition , $ dispatcher ) ; $ this -> _applyGlobalAspects ( $ definition , $ dispatcher ) ; if ( $ dispatcher -> hasMethodsIntercepted ( ) ) { $ definition -> setProxyClassName ( $ this -> _proxyFactory -> create ( $ class , $ dispatcher ) ) ; } }

Applies specific bean aspects and global defined aspects.

@param BeanDefinition $definition

@return void

Applies specific bean aspects and global defined aspects .


private function _createBean(BeanDefinition $definition)
    {
        $name = $definition->getName();
        if (isset($this->_definitionsInProcess[$name])) {
            throw new BeanFactoryException(
            	"Cyclic dependency found for: $name"
            );
        }
        $this->_definitionsInProcess[$name] = '';
        $this->_lifecycleManager->beforeCreate($definition);
        $this->_createBeanDependencies($definition);
        $this->_applyAspects($definition);
        $bean = $this->_instantiate($definition);
        if (!is_object($bean)) {
            unset($this->_definitionsInProcess[$name]);
            throw new BeanFactoryException(
            	'Could not instantiate ' . $definition->getName()
            );
        }
        $this->_assemble($bean, $definition);
        $this->_setupInitAndShutdown($bean, $definition);
        $this->_lifecycleManager->afterCreate($bean, $definition);
        unset($this->_definitionsInProcess[$name]);
        return $bean;
    }

private
function
_createBean
(
BeanDefinition
$
definition
)
{
$
name
=
$
definition
->
getName
(
)
;
if
(
isset
(
$
this
->
_definitionsInProcess
[
$
name
]
)
)
{
throw
new
BeanFactoryException
(
"Cyclic dependency found for: $name"
)
;
}
$
this
->
_definitionsInProcess
[
$
name
]
=
''
;
$
this
->
_lifecycleManager
->
beforeCreate
(
$
definition
)
;
$
this
->
_createBeanDependencies
(
$
definition
)
;
$
this
->
_applyAspects
(
$
definition
)
;
$
bean
=
$
this
->
_instantiate
(
$
definition
)
;
if
(
!
is_object
(
$
bean
)
)
{
unset
(
$
this
->
_definitionsInProcess
[
$
name
]
)
;
throw
new
BeanFactoryException
(
'Could not instantiate '
.
$
definition
->
getName
(
)
)
;
}
$
this
->
_assemble
(
$
bean
,
$
definition
)
;
$
this
->
_setupInitAndShutdown
(
$
bean
,
$
definition
)
;
$
this
->
_lifecycleManager
->
afterCreate
(
$
bean
,
$
definition
)
;
unset
(
$
this
->
_definitionsInProcess
[
$
name
]
)
;
return
$
bean
;
}

This will create a new bean, injecting all properties and applying all
aspects.

@throws BeanFactoryException
@return object

This will create a new bean injecting all properties and applying all aspects .


private function _setupInitAndShutdown($bean, BeanDefinition $definition)
    {
        if ($definition->hasInitMethod()) {
            $initMethod = $definition->getInitMethod();
            $bean->$initMethod();
        }
        if ($definition->hasDestroyMethod()) {
            $destroyMethod = $definition->getDestroyMethod();
            $this->registerShutdownMethod($bean, $destroyMethod);
        }
    }

private function _setupInitAndShutdown ( $ bean , BeanDefinition $ definition ) { if ( $ definition -> hasInitMethod ( ) ) { $ initMethod = $ definition -> getInitMethod ( ) ; $ bean -> $ initMethod ( ) ; } if ( $ definition -> hasDestroyMethod ( ) ) { $ destroyMethod = $ definition -> getDestroyMethod ( ) ; $ this -> registerShutdownMethod ( $ bean , $ destroyMethod ) ; } }

Calls init method and register shutdown method.

@param object $bean
@param BeanDefinition $definition

@return void

Calls init method and register shutdown method .


private function _nonSetterMethodInject($bean, $name, $value)
    {
        $rClass = $this->_reflectionFactory->getClass(get_class($bean));
        if ($rClass->hasMethod($name)) {
            $bean->$name($value);
            return true;
        }
        return false;
    }

private function _nonSetterMethodInject ( $ bean , $ name , $ value ) { $ rClass = $ this -> _reflectionFactory -> getClass ( get_class ( $ bean ) ) ; if ( $ rClass -> hasMethod ( $ name ) ) { $ bean -> $ name ( $ value ) ; return true ; } return false ; }

Tries to inject by looking up a method of the given name.

@param object $bean
@param string $name
@param string $value

@return boolean

Tries to inject by looking up a method of the given name .


private function _propertyInject($bean, $name, $value)
    {
        $rClass = $this->_reflectionFactory->getClass(get_class($bean));
        if ($rClass->hasProperty($name)) {
             $rProperty = $rClass->getProperty($name);
             if (!$rProperty->isPublic()) {
                $rProperty->setAccessible(true);
             }
            $rProperty->setValue($bean, $value);
            return true;
        }
        return false;
    }

private function _propertyInject ( $ bean , $ name , $ value ) { $ rClass = $ this -> _reflectionFactory -> getClass ( get_class ( $ bean ) ) ; if ( $ rClass -> hasProperty ( $ name ) ) { $ rProperty = $ rClass -> getProperty ( $ name ) ; if ( ! $ rProperty -> isPublic ( ) ) { $ rProperty -> setAccessible ( true ) ; } $ rProperty -> setValue ( $ bean , $ value ) ; return true ; } return false ; }

Tries to inject by looking up a property by name.

@param object $bean
@param string $name
@param string $value

@return boolean

Tries to inject by looking up a property by name .


public function getBean($name)
    {
        $ret = false;
        $beanDefinition = $this->getBeanDefinition($name);
        $beanName = $name . '.bean';
        if ($beanDefinition->isAbstract()) {
            throw new BeanFactoryException(
            	"Cant instantiate abstract bean: $name"
            );
        }
        if ($beanDefinition->isPrototype()) {
            $ret = $this->_createBean($beanDefinition);
        } else if ($beanDefinition->isSingleton()) {
            if (isset($this->_beans[$beanName])) {
                $ret = $this->_beans[$beanName];
            } else {
                $ret = $this->_beanCache->fetch($beanName, $result);
                if (!$ret) {
                    $ret = $this->_createBean($beanDefinition);
                }
                $this->_beans[$beanName] = $ret;
            }
        }
        return $ret;
    }

public
function
getBean
(
$
name
)
{
$
ret
=
false
;
$
beanDefinition
=
$
this
->
getBeanDefinition
(
$
name
)
;
$
beanName
=
$
name
.
'.bean'
;
if
(
$
beanDefinition
->
isAbstract
(
)
)
{
throw
new
BeanFactoryException
(
"Cant instantiate abstract bean: $name"
)
;
}
if
(
$
beanDefinition
->
isPrototype
(
)
)
{
$
ret
=
$
this
->
_createBean
(
$
beanDefinition
)
;
}
else
if
(
$
beanDefinition
->
isSingleton
(
)
)
{
if
(
isset
(
$
this
->
_beans
[
$
beanName
]
)
)
{
$
ret
=
$
this
->
_beans
[
$
beanName
]
;
}
else
{
$
ret
=
$
this
->
_beanCache
->
fetch
(
$
beanName
,
$
result
)
;
if
(
!
$
ret
)
{
$
ret
=
$
this
->
_createBean
(
$
beanDefinition
)
;
}
$
this
->
_beans
[
$
beanName
]
=
$
ret
;
}
}
return
$
ret
;
}

Returns a bean.

@param string $name Bean name.

@throws BeanFactoryException
@return object


public static function getInstance(array $properties = array())
    {
        if (self::$_containerInstance === false) {
            // Init cache subsystems.
            if (isset($properties['ding']['cache'])) {
                CacheLocator::configure($properties['ding']['cache']);
            }
            if (isset($properties['ding']['log4php.properties'])) {
                \Logger::configure($properties['ding']['log4php.properties']);
            }
            self::$_containerInstance = new ContainerImpl($properties['ding']['factory']);
        }
        return self::$_containerInstance;
    }

public
static
function
getInstance
(
array
$
properties
=
array
(
)
)
{
if
(
self
::
$
_containerInstance
===
false
)
{
// Init cache subsystems.
if
(
isset
(
$
properties
[
'ding'
]
[
'cache'
]
)
)
{
CacheLocator
::
configure
(
$
properties
[
'ding'
]
[
'cache'
]
)
;
}
if
(
isset
(
$
properties
[
'ding'
]
[
'log4php.properties'
]
)
)
{
\
Logger
::
configure
(
$
properties
[
'ding'
]
[
'log4php.properties'
]
)
;
}
self
::
$
_containerInstance
=
new
ContainerImpl
(
$
properties
[
'ding'
]
[
'factory'
]
)
;
}
return
self
::
$
_containerInstance
;
}

This will return a container

@param array $properties Container properties.

@return ContainerImpl


public function fillAware(BeanDefinition $def, $bean)
    {
        $class = get_class($bean);
        $rClass = $this->_reflectionFactory->getClass($class);
        if ($rClass->implementsInterface('Ding\Reflection\IReflectionFactoryAware')) {
            $bean->setReflectionFactory($this->_reflectionFactory);
        }
        if ($rClass->implementsInterface('Ding\Bean\IBeanNameAware')) {
            $bean->setBeanName($def->getName());
        }
        if ($rClass->implementsInterface('Ding\Logger\ILoggerAware')) {
            $bean->setLogger(\Logger::getLogger($class));
        }
        if ($rClass->implementsInterface('Ding\Container\IContainerAware')) {
            $bean->setContainer($this);
        }
        if ($rClass->implementsInterface('Ding\Resource\IResourceLoaderAware')) {
            $bean->setResourceLoader($this);
        }
        if ($rClass->implementsInterface('Ding\Aspect\IAspectManagerAware')) {
            $bean->setAspectManager($this->_aspectManager);
        }

        if ($rClass->implementsInterface('Ding\Bean\IBeanDefinitionProvider')) {
            $this->registerBeanDefinitionProvider($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterConfigListener')) {
            $this->_lifecycleManager->addAfterConfigListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterDefinitionListener')) {
            $this->_lifecycleManager->addAfterDefinitionListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IBeforeCreateListener')) {
            $this->_lifecycleManager->addBeforeCreateListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterCreateListener')) {
            $this->_lifecycleManager->addAfterCreateListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IBeforeAssembleListener')) {
            $this->_lifecycleManager->addBeforeAssembleListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Bean\Lifecycle\IAfterAssembleListener')) {
            $this->_lifecycleManager->addAfterAssembleListener($bean);
        }
        if ($rClass->implementsInterface('Ding\Aspect\IAspectProvider')) {
            $this->_aspectManager->registerAspectProvider($bean);
        }
        if ($rClass->implementsInterface('Ding\Aspect\IPointcutProvider')) {
            $this->_aspectManager->registerPointcutProvider($bean);
        }
    }

Will look for "aware" kind of interfaces and inject whatever necessary.

@param BeanDefinition $def The Bean Definition
@param object $bean The bean

@return void

Will look for aware kind of interfaces and inject whatever necessary .


public function signalHandler($signo)
    {
        $msg = "Caught Signal: $signo";
        $this->_logger->warn($msg);
        $this->eventDispatch('dingSignal', $signo);
    }

public
function
signalHandler
(
$
signo
)
{
$
msg
=
"Caught Signal: $signo"
;
$
this
->
_logger
->
warn
(
$
msg
)
;
$
this
->
eventDispatch
(
'dingSignal'
,
$
signo
)
;
}

Called when a signal is caught.

@param integer $signo

@return void


public static function load($class)
    {
        $classFile = str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
        $file = stream_resolve_include_path($classFile);
        if ($file && file_exists($file)) {
            require_once $file;
            return true;
        }
        return false;
    }

public static function load ( $ class ) { $ classFile = str_replace ( '\\' , DIRECTORY_SEPARATOR , $ class ) . '.php' ; $ file = stream_resolve_include_path ( $ classFile ) ; if ( $ file && file_exists ( $ file ) ) { require_once $ file ; return true ; } return false ; }

Called by php to load a given class. Returns true if the class was
successfully loaded.

@return boolean

Called by php to load a given class . Returns true if the class was successfully loaded .


public function makeChildBean($childName)
    {
        $bean = serialize($this);
        $bean = unserialize($bean);
        $bean->setName($childName);
        $bean->clearAliases();
        $bean->makeConcrete();
        return $bean;
    }

public function makeChildBean ( $ childName ) { $ bean = serialize ( $ this ) ; $ bean = unserialize ( $ bean ) ; $ bean -> setName ( $ childName ) ; $ bean -> clearAliases ( ) ; $ bean -> makeConcrete ( ) ; return $ bean ; }

Returns a new bean definition, a copy of this one.

@param string $childName The name for the new bean

@return BeanDefinition

Returns a new bean definition a copy of this one .


private function _populateClassesPerAnnotations($class, Collection $annotations)
    {
        foreach ($annotations->getAll() as $name => $annotation) {
            $cacheKey = $name . '.classbyannotations';
            if (!isset($this->_classesAnnotated[$name])) {
                $this->_classesAnnotated[$name] = array();
            }
            $this->_classesAnnotated[$name][$class] = $class;
            $this->_cache->store($cacheKey, $this->_classesAnnotated);
        }
    }

private function _populateClassesPerAnnotations ( $ class , Collection $ annotations ) { foreach ( $ annotations -> getAll ( ) as $ name => $ annotation ) { $ cacheKey = $ name . '.classbyannotations' ; if ( ! isset ( $ this -> _classesAnnotated [ $ name ] ) ) { $ this -> _classesAnnotated [ $ name ] = array ( ) ; } $ this -> _classesAnnotated [ $ name ] [ $ class ] = $ class ; $ this -> _cache -> store ( $ cacheKey , $ this -> _classesAnnotated ) ; } }

This one will populate the map indexed by annotations names, so we can
then get all classes with a particular annotation name.

@param string $class A class name.
@param Collection $annotations The annotations to index.

@return void

This one will populate the map indexed by annotations names so we can then get all classes with a particular annotation name .


private function _loadXml($filename)
    {
        $xmls = array();
        libxml_use_internal_errors(true);
        if (is_array($filename)) {
            foreach ($filename as $file) {
                $result = $this->_loadXml($file);
                if ($result !== false) {
                    foreach ($result as $name => $xml) {
                        $xmls[$name] = $xml;
                    }
                }
            }
            return $xmls;
        }
        $contents = false;
        foreach ($this->_directories as $directory) {
            $fullname = $directory . DIRECTORY_SEPARATOR . $filename;
            if (!file_exists($fullname)) {
                continue;
            }
            $contents = @file_get_contents($fullname);
        }
        if ($contents === false) {
            throw new BeanFactoryException($filename . ' not found in ' . print_r($this->_directories, true));
        }
        $ret = simplexml_load_string($contents);
        if ($ret === false) {
            return $ret;
        }
        $xmls[$filename] = $ret;
        foreach ($ret->xpath("//import") as $imported) {
            $filename = (string)$imported->attributes()->resource;
            foreach ($this->_loadXml($filename) as $name => $xml) {
                $xmls[$name] = $xml;
            }
        }
        return $xmls;
    }

private
function
_loadXml
(
$
filename
)
{
$
xmls
=
array
(
)
;
libxml_use_internal_errors
(
true
)
;
if
(
is_array
(
$
filename
)
)
{
foreach
(
$
filename
as
$
file
)
{
$
result
=
$
this
->
_loadXml
(
$
file
)
;
if
(
$
result
!==
false
)
{
foreach
(
$
result
as
$
name
=>
$
xml
)
{
$
xmls
[
$
name
]
=
$
xml
;
}
}
}
return
$
xmls
;
}
$
contents
=
false
;
foreach
(
$
this
->
_directories
as
$
directory
)
{
$
fullname
=
$
directory
.
DIRECTORY_SEPARATOR
.
$
filename
;
if
(
!
file_exists
(
$
fullname
)
)
{
continue
;
}
$
contents
=
@
file_get_contents
(
$
fullname
)
;
}
if
(
$
contents
===
false
)
{
throw
new
BeanFactoryException
(
$
filename
.
' not found in '
.
print_r
(
$
this
->
_directories
,
true
)
)
;
}
$
ret
=
simplexml_load_string
(
$
contents
)
;
if
(
$
ret
===
false
)
{
return
$
ret
;
}
$
xmls
[
$
filename
]
=
$
ret
;
foreach
(
$
ret
->
xpath
(
"//import"
)
as
$
imported
)
{
$
filename
=
(
string
)
$
imported
->
attributes
(
)
->
resource
;
foreach
(
$
this
->
_loadXml
(
$
filename
)
as
$
name
=>
$
xml
)
{
$
xmls
[
$
name
]
=
$
xml
;
}
}
return
$
xmls
;
}

Initializes SimpleXML Object

@param string $filename

@throws BeanFactoryException
@return SimpleXML


private function _load()
    {
        if ($this->_simpleXml !== false) {
            return;
        }
        $this->_simpleXml = $this->_loadXml($this->_filename);
        if (empty($this->_simpleXml)) {
            throw new BeanFactoryException(
                'Could not parse: ' . $this->_filename
                . ': ' . $this->_getXmlErrors()
            );
        }
    }

private
function
_load
(
)
{
if
(
$
this
->
_simpleXml
!==
false
)
{
return
;
}
$
this
->
_simpleXml
=
$
this
->
_loadXml
(
$
this
->
_filename
)
;
if
(
empty
(
$
this
->
_simpleXml
)
)
{
throw
new
BeanFactoryException
(
'Could not parse: '
.
$
this
->
_filename
.
': '
.
$
this
->
_getXmlErrors
(
)
)
;
}
}

Initialize SimpleXML.

@throws BeanFactoryException
@return void


public function close()
    {
        $this->_open = false;
        $this->_peers = array();
        $this->_peersSockets = array();
        $this->_peersLastDataReceived = array();
        $this->_handler->close();
        socket_close($this->_socket);
        $this->_socket = false;
    }

public function close ( ) { $ this -> _open = false ; $ this -> _peers = array ( ) ; $ this -> _peersSockets = array ( ) ; $ this -> _peersLastDataReceived = array ( ) ; $ this -> _handler -> close ( ) ; socket_close ( $ this -> _socket ) ; $ this -> _socket = false ; }

Call this to close the server.

@return void


public function open()
    {
        $this->_open = false;
        $this->_handler->beforeOpen();
        $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 (!@socket_bind($this->_socket, $this->_address, $this->_port)) {
            $error = socket_strerror(socket_last_error($this->_socket));
            socket_close($this->_socket);
            $this->_socket = false;
            throw new TcpException('Error binding socket: ' . $error);
        }
        socket_set_nonblock($this->_socket);
        $this->_handler->beforeListen();
        if (!socket_listen($this->_socket, $this->_backlog)) {
            $error = socket_strerror(socket_last_error($this->_socket));
            socket_close($this->_socket);
            $this->_socket = false;
            throw new TcpException('Error listening socket: ' . $error);
        }
        $this->_open = true;
    }

public
function
open
(
)
{
$
this
->
_open
=
false
;
$
this
->
_handler
->
beforeOpen
(
)
;
$
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
(
!
@
socket_bind
(
$
this
->
_socket
,
$
this
->
_address
,
$
this
->
_port
)
)
{
$
error
=
socket_strerror
(
socket_last_error
(
$
this
->
_socket
)
)
;
socket_close
(
$
this
->
_socket
)
;
$
this
->
_socket
=
false
;
throw
new
TcpException
(
'Error binding socket: '
.
$
error
)
;
}
socket_set_nonblock
(
$
this
->
_socket
)
;
$
this
->
_handler
->
beforeListen
(
)
;
if
(
!
socket_listen
(
$
this
->
_socket
,
$
this
->
_backlog
)
)
{
$
error
=
socket_strerror
(
socket_last_error
(
$
this
->
_socket
)
)
;
socket_close
(
$
this
->
_socket
)
;
$
this
->
_socket
=
false
;
throw
new
TcpException
(
'Error listening socket: '
.
$
error
)
;
}
$
this
->
_open
=
true
;
}

Call this to bind the socket and start listening for connections.
Will also set the socket non blocking.

@throws TcpException
@return void

Call this to bind the socket and start listening for connections . Will also set the socket non blocking .


private function _freePeer(\Ding\Helpers\Tcp\TcpPeer $peer)
    {
        $peerName = $peer->getName();
        unset($this->_peers[$peerName]);
        unset($this->_peersSockets[$peerName]);
        unset($this->_peersLastDataReceived[$peerName]);
    }

private function _freePeer ( \ Ding \ Helpers \ Tcp \ TcpPeer $ peer ) { $ peerName = $ peer -> getName ( ) ; unset ( $ this -> _peers [ $ peerName ] ) ; unset ( $ this -> _peersSockets [ $ peerName ] ) ; unset ( $ this -> _peersLastDataReceived [ $ peerName ] ) ; }

After disconnecting a peer, this will release all the associated
information.

@return void

After disconnecting a peer this will release all the associated information .


protected function createClass($newName, array $proxyMethods, \ReflectionClass $class)
    {
        $src = $this->proxyTemplate;
        $src = str_replace('NEW_NAME', $newName, $src);
        $src = str_replace('CLASS_NAME', $class->getName(), $src);
        $methods = array();
        foreach ($proxyMethods as $method) {
            if ($class->hasMethod($method)) {
                $methods[] = $this->createMethod($class->getMethod($method));
            }
        }
        $src = str_replace('METHODS', implode("\n", $methods), $src);
        return $src;
    }

protected function createClass ( $ newName , array $ proxyMethods , \ ReflectionClass $ class ) { $ src = $ this -> proxyTemplate ; $ src = str_replace ( 'NEW_NAME' , $ newName , $ src ) ; $ src = str_replace ( 'CLASS_NAME' , $ class -> getName ( ) , $ src ) ; $ methods = array ( ) ; foreach ( $ proxyMethods as $ method ) { if ( $ class -> hasMethod ( $ method ) ) { $ methods [ ] = $ this -> createMethod ( $ class -> getMethod ( $ method ) ) ; } } $ src = str_replace ( 'METHODS' , implode ( "\n" , $ methods ) , $ src ) ; return $ src ; }

This will return a proxy class source.

@param string          $newName     Name for the proxy class.
@param ReflectionClass $targetClass Class to be proxied.

@see Proxy::$proxyTemplate

@return string


protected function createParameter(\ReflectionParameter $parameter)
    {
        $parameterSrc = '';
        $paramClass = $parameter->getClass();
        if ($parameter->isArray()) {
            $parameterSrc .= 'array ';
        } else if ($paramClass) {
            $parameterSrc .= $paramClass->getName() . ' ';
        }
        if ($parameter->isPassedByReference()) {
            $parameterSrc .= ' &';
        }
        $parameterSrc .= '$' . $parameter->getName();
        if ($parameter->isOptional()) {
            $parameterSrc .= '=';
            if ($parameter->getDefaultValue() === null) {
                $parameterSrc .= 'null';
            } else if ($parameter->getDefaultValue() === false) {
                $parameterSrc .= 'false';
            } else if ($parameter->getDefaultValue() === true) {
                $parameterSrc .= 'true';
            } else if (is_array($parameter->getDefaultValue())) {
                $parameterSrc .= 'array()';
            } else {
                $parameterSrc .= "'" . $parameter->getDefaultValue() . "'";
            }
        }
        return $parameterSrc;
    }

protected
function
createParameter
(
\
ReflectionParameter
$
parameter
)
{
$
parameterSrc
=
''
;
$
paramClass
=
$
parameter
->
getClass
(
)
;
if
(
$
parameter
->
isArray
(
)
)
{
$
parameterSrc
.=
'array '
;
}
else
if
(
$
paramClass
)
{
$
parameterSrc
.=
$
paramClass
->
getName
(
)
.
' '
;
}
if
(
$
parameter
->
isPassedByReference
(
)
)
{
$
parameterSrc
.=
' &'
;
}
$
parameterSrc
.=
'$'
.
$
parameter
->
getName
(
)
;
if
(
$
parameter
->
isOptional
(
)
)
{
$
parameterSrc
.=
'='
;
if
(
$
parameter
->
getDefaultValue
(
)
===
)
{
$
parameterSrc
.=
'null'
;
}
else
if
(
$
parameter
->
getDefaultValue
(
)
===
false
)
{
$
parameterSrc
.=
'false'
;
}
else
if
(
$
parameter
->
getDefaultValue
(
)
===
true
)
{
$
parameterSrc
.=
'true'
;
}
else
if
(
is_array
(
$
parameter
->
getDefaultValue
(
)
)
)
{
$
parameterSrc
.=
'array()'
;
}
else
{
$
parameterSrc
.=
"'"
.
$
parameter
->
getDefaultValue
(
)
.
"'"
;
}
}
return
$
parameterSrc
;
}

This will return a full proxy-method-parameter source.

@param \ReflectionParameter $parameter The method parameter.

@see Proxy::$methodTemplate

@return string

This will return a full proxy - method - parameter source .


protected function createMethod(\ReflectionMethod $method)
    {
        $visibility = '';
        $additional = '';
        $name = $method->getName();
        if ($method->isPublic()) {
            $visibility = ' public';
        } else if ($method->isProtected()) {
            $visibility = ' protected';
        } else if ($method->isPrivate()) {
            // useless really. $visibility = ' private';
            return '';
        }
        if ($method->isStatic()) {
            // useless really. $additional .= ' static ';
            return '';
        }
        //if ($method->isAbstract()) {
            // useless really. $$additional .= ' abstract ';
            //return '';
        //}
        if ($method->isConstructor()) {
            $name = '__construct';
        } else if ($method->isDestructor()) {
            $name = '__destruct';
        }
        $args = array();
        foreach ($method->getParameters() as $parameter) {
            $args[] = $this->createParameter($parameter);
        }

        $src = $this->methodTemplate;
        $src = str_replace('VISIBILITY', $visibility, $src);
        $src = str_replace('ADDITIONAL', $additional, $src);
        $src = str_replace('METHOD_NAME', $name, $src);
        $src = str_replace('METHOD_ARGS', implode(',', $args), $src);
        $src = str_replace(
        	'CLASS_NAME', $method->getDeclaringClass()->getName(), $src
        );
        return $src;
    }

This will return a full proxy-method source.

@param \ReflectionMethod $method The method to be proxied.

@see Proxy::$methodTemplate

@return string

This will return a full proxy - method source .


public function create($class, IDispatcher $dispatcher)
    {
        $subject = $this->reflectionFactory->getClass($class);
        $proxyClassName = 'Proxy' . str_replace('\\', '', $subject->getName());
        $cacheKey = $proxyClassName . '.proxy';
        $result = false;
        $src = $this->cache->fetch($cacheKey, $result);
        if (!$result) {
            $src = $this->createClass(
                $proxyClassName, $dispatcher->getMethodsIntercepted(), $subject
            );
            $this->cache->store($cacheKey, $src);
        }
        eval($src);
        $proxyClassName::setDispatcher($dispatcher);
        $proxyClassName::setReflectionFactory($this->reflectionFactory);
        return $proxyClassName;
    }

public function create ( $ class , IDispatcher $ dispatcher ) { $ subject = $ this -> reflectionFactory -> getClass ( $ class ) ; $ proxyClassName = 'Proxy' . str_replace ( '\\' , '' , $ subject -> getName ( ) ) ; $ cacheKey = $ proxyClassName . '.proxy' ; $ result = false ; $ src = $ this -> cache -> fetch ( $ cacheKey , $ result ) ; if ( ! $ result ) { $ src = $ this -> createClass ( $ proxyClassName , $ dispatcher -> getMethodsIntercepted ( ) , $ subject ) ; $ this -> cache -> store ( $ cacheKey , $ src ) ; } eval ( $ src ) ; $ proxyClassName :: setDispatcher ( $ dispatcher ) ; $ proxyClassName :: setReflectionFactory ( $ this -> reflectionFactory ) ; return $ proxyClassName ; }

This will give you the name of a proxy class as a string. The class will
already exist in the vm.

@return string

This will give you the name of a proxy class as a string . The class will already exist in the vm .


private function _loadYaml($filename)
    {
        $yamls = array();
        if (is_array($filename)) {
            foreach ($filename as $file) {
                foreach ($this->_loadYaml($file) as $name => $yaml) {
                    $yamls[$name] = $yaml;
                }
            }
            return $yamls;
        }
            $contents = false;
        foreach ($this->_directories as $directory) {
            $fullname = $directory . DIRECTORY_SEPARATOR . $filename;
            if (!file_exists($fullname)) {
                continue;
            }
            $contents = @file_get_contents($fullname);
        }
        if ($contents === false) {
            throw new BeanFactoryException($filename . ' not found in ' . print_r($this->_directories, true));
        }
        $ret = @yaml_parse($contents);
        if ($ret === false) {
            return $ret;
        }
        $yamls[$filename] = $ret;
        if (isset($ret['import'])) {
            foreach ($ret['import'] as $imported) {
                foreach ($this->_loadYaml($imported) as $name => $yaml) {
                    $yamls[$name] = $yaml;
                }
            }
        }
        return $yamls;
    }

private
function
_loadYaml
(
$
filename
)
{
$
yamls
=
array
(
)
;
if
(
is_array
(
$
filename
)
)
{
foreach
(
$
filename
as
$
file
)
{
foreach
(
$
this
->
_loadYaml
(
$
file
)
as
$
name
=>
$
yaml
)
{
$
yamls
[
$
name
]
=
$
yaml
;
}
}
return
$
yamls
;
}
$
contents
=
false
;
foreach
(
$
this
->
_directories
as
$
directory
)
{
$
fullname
=
$
directory
.
DIRECTORY_SEPARATOR
.
$
filename
;
if
(
!
file_exists
(
$
fullname
)
)
{
continue
;
}
$
contents
=
@
file_get_contents
(
$
fullname
)
;
}
if
(
$
contents
===
false
)
{
throw
new
BeanFactoryException
(
$
filename
.
' not found in '
.
print_r
(
$
this
->
_directories
,
true
)
)
;
}
$
ret
=
@
yaml_parse
(
$
contents
)
;
if
(
$
ret
===
false
)
{
return
$
ret
;
}
$
yamls
[
$
filename
]
=
$
ret
;
if
(
isset
(
$
ret
[
'import'
]
)
)
{
foreach
(
$
ret
[
'import'
]
as
$
imported
)
{
foreach
(
$
this
->
_loadYaml
(
$
imported
)
as
$
name
=>
$
yaml
)
{
$
yamls
[
$
name
]
=
$
yaml
;
}
}
}
return
$
yamls
;
}

Initializes yaml contents.

@param string $filename

@throws BeanFactoryException
@return mixed[]


private function _load()
    {
        if ($this->_yamlFiles !== false) {
            return;
        }
        $this->_yamlFiles = $this->_loadYaml($this->_filename);
        if (empty($this->_yamlFiles)) {
            throw new BeanFactoryException('Could not parse: ' . $this->_filename);
        }
    }

private
function
_load
(
)
{
if
(
$
this
->
_yamlFiles
!==
false
)
{
return
;
}
$
this
->
_yamlFiles
=
$
this
->
_loadYaml
(
$
this
->
_filename
)
;
if
(
empty
(
$
this
->
_yamlFiles
)
)
{
throw
new
BeanFactoryException
(
'Could not parse: '
.
$
this
->
_filename
)
;
}
}

Initialize YAML contents.

@throws BeanFactoryException
@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;
    }

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 ; }

Loads pami and initializes everything.

@return void


public function open()
    {
        if (!$this->_init) {
            $this->_load();
        }
	    $this->_ami->registerEventListener($this);
	    $this->_ami->open();
    }

public function open ( ) { if ( ! $ this -> _init ) { $ this -> _load ( ) ; } $ this -> _ami -> registerEventListener ( $ this ) ; $ this -> _ami -> open ( ) ; }

Opens the connection to ami. Also calls _load if it has to.

@return void

Opens the connection to ami . Also calls _load if it has to .


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');
        }
    }

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'
)
;
}
}

Factory for cache implementations.

@param array $options Cache options.

@throws CacheException
@return ICache


public function afterDefinition(BeanDefinition $bean)
    {
        $return = $bean;
        foreach ($this->_lifecyclers[BeanLifecycle::AfterDefinition] as $lifecycleListener) {
            $return = $lifecycleListener->afterDefinition($return);
        }
        return $return;
    }

public function afterDefinition ( BeanDefinition $ bean ) { $ return = $ bean ; foreach ( $ this -> _lifecyclers [ BeanLifecycle :: AfterDefinition ] as $ lifecycleListener ) { $ return = $ lifecycleListener -> afterDefinition ( $ return ) ; } return $ return ; }

Runs the AfterDefinition point of the lifecycle.

@param string         $beanName Bean name.
@param BeanDefinition $bean     Actual definition.

@return BeanDefinition

Runs the AfterDefinition point of the lifecycle .


public function beforeCreate(BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::BeforeCreate] as $lifecycleListener) {
            $lifecycleListener->beforeCreate($beanDefinition);
        }
    }

public function beforeCreate ( BeanDefinition $ beanDefinition ) { foreach ( $ this -> _lifecyclers [ BeanLifecycle :: BeforeCreate ] as $ lifecycleListener ) { $ lifecycleListener -> beforeCreate ( $ beanDefinition ) ; } }

Runs the BeforeCreate point of the lifecycle.

@param BeanDefinition $beanDefinition Actual definition.

@return void

Runs the BeforeCreate point of the lifecycle .


public function afterCreate($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::AfterCreate] as $lifecycleListener) {
            $lifecycleListener->afterCreate($bean, $beanDefinition);
        }
    }

public function afterCreate ( $ bean , BeanDefinition $ beanDefinition ) { foreach ( $ this -> _lifecyclers [ BeanLifecycle :: AfterCreate ] as $ lifecycleListener ) { $ lifecycleListener -> afterCreate ( $ bean , $ beanDefinition ) ; } }

Runs the AfterCreate point of the lifecycle.

@param string         $beanName Bean name.
@param BeanDefinition $bean     Actual definition.

@return void

Runs the AfterCreate point of the lifecycle .


public function beforeAssemble($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::BeforeAssemble] as $lifecycleListener) {
            $lifecycleListener->beforeAssemble($bean, $beanDefinition);
        }
    }

public function beforeAssemble ( $ bean , BeanDefinition $ beanDefinition ) { foreach ( $ this -> _lifecyclers [ BeanLifecycle :: BeforeAssemble ] as $ lifecycleListener ) { $ lifecycleListener -> beforeAssemble ( $ bean , $ beanDefinition ) ; } }

Runs the BeforeAssemble point of the lifecycle.

@param string         $beanName Bean name.
@param BeanDefinition $bean     Actual definition.

@return BeanDefinition

Runs the BeforeAssemble point of the lifecycle .


public function afterAssemble($bean, BeanDefinition $beanDefinition)
    {
        foreach ($this->_lifecyclers[BeanLifecycle::AfterAssemble] as $lifecycleListener) {
            $lifecycleListener->afterAssemble($bean, $beanDefinition);
        }
    }

public function afterAssemble ( $ bean , BeanDefinition $ beanDefinition ) { foreach ( $ this -> _lifecyclers [ BeanLifecycle :: AfterAssemble ] as $ lifecycleListener ) { $ lifecycleListener -> afterAssemble ( $ bean , $ beanDefinition ) ; } }

Runs the AfterAssemble point of the lifecycle.

@param object         $bean           Bean.
@param BeanDefinition $beanDefinition Actual definition.

@return void

Runs the AfterAssemble point of the lifecycle .


public function open()
    {
        openlog($this->_ident, intval($this->_options), intval($this->_facility));
    }

public function open ( ) { openlog ( $ this -> _ident , intval ( $ this -> _options ) , intval ( $ this -> _facility ) ) ; }


public function getInterceptors($method)
    {
        if (!isset($this->_methodsIntercepted[$method])) {
            return false;
        }
        return $this->_methodsIntercepted[$method];
    }

public function getInterceptors ( $ method ) { if ( ! isset ( $ this -> _methodsIntercepted [ $ method ] ) ) { return false ; } return $ this -> _methodsIntercepted [ $ method ] ; }

Returns interceptors for a given method name or false if none was set.

@param string $method Method to check for.

@return object[]

Returns interceptors for a given method name or false if none was set .


public function getExceptionInterceptors($method)
    {
        if (!isset($this->_methodsExceptionIntercepted[$method])) {
            return false;
        }
        return $this->_methodsExceptionIntercepted[$method];
    }

public function getExceptionInterceptors ( $ method ) { if ( ! isset ( $ this -> _methodsExceptionIntercepted [ $ method ] ) ) { return false ; } return $ this -> _methodsExceptionIntercepted [ $ method ] ; }

Returns exception interceptors for a given method name or
false if none was set.

@param string $method Method to check for.

@return object[]

Returns exception interceptors for a given method name or false if none was set .


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();
    }

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 ( ) ; }

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

Will chain and return the result of the chained call of interceptors .


public function invokeException(MethodInvocation $invocation)
    {
        $interceptors = $this->getExceptionInterceptors($method = $invocation->getMethod());
        if ($interceptors != false && !empty($interceptors)) {
            return $this->_callInterceptors($invocation, $interceptors);
        }
        throw $invocation->getException();
    }

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 throws an
exception.

@param MethodInvocation $invocation Method invocation "descriptor".

@return void

The proxy will call this method when an aspected method throws an exception .


public function invoke(MethodInvocation $invocation)
    {
        $interceptors = $this->getInterceptors($invocation->getMethod());
        if ($interceptors != false) {
            return $this->_callInterceptors($invocation, $interceptors);
        }
        return $invocation->proceed();
    }

public function invoke ( MethodInvocation $ invocation ) { $ interceptors = $ this -> getInterceptors ( $ invocation -> getMethod ( ) ) ; if ( $ interceptors != false ) { return $ this -> _callInterceptors ( $ invocation , $ interceptors ) ; } return $ invocation -> proceed ( ) ; }

The proxy will call this method when an aspected method is called.

@param MethodInvocation $invocation Method invocation "descriptor".

@return void

The proxy will call this method when an aspected method is called .


public function close()
    {
        $this->_connected = false;
        $this->_handler->disconnect();
        socket_close($this->_socket);
        $this->_socket = false;
    }

public function close ( ) { $ this -> _connected = false ; $ this -> _handler -> disconnect ( ) ; socket_close ( $ this -> _socket ) ; $ this -> _socket = false ; }

Call this to close the connection.

@return void


public function read(&$buffer, $length, $peek = false)
    {
        $length = socket_recv($this->_socket, $buffer, $length, $peek ? MSG_PEEK : 0);
        return $length;
    }

public function read ( & $ buffer , $ length , $ peek = false ) { $ length = socket_recv ( $ this -> _socket , $ buffer , $ length , $ peek ? MSG_PEEK : 0 ) ; return $ length ; }

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

Call this to read data from the server . Returns the number of bytes read .


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'));
    }

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
=
;
$
ex
=
;
$
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'
)
)
;
}

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

Call this to open the connection to the server . Will also set the socket non blocking and control the connection timeout .


public function add(array $objects)
    {
        foreach ($objects as $name => $value) {
            $this->_objects[$name] = $value;
        }
    }

public function add ( array $ objects ) { foreach ( $ objects as $ name => $ value ) { $ this -> _objects [ $ name ] = $ value ; } }

Add model objects.

@param array $objects Key = object name (string), value is mixed.

@return void


protected function buildUri(string $uri, string $filePath, int $line): string
    {
        $uri = str_replace('%file', $filePath, $uri);
        $uri = str_replace('%line', $line, $uri);

        return $uri;
    }

protected function buildUri ( string $ uri , string $ filePath , int $ line ) : string { $ uri = str_replace ( '%file' , $ filePath , $ uri ) ; $ uri = str_replace ( '%line' , $ line , $ uri ) ; return $ uri ; }

Build URI for editor based on file path and line.

@param string $uri
@param string $filePath
@param int $line
@return string

Build URI for editor based on file path and line .


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;
        });
    }

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 config with Whoops Editor.

@return void

Overwrite application editor config with Whoops Editor .


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);
    }

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 ) ; }

Resolve file path when using Homestead.

@param string $filePath
@return string

Resolve file path when using Homestead .


public static function publishedDropDownList()
    {
        $formatter = Yii::$app->formatter;
        return [
            false => $formatter->asBoolean(false),
            true => $formatter->asBoolean(true),
        ];
    }

public static function publishedDropDownList ( ) { $ formatter = Yii :: $ app -> formatter ; return [ false => $ formatter -> asBoolean ( false ) , true => $ formatter -> asBoolean ( true ) , ] ; }

List values of field 'published' with label.
@return array

List values of field published with label .


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'));
    }

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' ) ) ; }

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

Finds the Page model based on alias value . If the model is not found a 404 HTTP exception will be thrown .


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;
    }

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 ; }

Create a new link.

@param string $name
@param string $url
@param bool $isInternal
@param bool $isNewtab
@return static


public function actionUpdate($id = null)
    {
        if ($id === null) {
            $model = new Page();
            $model->display_title = true;
        } else {
            $model = $this->findModel($id);
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            Yii::$app->session->setFlash('success', Module::t('SAVE_SUCCESS'));
            return $this->redirect(['update', 'id' => $model->id]);
        }

        $module = Yii::$app->getModule('pages');

        return $this->render($id === null ? 'create' : 'update', [
            'model' => $model,
            'module' => $module,
        ]);
    }

public function actionUpdate ( $ id = null ) { if ( $ id === null ) { $ model = new Page ( ) ; $ model -> display_title = true ; } else { $ model = $ this -> findModel ( $ id ) ; } if ( $ model -> load ( Yii :: $ app -> request -> post ( ) ) && $ model -> save ( ) ) { Yii :: $ app -> session -> setFlash ( 'success' , Module :: t ( 'SAVE_SUCCESS' ) ) ; return $ this -> redirect ( [ 'update' , 'id' => $ model -> id ] ) ; } $ module = Yii :: $ app -> getModule ( 'pages' ) ; return $ this -> render ( $ id === null ? 'create' : 'update' , [ 'model' => $ model , 'module' => $ module , ] ) ; }

Updates an existing Page model.
If update is successful, the browser will be redirected to the 'update' page.
@param integer|null $id
@return mixed

Updates an existing Page model . If update is successful the browser will be redirected to the update page .


private function registerTranslations()
    {
        Yii::$app->i18n->translations['datepicker'] = [
            'class' => 'yii\i18n\PhpMessageSource',
            'sourceLanguage' => 'en-US',
            'basePath' => __DIR__ . DIRECTORY_SEPARATOR . 'messages',
            'forceTranslation' => true,
        ];

        $this->clientOptions['tooltips'] = [
            'today' => Yii::t('datepicker', 'Go to today'),
            'clear' => Yii::t('datepicker', 'Clear selection'),
            'close' => Yii::t('datepicker', 'Close the picker'),
            'selectMonth' => Yii::t('datepicker', 'Select Month'),
            'prevMonth' => Yii::t('datepicker', 'Previous Month'),
            'nextMonth' => Yii::t('datepicker', 'Next Month'),
            'selectYear' => Yii::t('datepicker', 'Select Year'),
            'prevYear' => Yii::t('datepicker', 'Previous Year'),
            'nextYear' => Yii::t('datepicker', 'Next Year'),
            'selectDecade' => Yii::t('datepicker', 'Select Decade'),
            'prevDecade' => Yii::t('datepicker', 'Previous Decade'),
            'nextDecade' => Yii::t('datepicker', 'Next Decade'),
            'prevCentury' => Yii::t('datepicker', 'Previous Century'),
            'nextCentury' => Yii::t('datepicker', 'Next Century'),
            'pickHour' => Yii::t('datepicker', 'Pick Hour'),
            'incrementHour' => Yii::t('datepicker', 'Increment Hour'),
            'decrementHour' => Yii::t('datepicker', 'Decrement Hour'),
            'pickMinute' => Yii::t('datepicker', 'Pick Minute'),
            'incrementMinute' => Yii::t('datepicker', 'Increment Minute'),
            'decrementMinute' => Yii::t('datepicker', 'Decrement Minute'),
            'pickSecond' => Yii::t('datepicker', 'Pick Second'),
            'incrementSecond' => Yii::t('datepicker', 'Increment Second'),
            'decrementSecond' => Yii::t('datepicker', 'Decrement Second'),
            'togglePeriod' => Yii::t('datepicker', 'Toggle Period'),
            'selectTime' => Yii::t('datepicker', 'Select Time'),
        ];
    }

private
function
registerTranslations
(
)
{
Yii
::
$
app
->
i18n
->
translations
[
'datepicker'
]
=
[
'class'
=>
'yii\i18n\PhpMessageSource'
,
'sourceLanguage'
=>
'en-US'
,
'basePath'
=>
__DIR__
.
DIRECTORY_SEPARATOR
.
'messages'
,
'forceTranslation'
=>
true
,
]
;
$
this
->
clientOptions
[
'tooltips'
]
=
[
'today'
=>
Yii
::
t
(
'datepicker'
,
'Go to today'
)
,
'clear'
=>
Yii
::
t
(
'datepicker'
,
'Clear selection'
)
,
'close'
=>
Yii
::
t
(
'datepicker'
,
'Close the picker'
)
,
'selectMonth'
=>
Yii
::
t
(
'datepicker'
,
'Select Month'
)
,
'prevMonth'
=>
Yii
::
t
(
'datepicker'
,
'Previous Month'
)
,
'nextMonth'
=>
Yii
::
t
(
'datepicker'
,
'Next Month'
)
,
'selectYear'
=>
Yii
::
t
(
'datepicker'
,
'Select Year'
)
,
'prevYear'
=>
Yii
::
t
(
'datepicker'
,
'Previous Year'
)
,
'nextYear'
=>
Yii
::
t
(
'datepicker'
,
'Next Year'
)
,
'selectDecade'
=>
Yii
::
t
(
'datepicker'
,
'Select Decade'
)
,
'prevDecade'
=>
Yii
::
t
(
'datepicker'
,
'Previous Decade'
)
,
'nextDecade'
=>
Yii
::
t
(
'datepicker'
,
'Next Decade'
)
,
'prevCentury'
=>
Yii
::
t
(
'datepicker'
,
'Previous Century'
)
,
'nextCentury'
=>
Yii
::
t
(
'datepicker'
,
'Next Century'
)
,
'pickHour'
=>
Yii
::
t
(
'datepicker'
,
'Pick Hour'
)
,
'incrementHour'
=>
Yii
::
t
(
'datepicker'
,
'Increment Hour'
)
,
'decrementHour'
=>
Yii
::
t
(
'datepicker'
,
'Decrement Hour'
)
,
'pickMinute'
=>
Yii
::
t
(
'datepicker'
,
'Pick Minute'
)
,
'incrementMinute'
=>
Yii
::
t
(
'datepicker'
,
'Increment Minute'
)
,
'decrementMinute'
=>
Yii
::
t
(
'datepicker'
,
'Decrement Minute'
)
,
'pickSecond'
=>
Yii
::
t
(
'datepicker'
,
'Pick Second'
)
,
'incrementSecond'
=>
Yii
::
t
(
'datepicker'
,
'Increment Second'
)
,
'decrementSecond'
=>
Yii
::
t
(
'datepicker'
,
'Decrement Second'
)
,
'togglePeriod'
=>
Yii
::
t
(
'datepicker'
,
'Toggle Period'
)
,
'selectTime'
=>
Yii
::
t
(
'datepicker'
,
'Select Time'
)
,
]
;
}


public function registerClientScript()
    {
        $js = [];
        $view = $this->getView();

        DatePickerAsset::register($view);

        $id = $this->options['id'];
        $selector = ";jQuery('#$id')";

        if ($this->addon) {
            $selector .= ".parent()";
        }

        $this->hashPluginOptions($view);

        $js[] = "$selector." . self::PLUGIN_NAME . "({$this->_hashVar});";

        if (!empty($this->dropdownItems)) {
            $js[] = "$selector.find('.dropdown-menu a').on('click', function (e) { e.preventDefault(); jQuery('#$id').val(jQuery(this).data('value')); });";
        }

        if ($this->showDecades === false) {
            $js[] = "$selector.on('dp.show dp.update', function () { $(this).find('.datepicker-years .picker-switch').removeAttr('title').css('cursor', 'default').css('background', 'inherit').on('click', function (e) { e.stopPropagation(); }); });";
        }

        if (!empty($this->clientEvents)) {
            foreach ($this->clientEvents as $event => $handler) {
                $js[] = "$selector.on('$event', $handler);";
            }
        }

        $view->registerJs(implode("\n", $js) . "\n");
    }

Registers required script for the plugin to work as DatePicker.

Registers required script for the plugin to work as DatePicker .


public function vote(TokenInterface $token, $object, array $attributes)
    {
        $user = $token->getUser();

        foreach ($attributes as $attribute) {
            if (!$this->supportsAttribute($attribute)) {
                continue;
            }

            if ($this->hasRole($token, 'ROLE_ADMIN')) {
                return VoterInterface::ACCESS_GRANTED;
            }

            if ($attribute == 'EDIT_USER') {
                $user2 = $object;
                return $this->usersHaveSameId($user, $user2) ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
            }

            if ($attribute == 'EDIT_USER_ID') {
                $id = $object;
                return $this->hasUserId($user, $id) ? VoterInterface::ACCESS_GRANTED : VoterInterface::ACCESS_DENIED;
            }
        }

        return VoterInterface::ACCESS_ABSTAIN;
    }

public function vote ( TokenInterface $ token , $ object , array $ attributes ) { $ user = $ token -> getUser ( ) ; foreach ( $ attributes as $ attribute ) { if ( ! $ this -> supportsAttribute ( $ attribute ) ) { continue ; } if ( $ this -> hasRole ( $ token , 'ROLE_ADMIN' ) ) { return VoterInterface :: ACCESS_GRANTED ; } if ( $ attribute == 'EDIT_USER' ) { $ user2 = $ object ; return $ this -> usersHaveSameId ( $ user , $ user2 ) ? VoterInterface :: ACCESS_GRANTED : VoterInterface :: ACCESS_DENIED ; } if ( $ attribute == 'EDIT_USER_ID' ) { $ id = $ object ; return $ this -> hasUserId ( $ user , $ id ) ? VoterInterface :: ACCESS_GRANTED : VoterInterface :: ACCESS_DENIED ; } } return VoterInterface :: ACCESS_ABSTAIN ; }

Returns the vote for the given parameters.

This method must return one of the following constants:
ACCESS_GRANTED, ACCESS_DENIED, or ACCESS_ABSTAIN.

@param TokenInterface $token      A TokenInterface instance
@param object $object     The object to secure
@param array $attributes An array of attributes associated with the method being invoked

@return integer either ACCESS_GRANTED, ACCESS_ABSTAIN, or ACCESS_DENIED

Returns the vote for the given parameters .


protected function getFromEmail()
    {
        if (!$this->fromAddress) {
            return null;
        }

        if ($this->fromName) {
            return array($this->fromAddress => $this->fromName);
        }

        return $this->fromAddress;
    }

protected function getFromEmail ( ) { if ( ! $ this -> fromAddress ) { return null ; } if ( $ this -> fromName ) { return array ( $ this -> fromAddress => $ this -> fromName ) ; } return $ this -> fromAddress ; }

Format the fromEmail parameter for the Swift_Mailer.

@return array|string|null

Format the fromEmail parameter for the Swift_Mailer .


public function loadUserByUsername($username)
    {
        if (strpos($username, '@') !== false) {
            $user = $this->findOneBy(array($this->getUserColumns('email') => $username));
            if (!$user) {
                throw new UsernameNotFoundException(sprintf('Email "%s" does not exist.', $username));
            }

            return $user;
        }

        $user = $this->findOneBy(array($this->getUserColumns('username') => $username));
        if (!$user) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
        }

        return $user;
    }

public
function
loadUserByUsername
(
$
username
)
{
if
(
strpos
(
$
username
,
'@'
)
!==
false
)
{
$
user
=
$
this
->
findOneBy
(
array
(
$
this
->
getUserColumns
(
'email'
)
=>
$
username
)
)
;
if
(
!
$
user
)
{
throw
new
UsernameNotFoundException
(
sprintf
(
'Email "%s" does not exist.'
,
$
username
)
)
;
}
return
$
user
;
}
$
user
=
$
this
->
findOneBy
(
array
(
$
this
->
getUserColumns
(
'username'
)
=>
$
username
)
)
;
if
(
!
$
user
)
{
throw
new
UsernameNotFoundException
(
sprintf
(
'Username "%s" does not exist.'
,
$
username
)
)
;
}
return
$
user
;
}

Loads the user for the given username or email address.

Required by UserProviderInterface.

@param string $username The username
@return UserInterface
@throws UsernameNotFoundException if the user is not found

Loads the user for the given username or email address .


protected function hydrateUser(array $data)
    {
        // Test for new columns added in v2.0.
        // If they're missing, throw an exception and explain that migration is needed.
        foreach (array(
                    $this->getUserColumns('username'),
                    $this->getUserColumns('isEnabled'),
                    $this->getUserColumns('confirmationToken'),
                    $this->getUserColumns('timePasswordResetRequested')
                ) as $col) {
            if (!array_key_exists($col, $data)) {
                throw new \RuntimeException('Internal error: database schema appears out of date. See https://github.com/jasongrimes/silex-simpleuser/blob/master/sql/MIGRATION.md');
            }
        }

        $userClass = $this->getUserClass();

        /** @var User $user */
        $user = new $userClass($data['email']);

        $user->setId($data['id']);
        $user->setPassword($data['password']);
        $user->setSalt($data['salt']);
        $user->setName($data['name']);
        if ($roles = explode(',', $data['roles'])) {
            $user->setRoles($roles);
        }
        $user->setTimeCreated($data['time_created']);
        $user->setUsername($data['username']);
        $user->setEnabled($data['isEnabled']);
        $user->setConfirmationToken($data['confirmationToken']);
        $user->setTimePasswordResetRequested($data['timePasswordResetRequested']);

        if (!empty($data['customFields'])) {
            $user->setCustomFields($data['customFields']);
        }

        return $user;
    }

Reconstitute a User object from stored data.

@param array $data
@return User
@throws \RuntimeException if database schema is out of date.

Reconstitute a User object from stored data .


public function createUser($email, $plainPassword, $name = null, $roles = array())
    {

        $userClass = $this->getUserClass();

        $user = new $userClass($email);

        if (!empty($plainPassword)) {
            $this->setUserPassword($user, $plainPassword);
        }

        if ($name !== null) {
            $user->setName($name);
        }
        if (!empty($roles)) {
            $user->setRoles($roles);
        }

        return $user;
    }

public function createUser ( $ email , $ plainPassword , $ name = null , $ roles = array ( ) ) { $ userClass = $ this -> getUserClass ( ) ; $ user = new $ userClass ( $ email ) ; if ( ! empty ( $ plainPassword ) ) { $ this -> setUserPassword ( $ user , $ plainPassword ) ; } if ( $ name !== null ) { $ user -> setName ( $ name ) ; } if ( ! empty ( $ roles ) ) { $ user -> setRoles ( $ roles ) ; } return $ user ; }

Factory method for creating a new User instance.

@param string $email
@param string $plainPassword
@param string $name
@param array $roles
@return User

Factory method for creating a new User instance .


public function setUserPassword(User $user, $password)
    {
        $user->setPassword($this->encodeUserPassword($user, $password));
    }

public function setUserPassword ( User $ user , $ password ) { $ user -> setPassword ( $ this -> encodeUserPassword ( $ user , $ password ) ) ; }

Encode a plain text password and set it on the given User object.

@param User $user
@param string $password A plain text password.

Encode a plain text password and set it on the given User object .


public function checkUserPassword(User $user, $password)
    {
        return $user->getPassword() === $this->encodeUserPassword($user, $password);
    }

public function checkUserPassword ( User $ user , $ password ) { return $ user -> getPassword ( ) === $ this -> encodeUserPassword ( $ user , $ password ) ; }

Test whether a given plain text password matches a given User's encoded password.

@param User $user
@param string $password
@return bool

Test whether a given plain text password matches a given User s encoded password .


function isLoggedIn()
    {
        $token = $this->app['security']->getToken();
        if (null === $token) {
            return false;
        }

        return $this->app['security']->isGranted('IS_AUTHENTICATED_REMEMBERED');
    }

function isLoggedIn ( ) { $ token = $ this -> app [ 'security' ] -> getToken ( ) ; if ( null === $ token ) { return false ; } return $ this -> app [ 'security' ] -> isGranted ( 'IS_AUTHENTICATED_REMEMBERED' ) ; }

Test whether the current user is authenticated.

@return boolean

Test whether the current user is authenticated .


public function findOneBy(array $criteria)
    {
        $users = $this->findBy($criteria);

        if (empty($users)) {
            return null;
        }

        return reset($users);
    }

public function findOneBy ( array $ criteria ) { $ users = $ this -> findBy ( $ criteria ) ; if ( empty ( $ users ) ) { return null ; } return reset ( $ users ) ; }

Get a single User instance that matches the given criteria. If more than one User matches, the first result is returned.

@param array $criteria
@return User|null

Get a single User instance that matches the given criteria . If more than one User matches the first result is returned .


public function findBy(array $criteria = array(), array $options = array())
    {
        // Check the identity map first.
        if (array_key_exists($this->getUserColumns('id'), $criteria)
            && array_key_exists($criteria[$this->getUserColumns('id')], $this->identityMap)) {
            return array($this->identityMap[$criteria[$this->getUserColumns('id')]]);
        }

        list ($common_sql, $params) = $this->createCommonFindSql($criteria);

        $sql = 'SELECT * ' . $common_sql;

        if (array_key_exists('order_by', $options)) {
            list ($order_by, $order_dir) = is_array($options['order_by']) ? $options['order_by'] : array($options['order_by']);
            $sql .= 'ORDER BY ' . $this->conn->quoteIdentifier($order_by) . ' ' . ($order_dir == 'DESC' ? 'DESC' : 'ASC') . ' ';
        }
        if (array_key_exists('limit', $options)) {
            list ($offset, $limit) = is_array($options['limit']) ? $options['limit'] : array(0, $options['limit']);
            $sql .=   ' LIMIT ' . (int) $limit . ' ' .' OFFSET ' . (int) $offset ;
        }

        $data = $this->conn->fetchAll($sql, $params);

        $users = array();
        foreach ($data as $userData) {
            if (array_key_exists($userData[$this->getUserColumns('id')], $this->identityMap)) {
                $user = $this->identityMap[$userData[$this->getUserColumns('id')]];
            } else {
                $userData['customFields'] = $this->getUserCustomFields($userData[$this->getUserColumns('id')]);
                $user = $this->hydrateUser($userData);
                $this->identityMap[$user->getId()] = $user;
            }
            $users[] = $user;
        }

        return $users;
    }

public
function
findBy
(
array
$
criteria
=
array
(
)
,
array
$
options
=
array
(
)
)
{
// Check the identity map first.
if
(
array_key_exists
(
$
this
->
getUserColumns
(
'id'
)
,
$
criteria
)
&&
array_key_exists
(
$
criteria
[
$
this
->
getUserColumns
(
'id'
)
]
,
$
this
->
identityMap
)
)
{
return
array
(
$
this
->
identityMap
[
$
criteria
[
$
this
->
getUserColumns
(
'id'
)
]
]
)
;
}
list
(
$
common_sql
,
$
params
)
=
$
this
->
createCommonFindSql
(
$
criteria
)
;
$
sql
=
'SELECT * '
.
$
common_sql
;
if
(
array_key_exists
(
'order_by'
,
$
options
)
)
{
list
(
$
order_by
,
$
order_dir
)
=
is_array
(
$
options
[
'order_by'
]
)
$
options
[
'order_by'
]
:
array
(
$
options
[
'order_by'
]
)
;
$
sql
.=
'ORDER BY '
.
$
this
->
conn
->
quoteIdentifier
(
$
order_by
)
.
' '
.
(
$
order_dir
==
'DESC'
'DESC'
:
'ASC'
)
.
' '
;
}
if
(
array_key_exists
(
'limit'
,
$
options
)
)
{
list
(
$
offset
,
$
limit
)
=
is_array
(
$
options
[
'limit'
]
)
$
options
[
'limit'
]
:
array
(
0
,
$
options
[
'limit'
]
)
;
$
sql
.=
' LIMIT '
.
(
int
)
$
limit
.
' '
.
' OFFSET '
.
(
int
)
$
offset
;
}
$
data
=
$
this
->
conn
->
fetchAll
(
$
sql
,
$
params
)
;
$
users
=
array
(
)
;
foreach
(
$
data
as
$
userData
)
{
if
(
array_key_exists
(
$
userData
[
$
this
->
getUserColumns
(
'id'
)
]
,
$
this
->
identityMap
)
)
{
$
user
=
$
this
->
identityMap
[
$
userData
[
$
this
->
getUserColumns
(
'id'
)
]
]
;
}
else
{
$
userData
[
'customFields'
]
=
$
this
->
getUserCustomFields
(
$
userData
[
$
this
->
getUserColumns
(
'id'
)
]
)
;
$
user
=
$
this
->
hydrateUser
(
$
userData
)
;
$
this
->
identityMap
[
$
user
->
getId
(
)
]
=
$
user
;
}
$
users
[
]
=
$
user
;
}
return
$
users
;
}

Find User instances that match the given criteria.

@param array $criteria
@param array $options An array of the following options (all optional):<pre>
limit (int|array) The maximum number of results to return, or an array of (offset, limit).
order_by (string|array) The name of the column to order by, or an array of column name and direction, ex. array(time_created, DESC)
</pre>
@return User[] An array of matching User instances, or an empty array if no matching users were found.

Find User instances that match the given criteria .


protected function createCommonFindSql(array $criteria = array())
    {
        $params = array();

        $sql = 'FROM ' . $this->conn->quoteIdentifier($this->userTableName). ' ';
        // JOIN on custom fields, if needed.
        if (array_key_exists('customFields', $criteria)) {
            $i = 0;
            foreach ($criteria['customFields'] as $attribute => $value) {
                $i++;
                $alias = 'custom' . $i;
                $sql .= 'JOIN ' . $this->conn->quoteIdentifier($this->userCustomFieldsTableName). ' ' . $alias . ' ';
                $sql .= 'ON ' . $this->conn->quoteIdentifier($this->userTableName). '.' . $this->getUserColumns('id') . ' = ' . $alias . '.'. $this->getUserColumns('user_id').' ';
                $sql .= 'AND ' . $alias . '.'.$this->getUserColumns('attribute').' = :attribute' . $i . ' ';
                $sql .= 'AND ' . $alias . '.'.$this->getUserColumns('value').' = :value' . $i . ' ';
                $params['attribute' . $i] = $attribute;
                $params['value' . $i] = $value;
            }
        }

        $first_crit = true;
        foreach ($criteria as $key => $val) {
            if ($key == 'customFields') {
                continue;
            } else {
                $sql .= ($first_crit ? 'WHERE' : 'AND') . ' ' . $key . ' = :' . $key . ' ';
                $params[$key] = $val;
            }
            $first_crit = false;
        }

        return array ($sql, $params);
    }

protected
function
createCommonFindSql
(
array
$
criteria
=
array
(
)
)
{
$
params
=
array
(
)
;
$
sql
=
'FROM '
.
$
this
->
conn
->
quoteIdentifier
(
$
this
->
userTableName
)
.
' '
;
// JOIN on custom fields, if needed.
if
(
array_key_exists
(
'customFields'
,
$
criteria
)
)
{
$
i
=
0
;
foreach
(
$
criteria
[
'customFields'
]
as
$
attribute
=>
$
value
)
{
$
i
++
;
$
alias
=
'custom'
.
$
i
;
$
sql
.=
'JOIN '
.
$
this
->
conn
->
quoteIdentifier
(
$
this
->
userCustomFieldsTableName
)
.
' '
.
$
alias
.
' '
;
$
sql
.=
'ON '
.
$
this
->
conn
->
quoteIdentifier
(
$
this
->
userTableName
)
.
'.'
.
$
this
->
getUserColumns
(
'id'
)
.
' = '
.
$
alias
.
'.'
.
$
this
->
getUserColumns
(
'user_id'
)
.
' '
;
$
sql
.=
'AND '
.
$
alias
.
'.'
.
$
this
->
getUserColumns
(
'attribute'
)
.
' = :attribute'
.
$
i
.
' '
;
$
sql
.=
'AND '
.
$
alias
.
'.'
.
$
this
->
getUserColumns
(
'value'
)
.
' = :value'
.
$
i
.
' '
;
$
params
[
'attribute'
.
$
i
]
=
$
attribute
;
$
params
[
'value'
.
$
i
]
=
$
value
;
}
}
$
first_crit
=
true
;
foreach
(
$
criteria
as
$
key
=>
$
val
)
{
if
(
$
key
==
'customFields'
)
{
continue
;
}
else
{
$
sql
.=
(
$
first_crit
'WHERE'
:
'AND'
)
.
' '
.
$
key
.
' = :'
.
$
key
.
' '
;
$
params
[
$
key
]
=
$
val
;
}
$
first_crit
=
false
;
}
return
array
(
$
sql
,
$
params
)
;
}

Get SQL query fragment common to both find and count querires.

@param array $criteria
@return array An array of SQL and query parameters, in the form array($sql, $params)

Get SQL query fragment common to both find and count querires .


public function findCount(array $criteria = array())
    {
        list ($common_sql, $params) = $this->createCommonFindSql($criteria);

        $sql = 'SELECT COUNT(*) ' . $common_sql;

        return $this->conn->fetchColumn($sql, $params) ?: 0;
    }

public
function
findCount
(
array
$
criteria
=
array
(
)
)
{
list
(
$
common_sql
,
$
params
)
=
$
this
->
createCommonFindSql
(
$
criteria
)
;
$
sql
=
'SELECT COUNT(*) '
.
$
common_sql
;
return
$
this
->
conn
->
fetchColumn
(
$
sql
,
$
params
)
:
0
;
}

Count users that match the given criteria.

@param array $criteria
@return int The number of users that match the criteria.

Count users that match the given criteria .


public function insert(User $user)
    {
        $this->dispatcher->dispatch(UserEvents::BEFORE_INSERT, new UserEvent($user));

        $sql = 'INSERT INTO ' . $this->conn->quoteIdentifier($this->userTableName) . '
            ('.$this->getUserColumns('email').', '.$this->getUserColumns('password').', '.$this->getUserColumns('salt').', '.$this->getUserColumns('name').
                ', '.$this->getUserColumns('roles').', '.$this->getUserColumns('time_created').', '.$this->getUserColumns('username').', '.$this->getUserColumns('isEnabled').
                ', '.$this->getUserColumns('confirmationToken').', '.$this->getUserColumns('timePasswordResetRequested').')
            VALUES (:email, :password, :salt, :name, :roles, :timeCreated, :username, :isEnabled, :confirmationToken, :timePasswordResetRequested) ';

        $params = array(
            'email' => $user->getEmail(),
            'password' => $user->getPassword(),
            'salt' => $user->getSalt(),
            'name' => $user->getName(),
            'roles' => implode(',', $user->getRoles()),
            'timeCreated' => $user->getTimeCreated(),
            'username' => $user->getRealUsername(),
            'isEnabled' => $user->isEnabled(),
            'confirmationToken' => $user->getConfirmationToken(),
            'timePasswordResetRequested' => $user->getTimePasswordResetRequested(),
        );

        $this->conn->executeUpdate($sql, $params);

        $user->setId($this->conn->lastInsertId());

        $this->saveUserCustomFields($user);

        $this->identityMap[$user->getId()] = $user;

        $this->dispatcher->dispatch(UserEvents::AFTER_INSERT, new UserEvent($user));
    }

Insert a new User instance into the database.

@param User $user

Insert a new User instance into the database .


public function update(User $user)
    {
        $this->dispatcher->dispatch(UserEvents::BEFORE_UPDATE, new UserEvent($user));

        $sql = 'UPDATE ' . $this->conn->quoteIdentifier($this->userTableName). '
            SET '.$this->getUserColumns('email').' = :email
            , '.$this->getUserColumns('password').' = :password
            , '.$this->getUserColumns('salt').' = :salt
            , '.$this->getUserColumns('name').' = :name
            , '.$this->getUserColumns('roles').' = :roles
            , '.$this->getUserColumns('time_created').' = :timeCreated
            , '.$this->getUserColumns('username').' = :username
            , '.$this->getUserColumns('isEnabled').' = :isEnabled
            , '.$this->getUserColumns('confirmationToken').' = :confirmationToken
            , '.$this->getUserColumns('timePasswordResetRequested').' = :timePasswordResetRequested
            WHERE '.$this->getUserColumns('id').' = :id';

        $params = array(
            'email' => $user->getEmail(),
            'password' => $user->getPassword(),
            'salt' => $user->getSalt(),
            'name' => $user->getName(),
            'roles' => implode(',', $user->getRoles()),
            'timeCreated' => $user->getTimeCreated(),
            'username' => $user->getRealUsername(),
            'isEnabled' => $user->isEnabled(),
            'confirmationToken' => $user->getConfirmationToken(),
            'timePasswordResetRequested' => $user->getTimePasswordResetRequested(),
            'id' => $user->getId(),
        );

        $this->conn->executeUpdate($sql, $params);

        $this->saveUserCustomFields($user);

        $this->dispatcher->dispatch(UserEvents::AFTER_UPDATE, new UserEvent($user));
    }

' = :timePasswordResetRequested
            WHERE '

Update data in the database for an existing user.

@param User $user

Update data in the database for an existing user .


public function delete(User $user)
    {
        $this->dispatcher->dispatch(UserEvents::BEFORE_DELETE, new UserEvent($user));

        $this->clearIdentityMap($user);

        $this->conn->executeUpdate('DELETE FROM ' . $this->conn->quoteIdentifier($this->userTableName). ' WHERE '.$this->getUserColumns('id').' = ?', array($user->getId()));
        $this->conn->executeUpdate('DELETE FROM ' . $this->conn->quoteIdentifier($this->userCustomFieldsTableName). ' WHERE '.$this->getUserColumns('user_id').' = ?', array($user->getId()));

        $this->dispatcher->dispatch(UserEvents::AFTER_DELETE, new UserEvent($user));
    }

public
function
delete
(
User
$
user
)
{
$
this
->
dispatcher
->
dispatch
(
UserEvents
::
BEFORE_DELETE
,
new
UserEvent
(
$
user
)
)
;
$
this
->
clearIdentityMap
(
$
user
)
;
$
this
->
conn
->
executeUpdate
(
'DELETE FROM '
.
$
this
->
conn
->
quoteIdentifier
(
$
this
->
userTableName
)
.
' WHERE '
.
$
this
->
getUserColumns
(
'id'
)
.
' = ?'
,
array
(
$
user
->
getId
(
)
)
)
;
$
this
->
conn
->
executeUpdate
(
'DELETE FROM '
.
$
this
->
conn
->
quoteIdentifier
(
$
this
->
userCustomFieldsTableName
)
.
' WHERE '
.
$
this
->
getUserColumns
(
'user_id'
)
.
' = ?'
,
array
(
$
user
->
getId
(
)
)
)
;
$
this
->
dispatcher
->
dispatch
(
UserEvents
::
AFTER_DELETE
,
new
UserEvent
(
$
user
)
)
;
}

Delete a User from the database.

@param User $user


public function validate(User $user)
    {
        $errors = $user->validate();

        // Ensure email address is unique.
        $duplicates = $this->findBy(array($this->getUserColumns('email') => $user->getEmail()));
        if (!empty($duplicates)) {
            foreach ($duplicates as $dup) {
                if ($user->getId() && $dup->getId() == $user->getId()) {
                    continue;
                }
                $errors['email'] = 'An account with that email address already exists.';
            }
        }

        // Ensure username is unique.
        $duplicates = $this->findBy(array($this->getUserColumns('username') => $user->getRealUsername()));
        if (!empty($duplicates)) {
            foreach ($duplicates as $dup) {
                if ($user->getId() && $dup->getId() == $user->getId()) {
                    continue;
                }
                $errors['username'] = 'An account with that username already exists.';
            }
        }

        // If username is required, ensure it is set.
        if ($this->isUsernameRequired && !$user->getRealUsername()) {
            $errors['username'] = 'Username is required.';
        }

        return $errors;
    }

Validate a user object.

Invokes User::validate(),
and additionally tests that the User's email address and username (if set) are unique across all users.'.

@param User $user
@return array An array of error messages, or an empty array if the User is valid.