public function getLatLongForLocation($location)
    {
        $encoded = urlencode($location);
        $response = json_decode(
            file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=$encoded"),
            true
        );

        if ($response['status'] === 'OK') {
            $lat = $response['results'][0]['geometry']['location']['lat'];
            $long = $response['results'][0]['geometry']['location']['lng'];

            return array($lat, $long);
        }

        return false;
    }

This method uses the Google Maps Geocoding API to retrieve the
lat and long for the given location.

More info here: https://developers.google.com/maps/documentation/geocoding/

@param string $location The location to look up the lat/long for

@return array An array of 2 elements: the lat and the long

This method uses the Google Maps Geocoding API to retrieve the lat and long for the given location .


public function addErrorMsg($event, $msg)
    {
        $event->addResponse(Response::msg($event->getRequest()->getSource(), $msg));
    }

public function addErrorMsg ( $ event , $ msg ) { $ event -> addResponse ( Response :: msg ( $ event -> getRequest ( ) -> getSource ( ) , $ msg ) ) ; }

Add an error message to the response.

@param \Philip\IRC\Event $event The event to add a response to
@param string $msg The error message to send

@return void


private function getEnglishIntensity($intensity)
    {
        $desc = 'no';

        if ($intensity >= 2 && $intensity < 15) {
            $desc = 'sporadic';
        } else if ($intensity >= 15 && $intensity < 30) {
            $desc = 'light';
        } else if ($intensity >= 30 && $intensity < 45) {
            $desc = 'moderate';
        } else if ($intensity > 45) {
            $desc = 'heavy';
        }

        return $desc . ' rain';
    }

private
function
getEnglishIntensity
(
$
intensity
)
{
$
desc
=
'no'
;
if
(
$
intensity
>=
2
&&
$
intensity
<
15
)
{
$
desc
=
'sporadic'
;
}
else
if
(
$
intensity
>=
15
&&
$
intensity
<
30
)
{
$
desc
=
'light'
;
}
else
if
(
$
intensity
>=
30
&&
$
intensity
<
45
)
{
$
desc
=
'moderate'
;
}
else
if
(
$
intensity
>
45
)
{
$
desc
=
'heavy'
;
}
return
$
desc
.
' rain'
;
}

Converts an intensity value to a string.

@param float $intensity The intensity value to convert to a string

@return string

Converts an intensity value to a string .


public function classAnnotations(string $class): array
    {
        $index = static::CLASS_CACHE . $class;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class' => $class,
                ],
                ...$this->parser->getAnnotations(
                $this->getClassReflection($class)->getDocComment()
            )
            );
    }

public function classAnnotations ( string $ class ) : array { $ index = static :: CLASS_CACHE . $ class ; return self :: $ annotations [ $ index ] ?? self :: $ annotations [ $ index ] = $ this -> setAnnotationValues ( [ 'class' => $ class , ] , ... $ this -> parser -> getAnnotations ( $ this -> getClassReflection ( $ class ) -> getDocComment ( ) ) ) ; }

Get a class's annotations.

@param string $class The class

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function classMembersAnnotations(string $class): array
    {
        $index = static::CLASS_MEMBERS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        return self::$annotations[$index] = array_merge(
            $this->propertiesAnnotations($class),
            $this->methodsAnnotations($class)
        );
    }

public function classMembersAnnotations ( string $ class ) : array { $ index = static :: CLASS_MEMBERS_CACHE . $ class ; if ( isset ( self :: $ annotations [ $ index ] ) ) { return self :: $ annotations [ $ index ] ; } return self :: $ annotations [ $ index ] = array_merge ( $ this -> propertiesAnnotations ( $ class ) , $ this -> methodsAnnotations ( $ class ) ) ; }

Get a class's members' annotations.

@param string $class The class

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function classAndMembersAnnotations(string $class): array
    {
        $index = static::CLASS_AND_MEMBERS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        return self::$annotations[$index] = array_merge(
            $this->classAnnotations($class),
            $this->classMembersAnnotations($class)
        );
    }

public function classAndMembersAnnotations ( string $ class ) : array { $ index = static :: CLASS_AND_MEMBERS_CACHE . $ class ; if ( isset ( self :: $ annotations [ $ index ] ) ) { return self :: $ annotations [ $ index ] ; } return self :: $ annotations [ $ index ] = array_merge ( $ this -> classAnnotations ( $ class ) , $ this -> classMembersAnnotations ( $ class ) ) ; }

Get a class's and class's members' annotations.

@param string $class The class

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]

Get a class s and class s members annotations .


public function propertyAnnotations(string $class, string $property): array
    {
        $index = static::PROPERTY_CACHE . $class . $property;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class'    => $class,
                    'property' => $property,
                ],
                ...$this->parser->getAnnotations(
                $this->getPropertyReflection($class, $property)->getDocComment()
            )
            );
    }

public function propertyAnnotations ( string $ class , string $ property ) : array { $ index = static :: PROPERTY_CACHE . $ class . $ property ; return self :: $ annotations [ $ index ] ?? self :: $ annotations [ $ index ] = $ this -> setAnnotationValues ( [ 'class' => $ class , 'property' => $ property , ] , ... $ this -> parser -> getAnnotations ( $ this -> getPropertyReflection ( $ class , $ property ) -> getDocComment ( ) ) ) ; }

Get a property's annotations.

@param string $class    The class
@param string $property The property

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function propertyAnnotationsType(string $type, string $class, string $property): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->propertyAnnotations(
            $class,
            $property
        )
        );
    }

public function propertyAnnotationsType ( string $ type , string $ class , string $ property ) : array { return $ this -> filterAnnotationsByType ( $ type , ... $ this -> propertyAnnotations ( $ class , $ property ) ) ; }

Get a property's annotations by type.

@param string $type     The type
@param string $class    The class
@param string $property The property

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function propertiesAnnotations(string $class): array
    {
        $index = static::PROPERTIES_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        $annotations = [];
        // Get the class's reflection
        $reflection = $this->getClassReflection($class);

        // Iterate through the properties
        foreach ($reflection->getProperties() as $property) {
            $index = static::METHOD_CACHE . $class . $property->getName();
            // Set the property's reflection class in the cache
            self::$reflections[$index] = $property;

            // Iterate through all the property's annotations
            foreach ($this->propertyAnnotations(
                $class,
                $property->getName()
            ) as $propertyAnnotation) {
                // Set the annotation in the list
                $annotations[] = $propertyAnnotation;
            }
        }

        self::$annotations[$index] = $annotations;

        return $annotations;
    }

Get a class's properties' annotations.

@param string $class The class

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function methodAnnotations(string $class, string $method): array
    {
        $index      = static::METHOD_CACHE . $class . $method;
        $reflection = $this->getMethodReflection($class, $method);

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'class'  => $class,
                    'method' => $method,
                ],
                ...$this->getReflectionFunctionAnnotations(
                $reflection
            )
            );
    }

public function methodAnnotations ( string $ class , string $ method ) : array { $ index = static :: METHOD_CACHE . $ class . $ method ; $ reflection = $ this -> getMethodReflection ( $ class , $ method ) ; return self :: $ annotations [ $ index ] ?? self :: $ annotations [ $ index ] = $ this -> setAnnotationValues ( [ 'class' => $ class , 'method' => $ method , ] , ... $ this -> getReflectionFunctionAnnotations ( $ reflection ) ) ; }

Get a method's annotations.

@param string $class  The class
@param string $method The method

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function methodAnnotationsType(string $type, string $class, string $method): array
    {
        return $this->filterAnnotationsByType(
            $type,
            ...$this->methodAnnotations(
            $class,
            $method
        )
        );
    }

public function methodAnnotationsType ( string $ type , string $ class , string $ method ) : array { return $ this -> filterAnnotationsByType ( $ type , ... $ this -> methodAnnotations ( $ class , $ method ) ) ; }

Get a method's annotations by type.

@param string $type   The type
@param string $class  The class
@param string $method The method

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function methodsAnnotations(string $class): array
    {
        $index = static::METHODS_CACHE . $class;

        if (isset(self::$annotations[$index])) {
            return self::$annotations[$index];
        }

        $annotations = [];
        // Get the class's reflection
        $reflection = $this->getClassReflection($class);

        // Iterate through the methods
        foreach ($reflection->getMethods() as $method) {
            $index = static::METHOD_CACHE . $class . $method->getName();
            // Set the method's reflection class in the cache
            self::$reflections[$index] = $method;

            // Iterate through all the method's annotations
            foreach ($this->methodAnnotations(
                $class,
                $method->getName()
            ) as $methodAnnotation) {
                // Set the annotation in the list
                $annotations[] = $methodAnnotation;
            }
        }

        self::$annotations[$index] = $annotations;

        return $annotations;
    }

Get a class's methods' annotations.

@param string $class The class

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function functionAnnotations(string $function): array
    {
        $index = static::FUNCTION_CACHE . $function;

        return self::$annotations[$index]
            ?? self::$annotations[$index] = $this->setAnnotationValues(
                [
                    'function' => $function,
                ],
                ...$this->getReflectionFunctionAnnotations(
                $this->getFunctionReflection($function)
            )
            );
    }

public function functionAnnotations ( string $ function ) : array { $ index = static :: FUNCTION_CACHE . $ function ; return self :: $ annotations [ $ index ] ?? self :: $ annotations [ $ index ] = $ this -> setAnnotationValues ( [ 'function' => $ function , ] , ... $ this -> getReflectionFunctionAnnotations ( $ this -> getFunctionReflection ( $ function ) ) ) ; }

Get a function's annotations.

@param string $function The function

@throws \ReflectionException

@return \Valkyrja\Annotations\Annotation[]


public function filterAnnotationsByType(string $type, Annotation ...$annotations): array
    {
        // Set a list of annotations to return
        $annotationsList = [];

        // Iterate through the annotation
        foreach ($annotations as $annotation) {
            // If the annotation's type matches the type requested
            if ($annotation->getAnnotationType() === $type) {
                // Set the annotation in the list
                $annotationsList[] = $annotation;
            }
        }

        return $annotationsList;
    }

Filter annotations by type.

@param string       $type           The type to match
@param Annotation[] ...$annotations The annotations

@return array


protected function setAnnotationValues(array $properties, Annotation ...$annotations): array
    {
        foreach ($annotations as $annotation) {
            $annotation->setClass($properties['class'] ?? null);
            $annotation->setProperty($properties['property'] ?? null);
            $annotation->setMethod($properties['method'] ?? null);
            $annotation->setFunction($properties['function'] ?? null);
        }

        return $annotations;
    }

protected function setAnnotationValues ( array $ properties , Annotation ... $ annotations ) : array { foreach ( $ annotations as $ annotation ) { $ annotation -> setClass ( $ properties [ 'class' ] ?? null ) ; $ annotation -> setProperty ( $ properties [ 'property' ] ?? null ) ; $ annotation -> setMethod ( $ properties [ 'method' ] ?? null ) ; $ annotation -> setFunction ( $ properties [ 'function' ] ?? null ) ; } return $ annotations ; }

Set the base annotation model values.

@param array        $properties  The properties
@param Annotation[] $annotations The annotations

@return \Valkyrja\Annotations\Annotation[]


public function getClassReflection(string $class): ReflectionClass
    {
        $index = static::CLASS_CACHE . $class;

        return self::$reflections[$index]
            ?? self::$reflections[$index] = new ReflectionClass($class);
    }

public function getClassReflection ( string $ class ) : ReflectionClass { $ index = static :: CLASS_CACHE . $ class ; return self :: $ reflections [ $ index ] ?? self :: $ reflections [ $ index ] = new ReflectionClass ( $ class ) ; }

Get a class's reflection.

@param string $class The class

@throws \ReflectionException

@return \ReflectionClass


public function getPropertyReflection(string $class, string $property): ReflectionProperty
    {
        $index = static::PROPERTY_CACHE . $class . $property;

        return self::$reflections[$index]
            ?? self::$reflections[$index] =
                new ReflectionProperty($class, $property);
    }

public function getPropertyReflection ( string $ class , string $ property ) : ReflectionProperty { $ index = static :: PROPERTY_CACHE . $ class . $ property ; return self :: $ reflections [ $ index ] ?? self :: $ reflections [ $ index ] = new ReflectionProperty ( $ class , $ property ) ; }

Get a property's reflection.

@param string $class    The class
@param string $property The property

@throws \ReflectionException

@return \ReflectionProperty


public function getMethodReflection(string $class, string $method): ReflectionMethod
    {
        $index = static::METHOD_CACHE . $class . $method;

        return self::$reflections[$index]
            ?? self::$reflections[$index] =
                new ReflectionMethod($class, $method);
    }

public function getMethodReflection ( string $ class , string $ method ) : ReflectionMethod { $ index = static :: METHOD_CACHE . $ class . $ method ; return self :: $ reflections [ $ index ] ?? self :: $ reflections [ $ index ] = new ReflectionMethod ( $ class , $ method ) ; }

Get a method's reflection.

@param string $class  The class
@param string $method The method

@throws \ReflectionException

@return \ReflectionMethod


public function getFunctionReflection(string $function): ReflectionFunction
    {
        $index = static::FUNCTION_CACHE . $function;

        return self::$reflections[$index]
            ?? self::$reflections[$index] = new ReflectionFunction($function);
    }

public function getFunctionReflection ( string $ function ) : ReflectionFunction { $ index = static :: FUNCTION_CACHE . $ function ; return self :: $ reflections [ $ index ] ?? self :: $ reflections [ $ index ] = new ReflectionFunction ( $ function ) ; }

get a function's reflection.

@param string $function The function

@throws \ReflectionException

@return \ReflectionFunction


protected function getDependencies(ReflectionParameter ...$parameters): array
    {
        // Setup to find any injectable objects through the service container
        $dependencies = [];

        // Iterate through the method's parameters
        foreach ($parameters as $parameter) {
            // We only care for classes
            if ($parameter->getClass()) {
                // Set the injectable in the array
                $dependencies[] = $parameter->getClass()->getName();
            }
        }

        return $dependencies;
    }

Get dependencies from parameters.

@param \ReflectionParameter[] $parameters The parameters

@return string[]


public function getLength()
    {
        return sqrt(
            pow(($this->getPointB()->getAbscissa() - $this->getPointA()->getAbscissa()), 2)
            +
            pow(($this->getPointB()->getOrdinate() - $this->getPointA()->getOrdinate()), 2)
        );
    }

public function getLength ( ) { return sqrt ( pow ( ( $ this -> getPointB ( ) -> getAbscissa ( ) - $ this -> getPointA ( ) -> getAbscissa ( ) ) , 2 ) + pow ( ( $ this -> getPointB ( ) -> getOrdinate ( ) - $ this -> getPointA ( ) -> getOrdinate ( ) ) , 2 ) ) ; }

Get the length of the segment

@return  float


public function getCenter()
    {
        $abscissas = array(
            $this->getPointA()->getAbscissa(), $this->getPointB()->getAbscissa()
        );
        $ordinates = array(
            $this->getPointA()->getOrdinate(), $this->getPointB()->getOrdinate()
        );
        return new Point(
            ((max($abscissas) - min($abscissas)) / 2),
            ((max($ordinates) - min($ordinates)) / 2)
        );
    }

public function getCenter ( ) { $ abscissas = array ( $ this -> getPointA ( ) -> getAbscissa ( ) , $ this -> getPointB ( ) -> getAbscissa ( ) ) ; $ ordinates = array ( $ this -> getPointA ( ) -> getOrdinate ( ) , $ this -> getPointB ( ) -> getOrdinate ( ) ) ; return new Point ( ( ( max ( $ abscissas ) - min ( $ abscissas ) ) / 2 ) , ( ( max ( $ ordinates ) - min ( $ ordinates ) ) / 2 ) ) ; }

Get the middle of the segment as a `\Maths\Geometry\Point` object

@return  \Maths\Geometry\Point

Get the middle of the segment as a \ Maths \ Geometry \ Point object


public function run()
    {
        if (!empty($this->_fields)) {
            throw new InvalidCallException('Each beginField() should have a matching endField() call.');
        }

        $content = ob_get_clean();
        echo $this->htmlHlp->beginForm($this->action, $this->method, $this->options);
        echo $content;

        if ($this->enableClientScript) {
            $this->registerClientScript();
        }

        echo $this->htmlHlp->endForm();
    }

Runs the widget.
This registers the necessary JavaScript code and renders the form open and close tags.
@throws InvalidCallException if `beginField()` and `endField()` calls are not matching.

Runs the widget . This registers the necessary JavaScript code and renders the form open and close tags .


public function field($model, $attribute, $options = [])
    {
        $config = $this->fieldConfig;
        if ($config instanceof \Closure) {
            $config = call_user_func($config, $model, $attribute);
        }
        if (!isset($config['class'])) {
            $config['class'] = $this->fieldClass;
        }

        return Reaction::create(ArrayHelper::merge($config, $options, [
            'model' => $model,
            'attribute' => $attribute,
            'form' => $this,
        ]));
    }

public function field ( $ model , $ attribute , $ options = [ ] ) { $ config = $ this -> fieldConfig ; if ( $ config instanceof \ Closure ) { $ config = call_user_func ( $ config , $ model , $ attribute ) ; } if ( ! isset ( $ config [ 'class' ] ) ) { $ config [ 'class' ] = $ this -> fieldClass ; } return Reaction :: create ( ArrayHelper :: merge ( $ config , $ options , [ 'model' => $ model , 'attribute' => $ attribute , 'form' => $ this , ] ) ) ; }

Generates a form field.
A form field is associated with a model and an attribute. It contains a label, an input and an error message
and use them to interact with end users to collect their inputs for the attribute.
@param Model $model the data model.
@param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
about attribute expression.
@param array $options the additional configurations for the field object. These are properties of [[ActiveField]]
or a subclass, depending on the value of [[fieldClass]].
@return ActiveField the created ActiveField object.
@see fieldConfig

Generates a form field . A form field is associated with a model and an attribute . It contains a label an input and an error message and use them to interact with end users to collect their inputs for the attribute .


public function has($key)
    {
        if (strpos($key, '.') === false) {
            return $this->hasByKey($key);
        }

        return $this->hasByPath($key);
    }

public function has ( $ key ) { if ( strpos ( $ key , '.' ) === false ) { return $ this -> hasByKey ( $ key ) ; } return $ this -> hasByPath ( $ key ) ; }

Determine if the given configuration value exists.

@param  string $key
@return bool

Determine if the given configuration value exists .


public function getDisplayDirname()
    {
        $_dirname = $this->dirname;
        if (empty($_dirname)) $_dirname = basename($this->getPath());
        return ucwords( str_replace( '_', ' ', $_dirname ) );
    }

public
function
getDisplayDirname
(
)
{
$
_dirname
=
$
this
->
dirname
;
if
(
empty
(
$
_dirname
)
)
$
_dirname
=
basename
(
$
this
->
getPath
(
)
)
;
return
ucwords
(
str_replace
(
'_'
,
' '
,
$
_dirname
)
)
;
}

Gets the directory name transformed to be displayed as a title

@return string The directory name transformed


public function scanDir($recursive = false)
    {
        if (!$this->exists()) return false;
        $_dir = opendir($this->getPath().$this->dirname);
        $data = array();
        while ($entry = @readdir($_dir)) {
            if (!in_array($entry, $this->ignore)) {
                if (is_dir($this->getPath().$this->dirname.'/'.$entry)) {
                    if (true === $recursive){
                        $_new_dir = new DirectoryModel;
                        $_new_dir->setPath( $this->getPath().$this->dirname );
                        $_new_dir->setDirname( $entry );
                        $data[] = $_new_dir->scanDir( $recursive );
                    } else {
                        $data[] = $entry;
                    }
                } else {
                    $data[] = $entry;
                }
            }
        }
        closedir($_dir);
        return $data;
    }

public function scanDir ( $ recursive = false ) { if ( ! $ this -> exists ( ) ) return false ; $ _dir = opendir ( $ this -> getPath ( ) . $ this -> dirname ) ; $ data = array ( ) ; while ( $ entry = @ readdir ( $ _dir ) ) { if ( ! in_array ( $ entry , $ this -> ignore ) ) { if ( is_dir ( $ this -> getPath ( ) . $ this -> dirname . '/' . $ entry ) ) { if ( true === $ recursive ) { $ _new_dir = new DirectoryModel ; $ _new_dir -> setPath ( $ this -> getPath ( ) . $ this -> dirname ) ; $ _new_dir -> setDirname ( $ entry ) ; $ data [ ] = $ _new_dir -> scanDir ( $ recursive ) ; } else { $ data [ ] = $ entry ; } } else { $ data [ ] = $ entry ; } } } closedir ( $ _dir ) ; return $ data ; }

Scan the current directory

@param bool $recursive Is the scan recursive ?
@return array


final public static function header($string, $replace = true, $http_response_code = null)
    {
        if ( !$headers = http\Header::parse($string) ) Returns;
        $header = key($headers);

        if ( $replace || !isset(self::$list[$header]) ) {
            self::$list[$header] = array();
        }

        self::$list[$header][] = $string;

        if ( strtolower($header) == 'location' ) $http_response_code = 302;
        if ( $http_response_code ) self::$code = $http_response_code;
    }

final public static function header ( $ string , $ replace = true , $ http_response_code = null ) { if ( ! $ headers = http \ Header :: parse ( $ string ) ) Returns ; $ header = key ( $ headers ) ; if ( $ replace || ! isset ( self :: $ list [ $ header ] ) ) { self :: $ list [ $ header ] = array ( ) ; } self :: $ list [ $ header ] [ ] = $ string ; if ( strtolower ( $ header ) == 'location' ) $ http_response_code = 302 ; if ( $ http_response_code ) self :: $ code = $ http_response_code ; }

Send a raw HTTP header.

@link http://www.php.net/manual/en/function.header.php

@param  string  $string             The header string.
@param  boolean $replace            (optional) The optional replace parameter indicates whether the header should replace a previous similar header, or add a second header of the same type.
@param  boolean $http_response_code (optional) Forces the HTTP response code to the specified value.
@return boolean


final public static function headers_list()
    {
        $results = array();
        foreach (self::$list as $headers) {
            $results = array_merge($results, $headers);
        }

        return $results;
    }

final public static function headers_list ( ) { $ results = array ( ) ; foreach ( self :: $ list as $ headers ) { $ results = array_merge ( $ results , $ headers ) ; } return $ results ; }

Returns a list of response headers ready to send

@link http://www.php.net/manual/en/function.headers_list.php

@return array Returns a numerically indexed array of headers.


public function createDB($DBName, $charset = 'utf8', $collation = 'utf8_unicode_ci') {
        QC::executeSQL($this->generateDBSQL($DBName, $charset, $collation));
        return $this;
    }

public function createDB ( $ DBName , $ charset = 'utf8' , $ collation = 'utf8_unicode_ci' ) { QC :: executeSQL ( $ this -> generateDBSQL ( $ DBName , $ charset , $ collation ) ) ; return $ this ; }

Using for creating database
@param string $DBName
@param string $charset
@param string $collation
@return $this


public function getDBTables($force_fetch = false) {
        if ($this->_tables && !$force_fetch) return $this->_tables;

        $res = QC::executeSQL('SHOW TABLES');
        $this->_tables = array();
        if ($res->rowCount()) {
            $res = $res->fetchAll(\PDO::FETCH_NUM);
            foreach($res as $info) {
                $this->_tables[$info[0]] = array('name'=>$info[0]);
            }
        }
        return $this->_tables;
    }

public
function
getDBTables
(
$
force_fetch
=
false
)
{
if
(
$
this
->
_tables
&&
!
$
force_fetch
)
return
$
this
->
_tables
;
$
res
=
QC
::
executeSQL
(
'SHOW TABLES'
)
;
$
this
->
_tables
=
array
(
)
;
if
(
$
res
->
rowCount
(
)
)
{
$
res
=
$
res
->
fetchAll
(
\
PDO
::
FETCH_NUM
)
;
foreach
(
$
res
as
$
info
)
{
$
this
->
_tables
[
$
info
[
0
]
]
=
array
(
'name'
=>
$
info
[
0
]
)
;
}
}
return
$
this
->
_tables
;
}

Return list of tables from connected database
@param bool $force_fetch reload tables list
@return array|null


public function updateDBFromStructure($structure, $safeUpdate = true) {
        $diffs = $this->getDifferenceSQL($structure);
        if ($diffs['result'] === true) {
            QC::executeSQL('SET FOREIGN_KEY_CHECKS = 0');
            if (!empty($diffs['sql']['ADD'])) QC::executeArrayOfSQL($diffs['sql']['ADD']);
            if (!empty($diffs['sql']['CHANGE'])) QC::executeArrayOfSQL($diffs['sql']['CHANGE']);
            if (!empty($diffs['sql']['DROP']) && !$safeUpdate) QC::executeArrayOfSQL($diffs['sql']['DROP']);
        }
    }

public
function
updateDBFromStructure
(
$
structure
,
$
safeUpdate
=
true
)
{
$
diffs
=
$
this
->
getDifferenceSQL
(
$
structure
)
;
if
(
$
diffs
[
'result'
]
===
true
)
{
QC
::
executeSQL
(
'SET FOREIGN_KEY_CHECKS = 0'
)
;
if
(
!
empty
(
$
diffs
[
'sql'
]
[
'ADD'
]
)
)
QC
::
executeArrayOfSQL
(
$
diffs
[
'sql'
]
[
'ADD'
]
)
;
if
(
!
empty
(
$
diffs
[
'sql'
]
[
'CHANGE'
]
)
)
QC
::
executeArrayOfSQL
(
$
diffs
[
'sql'
]
[
'CHANGE'
]
)
;
if
(
!
empty
(
$
diffs
[
'sql'
]
[
'DROP'
]
)
&&
!
$
safeUpdate
)
QC
::
executeArrayOfSQL
(
$
diffs
[
'sql'
]
[
'DROP'
]
)
;
}
}

Update database from array
@param mixed|ModelStructure $structure
@param bool $safeUpdate if true - method will delete not specified fields
@throws \Exception


public function updateDBRelations($modelName, $structure) {
        if (empty($structure['relations'])) return true;

        foreach($structure['relations'] as $relationName => $relationInfo) {
            $info = ModelOperator::calculateRelationVariables($modelName, $relationName);
            switch($info['relationType']) {
                case 'many_to_many':
                    $this->updateManyTable($info);
                    break;
                case 'many_to_one':
                    break;
                case 'one_to_many':
                    break;
            }
        }
    }

public function updateDBRelations ( $ modelName , $ structure ) { if ( empty ( $ structure [ 'relations' ] ) ) return true ; foreach ( $ structure [ 'relations' ] as $ relationName => $ relationInfo ) { $ info = ModelOperator :: calculateRelationVariables ( $ modelName , $ relationName ) ; switch ( $ info [ 'relationType' ] ) { case 'many_to_many' : $ this -> updateManyTable ( $ info ) ; break ; case 'many_to_one' : break ; case 'one_to_many' : break ; } } }

Updates relations in database
@param string $modelName
@param mixed $structure
@throws \Exception


public function updateManyTable($info) {
        $structure = array(
            'table'     => $info['manyTable'],
            'columns'   => array(),
            'indexes'   => array(),
            'constraints'   => array(),
        );

        $localName = Inflector::singularize($info['localTable']);
        $foreignName = Inflector::singularize($info['foreignTable']);

        $structure['columns']['id'] = array('type' => 'int(11) unsigned', 'auto_increment'=>true);
        $structure['columns']['id_'. $localName] = 'int(11) unsigned';
        $structure['columns']['id_'. $foreignName] = 'int(11) unsigned';
        $structure['indexes']['primary'] = array('columns'=>array('id'), 'type'=>'primary');
        $structure['indexes']['unique_id_'.$localName.'_id_'.$foreignName] = array(
            'columns'   => array(
                'id_'.$localName,
                'id_'.$foreignName
            ),
            'type'      => 'unique'
        );
        $foreignKeysInfo = array(
            'local_table'   => $info['manyTable'],
            'foreign_table' => $info['localTable'],
            'local_field'   => 'id_'.$localName,
            'foreign_field' => $info['foreignKey']
        );
        $structure['constraints'][$this->generateForeignKeyName($foreignKeysInfo)] = $foreignKeysInfo;
        $foreignKeysInfo = array(
            'local_table'   => $info['manyTable'],
            'foreign_table' => $info['foreignTable'],
            'local_field'   => 'id_'.$foreignName,
            'foreign_field' => $info['foreignKey']
        );
        $structure['constraints'][$this->generateForeignKeyName($foreignKeysInfo)] = $foreignKeysInfo;

        $diffs = $this->getDifferenceSQL($structure, $info['manyTable']);
        if ($diffs['result'] === true) {
            QC::executeSQL('SET FOREIGN_KEY_CHECKS = 0');
            if (!empty($diffs['sql']['ADD'])) {
                try {
                    QC::executeArrayOfSQL($diffs['sql']['ADD']);
                } catch(\Exception $e) {
                    var_dump($e->getMessage());die();
                }
            }
        }
        return $diffs['result'];

    }

public
function
updateManyTable
(
$
info
)
{
$
structure
=
array
(
'table'
=>
$
info
[
'manyTable'
]
,
'columns'
=>
array
(
)
,
'indexes'
=>
array
(
)
,
'constraints'
=>
array
(
)
,
)
;
$
localName
=
Inflector
::
singularize
(
$
info
[
'localTable'
]
)
;
$
foreignName
=
Inflector
::
singularize
(
$
info
[
'foreignTable'
]
)
;
$
structure
[
'columns'
]
[
'id'
]
=
array
(
'type'
=>
'int(11) unsigned'
,
'auto_increment'
=>
true
)
;
$
structure
[
'columns'
]
[
'id_'
.
$
localName
]
=
'int(11) unsigned'
;
$
structure
[
'columns'
]
[
'id_'
.
$
foreignName
]
=
'int(11) unsigned'
;
$
structure
[
'indexes'
]
[
'primary'
]
=
array
(
'columns'
=>
array
(
'id'
)
,
'type'
=>
'primary'
)
;
$
structure
[
'indexes'
]
[
'unique_id_'
.
$
localName
.
'_id_'
.
$
foreignName
]
=
array
(
'columns'
=>
array
(
'id_'
.
$
localName
,
'id_'
.
$
foreignName
)
,
'type'
=>
'unique'
)
;
$
foreignKeysInfo
=
array
(
'local_table'
=>
$
info
[
'manyTable'
]
,
'foreign_table'
=>
$
info
[
'localTable'
]
,
'local_field'
=>
'id_'
.
$
localName
,
'foreign_field'
=>
$
info
[
'foreignKey'
]
)
;
$
structure
[
'constraints'
]
[
$
this
->
generateForeignKeyName
(
$
foreignKeysInfo
)
]
=
$
foreignKeysInfo
;
$
foreignKeysInfo
=
array
(
'local_table'
=>
$
info
[
'manyTable'
]
,
'foreign_table'
=>
$
info
[
'foreignTable'
]
,
'local_field'
=>
'id_'
.
$
foreignName
,
'foreign_field'
=>
$
info
[
'foreignKey'
]
)
;
$
structure
[
'constraints'
]
[
$
this
->
generateForeignKeyName
(
$
foreignKeysInfo
)
]
=
$
foreignKeysInfo
;
$
diffs
=
$
this
->
getDifferenceSQL
(
$
structure
,
$
info
[
'manyTable'
]
)
;
if
(
$
diffs
[
'result'
]
===
true
)
{
QC
::
executeSQL
(
'SET FOREIGN_KEY_CHECKS = 0'
)
;
if
(
!
empty
(
$
diffs
[
'sql'
]
[
'ADD'
]
)
)
{
try
{
QC
::
executeArrayOfSQL
(
$
diffs
[
'sql'
]
[
'ADD'
]
)
;
}
catch
(
\
Exception
$
e
)
{
var_dump
(
$
e
->
getMessage
(
)
)
;
die
(
)
;
}
}
}
return
$
diffs
[
'result'
]
;
}

Updates many to many tables
@param $info
@return mixed


public function generateTableSQL($structure) {
        $sql = 'CREATE TABLE' . ' IF NOT EXISTS `' . $structure['table'].'` (' . "\n";

        foreach($structure['columns'] as $column=>$info) {
            if (!is_array($info)) $info = array('type'=>$info);
            if (!isset($info['name'])) $info['name'] = $column;
            if (!empty($info['virtual'])) continue;
            $sql .= $this->generateColumnSQL($info).','."\n";
        }
        if (!empty($structure['indexes'])) {
            foreach($structure['indexes'] as $name=>$info) {
                if (!isset($info['name'])) $info['name'] = $name;
                $sql .= $this->generateIndexSQL($info).','."\n";
            }
        }
        if (!empty($structure['constraints'])) {
            foreach($structure['constraints'] as $info) {
                $info['local_table'] = $structure['table'];
                $sql .= $this->generateConstraintSQL($info).','."\n";
            }
        }
        $sql = substr($sql, 0, -2).')';
        $sql .= ' ENGINE = '.(empty($info['engine']) ? 'INNODB' : $info['engine']).'  CHARACTER SET='.(empty($info['charset']) ? 'utf8' : $info['charset']).' COLLATE='.(empty($info['collate']) ? 'utf8_unicode_ci' : $info['collate']);

        return $sql;
    }

public
function
generateTableSQL
(
$
structure
)
{
$
sql
=
'CREATE TABLE'
.
' IF NOT EXISTS `'
.
$
structure
[
'table'
]
.
'` ('
.
"\n"
;
foreach
(
$
structure
[
'columns'
]
as
$
column
=>
$
info
)
{
if
(
!
is_array
(
$
info
)
)
$
info
=
array
(
'type'
=>
$
info
)
;
if
(
!
isset
(
$
info
[
'name'
]
)
)
$
info
[
'name'
]
=
$
column
;
if
(
!
empty
(
$
info
[
'virtual'
]
)
)
continue
;
$
sql
.=
$
this
->
generateColumnSQL
(
$
info
)
.
','
.
"\n"
;
}
if
(
!
empty
(
$
structure
[
'indexes'
]
)
)
{
foreach
(
$
structure
[
'indexes'
]
as
$
name
=>
$
info
)
{
if
(
!
isset
(
$
info
[
'name'
]
)
)
$
info
[
'name'
]
=
$
name
;
$
sql
.=
$
this
->
generateIndexSQL
(
$
info
)
.
','
.
"\n"
;
}
}
if
(
!
empty
(
$
structure
[
'constraints'
]
)
)
{
foreach
(
$
structure
[
'constraints'
]
as
$
info
)
{
$
info
[
'local_table'
]
=
$
structure
[
'table'
]
;
$
sql
.=
$
this
->
generateConstraintSQL
(
$
info
)
.
','
.
"\n"
;
}
}
$
sql
=
substr
(
$
sql
,
0
,
2
)
.
')'
;
$
sql
.=
' ENGINE = '
.
(
empty
(
$
info
[
'engine'
]
)
'INNODB'
:
$
info
[
'engine'
]
)
.
'  CHARACTER SET='
.
(
empty
(
$
info
[
'charset'
]
)
'utf8'
:
$
info
[
'charset'
]
)
.
' COLLATE='
.
(
empty
(
$
info
[
'collate'
]
)
'utf8_unicode_ci'
:
$
info
[
'collate'
]
)
;
return
$
sql
;
}

Generate whole SQL definition for table

@param array $structure
@return string


private function generateColumnSQL($info) {
        $sql = '';
        if (isset($info['old_name'])) {
            $sql = '`'.$info['old_name'].'` ';
        }
        $sql .= '`'.$info['name'].'` '.$this->getSQLTypeForField($info);
        if (isset($info['unsigned'])) $sql .= ' unsigned';
        if (isset($info['zerofill'])) $sql .= ' zerofill';
        if (isset($info['auto_increment'])) {
            $sql .= ' NOT NULL auto_increment';
        } elseif (isset($info['default']) && (strpos($info['default'], '#sql#') === false)) {
            $sql .= ' DEFAULT \''.$info['default']."'";
        } elseif (isset($info['not_null'])) {
            $sql .= ' NOT NULL';
        }
        //var_dump($sql);die();
        return $sql;
    }

private
function
generateColumnSQL
(
$
info
)
{
$
sql
=
''
;
if
(
isset
(
$
info
[
'old_name'
]
)
)
{
$
sql
=
'`'
.
$
info
[
'old_name'
]
.
'` '
;
}
$
sql
.=
'`'
.
$
info
[
'name'
]
.
'` '
.
$
this
->
getSQLTypeForField
(
$
info
)
;
if
(
isset
(
$
info
[
'unsigned'
]
)
)
$
sql
.=
' unsigned'
;
if
(
isset
(
$
info
[
'zerofill'
]
)
)
$
sql
.=
' zerofill'
;
if
(
isset
(
$
info
[
'auto_increment'
]
)
)
{
$
sql
.=
' NOT NULL auto_increment'
;
}
elseif
(
isset
(
$
info
[
'default'
]
)
&&
(
strpos
(
$
info
[
'default'
]
,
'#sql#'
)
===
false
)
)
{
$
sql
.=
' DEFAULT \''
.
$
info
[
'default'
]
.
"'"
;
}
elseif
(
isset
(
$
info
[
'not_null'
]
)
)
{
$
sql
.=
' NOT NULL'
;
}
//var_dump($sql);die();
return
$
sql
;
}

Generate part of SQL definition for column

@access private
@param array $info
@return string SQL


private function generateIndexSQL($info) {
        $keys = $info['columns'];
        $sql = '';
        if (!isset($info['type'])) $info['type'] = ($info['name'] == 'primary' ? 'primary' : 'simple');
        switch ($info['type']) {
            case 'primary':
                $sql .= 'PRIMARY KEY (`'.(is_array($keys) ? implode('`, `', $keys) : $keys).'`)';
                break;
            case 'unique':
            case 'simple':
                $sql .= ($info['type'] == 'unique' ? 'UNIQUE ' : '').'KEY '.'`'.$info['name'].'` (`'.(is_array($keys) ? implode('`, `', $keys) : $keys).'`)';
                break;
        }
        return $sql;
    }

private
function
generateIndexSQL
(
$
info
)
{
$
keys
=
$
info
[
'columns'
]
;
$
sql
=
''
;
if
(
!
isset
(
$
info
[
'type'
]
)
)
$
info
[
'type'
]
=
(
$
info
[
'name'
]
==
'primary'
'primary'
:
'simple'
)
;
switch
(
$
info
[
'type'
]
)
{
case
'primary'
:
$
sql
.=
'PRIMARY KEY (`'
.
(
is_array
(
$
keys
)
implode
(
'`, `'
,
$
keys
)
:
$
keys
)
.
'`)'
;
break
;
case
'unique'
:
case
'simple'
:
$
sql
.=
(
$
info
[
'type'
]
==
'unique'
'UNIQUE '
:
''
)
.
'KEY '
.
'`'
.
$
info
[
'name'
]
.
'` (`'
.
(
is_array
(
$
keys
)
implode
(
'`, `'
,
$
keys
)
:
$
keys
)
.
'`)'
;
break
;
}
return
$
sql
;
}

Generate part of SQL definition for Indexes

@access private
@param array $info
@return string


private function generateConstraintSQL($info) {
        $name = isset($info['name']) ? $info['name'] : $this->generateForeignKeyName($info);
        $sql = 'CONSTRAINT `'.$name.'` FOREIGN KEY (`'.$info['local_field'].'`) REFERENCES `'
            .$info['foreign_table'].'` (`'.$info['foreign_field'].'`) '.
            'ON DELETE '.(empty($info['on_delete']) ? 'SET NULL' : $info['on_delete']).' ON UPDATE '.(empty($info['on_update']) ? 'CASCADE' : $info['on_update']);
        return $sql;
    }

private
function
generateConstraintSQL
(
$
info
)
{
$
name
=
isset
(
$
info
[
'name'
]
)
$
info
[
'name'
]
:
$
this
->
generateForeignKeyName
(
$
info
)
;
$
sql
=
'CONSTRAINT `'
.
$
name
.
'` FOREIGN KEY (`'
.
$
info
[
'local_field'
]
.
'`) REFERENCES `'
.
$
info
[
'foreign_table'
]
.
'` (`'
.
$
info
[
'foreign_field'
]
.
'`) '
.
'ON DELETE '
.
(
empty
(
$
info
[
'on_delete'
]
)
'SET NULL'
:
$
info
[
'on_delete'
]
)
.
' ON UPDATE '
.
(
empty
(
$
info
[
'on_update'
]
)
'CASCADE'
:
$
info
[
'on_update'
]
)
;
return
$
sql
;
}

Generate part of SQL definition for Constraints

@param array $info
@return string


public static function getKeyvaluesByKeyType($keyType)
    {
        if (empty($keyType)) {
            // return empty array
            return [];
        }

        $tableCache = static::tableToArray();

        // Read through the entire table cache looking for keys that match
        // the keyType
        $result = [];
        foreach ($tableCache as $key => $value) {
            list($storedType, $storedValue) = explode('__', $key, 2);
            if ($storedType == $keyType) {
                $result[$value->keyvalue] = $value;
            }
        }

        return $result;
    }

return the Keyvalues objects for a given keytype

Result array is formatted like this:

* keyvalue => fluent object(keyvalue, keyname, ...),
* ... etc

@param string $keyType
@return array of Fluent


public static function getKeyValuesByType($keyType)
    {
        $keyvalues = self::getKeyvaluesByKeyType($keyType);

        // Sort through the enums of the found type and reformat those
        // as a keyvalue => keyname list.
        $list = [];

        /** @var Keyvalue $keyvalue */
        foreach ($keyvalues as $keyvalue) {
            $list[$keyvalue->keyvalue] = $keyvalue->keyname;
        }

        return $list;
    }

return the keyvalue -> keyname pairs for all elements that match a keytype

Result array is formatted like this:

* keyvalue => keyname
* ... etc

@param string $keyType
@return array of string

return the keyvalue - > keyname pairs for all elements that match a keytype


public function getClass($class, $refresh = false)
    {
        $reflector = $this->getClassReflection($class);
        $cacheKey = $reflector->getName();
        if (!$refresh && $this->cacheExists($cacheKey)) {
            return $this->getFromCache($cacheKey);
        }
        /** @var array|null $annotations */
        $annotations = $this->reader->getClassAnnotations($reflector);
        $annotations = is_array($annotations) ? $annotations : [];
        $this->setToCache($cacheKey, $annotations);
        return $annotations;
    }

public
function
getClass
(
$
class
,
$
refresh
=
false
)
{
$
reflector
=
$
this
->
getClassReflection
(
$
class
)
;
$
cacheKey
=
$
reflector
->
getName
(
)
;
if
(
!
$
refresh
&&
$
this
->
cacheExists
(
$
cacheKey
)
)
{
return
$
this
->
getFromCache
(
$
cacheKey
)
;
}
/** @var array|null $annotations */
$
annotations
=
$
this
->
reader
->
getClassAnnotations
(
$
reflector
)
;
$
annotations
=
is_array
(
$
annotations
)
$
annotations
:
[
]
;
$
this
->
setToCache
(
$
cacheKey
,
$
annotations
)
;
return
$
annotations
;
}

Get all annotations for class
@param string|object $class
@param bool          $refresh
@return array


public function getClassExact($class, $annotationClass, $refresh = false)
    {
        $annotations = $this->getClass($class, $refresh);
        foreach ($annotations as $annotation) {
            if ($annotation instanceof $annotationClass) {
                return $annotation;
            }
        }
        return null;
    }

public function getClassExact ( $ class , $ annotationClass , $ refresh = false ) { $ annotations = $ this -> getClass ( $ class , $ refresh ) ; foreach ( $ annotations as $ annotation ) { if ( $ annotation instanceof $ annotationClass ) { return $ annotation ; } } return null ; }

Get class annotation by its class|interface name
@param string|object $class
@param string|object $annotationClass
@param bool          $refresh
@return object|null


public function getProperty($property, $class = null, $refresh = false)
    {
        $propertyReflection = $this->getPropertyReflection($property, $class);
        $classReflection = $propertyReflection->getDeclaringClass();
        $cacheKey = $classReflection->getName() . '$' . $propertyReflection->getName();
        if (!$refresh && $this->cacheExists($cacheKey)) {
            return $this->getFromCache($cacheKey);
        }
        /** @var array|null $annotations */
        $annotations = $this->reader->getPropertyAnnotations($propertyReflection);
        $annotations = is_array($annotations) ? $annotations : [];
        $this->setToCache($cacheKey, $annotations);
        return $annotations;
    }

public
function
getProperty
(
$
property
,
$
class
=
,
$
refresh
=
false
)
{
$
propertyReflection
=
$
this
->
getPropertyReflection
(
$
property
,
$
class
)
;
$
classReflection
=
$
propertyReflection
->
getDeclaringClass
(
)
;
$
cacheKey
=
$
classReflection
->
getName
(
)
.
'$'
.
$
propertyReflection
->
getName
(
)
;
if
(
!
$
refresh
&&
$
this
->
cacheExists
(
$
cacheKey
)
)
{
return
$
this
->
getFromCache
(
$
cacheKey
)
;
}
/** @var array|null $annotations */
$
annotations
=
$
this
->
reader
->
getPropertyAnnotations
(
$
propertyReflection
)
;
$
annotations
=
is_array
(
$
annotations
)
$
annotations
:
[
]
;
$
this
->
setToCache
(
$
cacheKey
,
$
annotations
)
;
return
$
annotations
;
}

Get all annotations for property
@param string|object $class
@param string        $property
@param bool          $refresh
@return array


public function getPropertyExact($property, $annotationClass, $class = null, $refresh = false)
    {
        $annotations = $this->getProperty($property, $class, $refresh);
        foreach ($annotations as $annotation) {
            if ($annotation instanceof $annotationClass) {
                return $annotation;
            }
        }
        return null;
    }

public function getPropertyExact ( $ property , $ annotationClass , $ class = null , $ refresh = false ) { $ annotations = $ this -> getProperty ( $ property , $ class , $ refresh ) ; foreach ( $ annotations as $ annotation ) { if ( $ annotation instanceof $ annotationClass ) { return $ annotation ; } } return null ; }

Get property annotation by its class|interface name
@param string|\ReflectionProperty        $property
@param string|object $annotationClass
@param string|object $class
@param bool          $refresh
@return object|null


public function getMethod($method, $class = null, $refresh = false)
    {
        $methodReflection = $this->getMethodReflection($method, $class);
        $classReflection = $methodReflection->getDeclaringClass();
        $cacheKey = $classReflection->getName() . '#' . $methodReflection->getName();
        if (!$refresh && $this->cacheExists($cacheKey)) {
            return $this->getFromCache($cacheKey);
        }
        /** @var array|null $annotations */
        $annotations = $this->reader->getMethodAnnotations($methodReflection);
        $annotations = is_array($annotations) ? $annotations : [];
        $this->setToCache($cacheKey, $annotations);
        return $annotations;
    }

public
function
getMethod
(
$
method
,
$
class
=
,
$
refresh
=
false
)
{
$
methodReflection
=
$
this
->
getMethodReflection
(
$
method
,
$
class
)
;
$
classReflection
=
$
methodReflection
->
getDeclaringClass
(
)
;
$
cacheKey
=
$
classReflection
->
getName
(
)
.
'#'
.
$
methodReflection
->
getName
(
)
;
if
(
!
$
refresh
&&
$
this
->
cacheExists
(
$
cacheKey
)
)
{
return
$
this
->
getFromCache
(
$
cacheKey
)
;
}
/** @var array|null $annotations */
$
annotations
=
$
this
->
reader
->
getMethodAnnotations
(
$
methodReflection
)
;
$
annotations
=
is_array
(
$
annotations
)
$
annotations
:
[
]
;
$
this
->
setToCache
(
$
cacheKey
,
$
annotations
)
;
return
$
annotations
;
}

Get all annotations for method
@param string|object|null       $class
@param string|\ReflectionMethod $method
@param bool                     $refresh
@return array


public function getMethodExact($method, $annotationClass, $class = null, $refresh = false)
    {
        $annotations = $this->getMethod($method, $class, $refresh);
        foreach ($annotations as $annotation) {
            if ($annotation instanceof $annotationClass) {
                return $annotation;
            }
        }
        return null;
    }

public function getMethodExact ( $ method , $ annotationClass , $ class = null , $ refresh = false ) { $ annotations = $ this -> getMethod ( $ method , $ class , $ refresh ) ; foreach ( $ annotations as $ annotation ) { if ( $ annotation instanceof $ annotationClass ) { return $ annotation ; } } return null ; }

Get method annotation by its class|interface name
@param string|\ReflectionMethod $method
@param string|object            $annotationClass
@param string|object|null       $class
@param bool                     $refresh
@return object|null


protected function getReader()
    {
        if (!isset($this->_reader)) {
            ClassFinderHelper::findClassesPsr4($this->annotationNamespaces);
            $this->_reader = new IndexedReader(new AnnotationReader());
        }
        return $this->_reader;
    }

protected function getReader ( ) { if ( ! isset ( $ this -> _reader ) ) { ClassFinderHelper :: findClassesPsr4 ( $ this -> annotationNamespaces ) ; $ this -> _reader = new IndexedReader ( new AnnotationReader ( ) ) ; } return $ this -> _reader ; }

Get doctrine annotation reader
@return mixed|object
@throws \Doctrine\Common\Annotations\AnnotationException


protected function getMethodReflection($method, $class = null)
    {
        if (is_object($method) && $method instanceof \ReflectionMethod) {
            return $method;
        }
        if ($class === null) {
            throw new InvalidArgumentException("Argument 'class' must be set");
        }
        return ReflectionHelper::getMethodReflection($class, $method);
    }

protected
function
getMethodReflection
(
$
method
,
$
class
=
)
{
if
(
is_object
(
$
method
)
&&
$
method
instanceof
\
ReflectionMethod
)
{
return
$
method
;
}
if
(
$
class
===
)
{
throw
new
InvalidArgumentException
(
"Argument 'class' must be set"
)
;
}
return
ReflectionHelper
::
getMethodReflection
(
$
class
,
$
method
)
;
}

Get method reflection
@param string|\ReflectionMethod $method
@param string|object|null       $class
@return \ReflectionMethod


protected function getFromCache($key)
    {
        return isset($this->_cache[$key]) ? $this->_cache[$key] : null;
    }

protected function getFromCache ( $ key ) { return isset ( $ this -> _cache [ $ key ] ) ? $ this -> _cache [ $ key ] : null ; }

Get data from cache
@param string $key
@return mixed


protected function setToCache($key, $value = null)
    {
        if (!isset($value)) {
            unset($this->_cache[$value]);
            return;
        }
        $this->_cache[$key] = $value;
    }

protected function setToCache ( $ key , $ value = null ) { if ( ! isset ( $ value ) ) { unset ( $ this -> _cache [ $ value ] ) ; return ; } $ this -> _cache [ $ key ] = $ value ; }

Set data to cache
@param string $key
@param mixed|null $value


private static function getPaths($key){
    	$paths = array();
    	$sourcePaths = explode(".", $key);
    	foreach ($sourcePaths as $sourcePath){
    		$subPaths = preg_split('/\[(.*?)\]/',$sourcePath,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
    		if($subPaths !== FALSE){
    			$paths = array_merge($paths,$subPaths);
    		}
    	}
    	return $paths;
    }

private static function getPaths ( $ key ) { $ paths = array ( ) ; $ sourcePaths = explode ( "." , $ key ) ; foreach ( $ sourcePaths as $ sourcePath ) { $ subPaths = preg_split ( '/\[(.*?)\]/' , $ sourcePath , - 1 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ) ; if ( $ subPaths !== FALSE ) { $ paths = array_merge ( $ paths , $ subPaths ) ; } } return $ paths ; }

this method get the path array from string key
@param string $key


protected function processKey($key) {
        if (is_string($key)) {
            return $key;
        } else {
            $keyStr = Json::encode($key);
            return md5($keyStr);
        }
    }

protected function processKey ( $ key ) { if ( is_string ( $ key ) ) { return $ key ; } else { $ keyStr = Json :: encode ( $ key ) ; return md5 ( $ keyStr ) ; } }

Process key. Ensure that key is string
@param string|array $key
@return string


private function checkEventClassName(string $eventClassName): Observed
    {
        if (!\class_exists($eventClassName)) {
            throw new \RuntimeException('Missing event class '.$eventClassName);
        }

        $interfacesList = \class_implements($eventClassName);

        if (!isset($interfacesList['Teknoo\States\LifeCycle\Event\EventInterface'])) {
            throw new \RuntimeException('The event class does not implement the EventInterface');
        }

        $this->eventClassName = $eventClassName;

        return $this;
    }

To check if the required event class name.

@param string $eventClassName

@return self

To check if the required event class name .


private function buildEvent()
    {
        $currentEnabledStates = $this->getObject()->listEnabledStates();
        $lastEnabledStates = $this->getLastEnabledStates();

        //New state = current states - old states
        $incomingStates = \array_diff($currentEnabledStates, $lastEnabledStates);
        //Outgoing state = lst states - current states
        $outgoingStates = \array_diff($lastEnabledStates, $currentEnabledStates);

        $eventClassName = $this->eventClassName;
        $this->lastEvent = new $eventClassName($this, $incomingStates, $outgoingStates);

        return $this;
    }

Build event, retrieve current enabled states of the instace and compute difference with last enabled states.

@return $this

Build event retrieve current enabled states of the instace and compute difference with last enabled states .


public static function avg($array)
  {
    $total = 0;
    foreach ($array as $value) {
      if (is_numeric($value)) {
        $total += $value;
      }
    }
    return $total / count($array);
  }

public static function avg ( $ array ) { $ total = 0 ; foreach ( $ array as $ value ) { if ( is_numeric ( $ value ) ) { $ total += $ value ; } } return $ total / count ( $ array ) ; }

Effectue la moyenne des valeurs du tableau

@param  array $array  Tableau source
@return float


public function orderBy($field, $direction = self::ASCENDING) {
        $this->orderBy = [$field, $direction];
        return $this;
    }

public function orderBy ( $ field , $ direction = self :: ASCENDING ) { $ this -> orderBy = [ $ field , $ direction ] ; return $ this ; }

Changes how the results are ordered.
@param string $field
@return self


public function read()
    {
        if (is_null($constructor = $this->reflector->getConstructor())) {
            return [];
        }

        $parameters = [];

        foreach ($constructor->getParameters() as $reflectionParameter) {
            /**
             * @var \ReflectionParameter $parameter
             */

            $parameter = [
                "isClass"         => ! is_null($reflectionParameter->getClass()),
                "hasDefaultValue" => $reflectionParameter->isDefaultValueAvailable(),
            ];

            if ($parameter["isClass"]) {
                $parameter["value"] = $reflectionParameter->getClass()->getName();
            }

            if ($parameter["hasDefaultValue"]) {
                $parameter["defaultValue"] = $reflectionParameter->getDefaultValue();
            }

            $parameters[] = $parameter;
        }

        return $parameters;
    }

Reads the constructor's type-hints.

@return array


public function getValue($object, $path)
    {
        $paths = (array) preg_split('#(\[((?>[^\[\]]+)|(?R))*\])#i', $path, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

        for ($i = 0; $i < count($paths); ++$i) {
            $path = trim((string) $paths[$i], '.');
            if ('[' == substr($path, 0, 1)) {
                ++$i;
            }
            if (preg_match('#[^a-z0-9\.\]\[]+#i', $path)) {
                $expression = trim($path, '[]');
                $object = $this->filter($object, $expression);
            } else {
                $object = $this->accessor->getValue($object, $path);
            }

            if (null === $object) {
                break;
            }
        }

        return $object;
    }

public function getValue ( $ object , $ path ) { $ paths = ( array ) preg_split ( '#(\[((?>[^\[\]]+)|(?R))*\])#i' , $ path , - 1 , PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE ) ; for ( $ i = 0 ; $ i < count ( $ paths ) ; ++ $ i ) { $ path = trim ( ( string ) $ paths [ $ i ] , '.' ) ; if ( '[' == substr ( $ path , 0 , 1 ) ) { ++ $ i ; } if ( preg_match ( '#[^a-z0-9\.\]\[]+#i' , $ path ) ) { $ expression = trim ( $ path , '[]' ) ; $ object = $ this -> filter ( $ object , $ expression ) ; } else { $ object = $ this -> accessor -> getValue ( $ object , $ path ) ; } if ( null === $ object ) { break ; } } return $ object ; }

Returns the value at the given path.

@param mixed  $object
@param string $path

@return mixed


public function setValue($object, $path, $value)
    {
        $this->accessor->setValue($object, $path, $value);
    }

public function setValue ( $ object , $ path , $ value ) { $ this -> accessor -> setValue ( $ object , $ path , $ value ) ; }

Sets the value at the given path.

@param mixed  $object
@param string $path
@param mixed  $value


public function filter(array $objects, $expression)
    {
        $filteredObjects = [];

        foreach ($objects as $key => $object) {
            try {
                if (@$this->language->evaluate('object.'.$expression, ['object' => $object])) {
                    $filteredObjects[] = $object;
                }
            } catch (\Exception $exception) {
                // Property does not exist: ignore this item
            }
        }

        return $filteredObjects;
    }

Returns the objects filtered by the given path value.

@param array  $objects
@param string $expression

@return array

Returns the objects filtered by the given path value .


public function setFrom(string $address, string $name = ''): bool
    {
        return $this->PHPMailer->setFrom($address, $name);
    }

public function setFrom ( string $ address , string $ name = '' ) : bool { return $ this -> PHPMailer -> setFrom ( $ address , $ name ) ; }

Set the mail's sender information.

@param string $address
@param string $name

@throws Exception

@return bool


public function addAddress(string $address, string $name = ''): bool
    {
        return $this->PHPMailer->addAddress($address, $name);
    }

public function addAddress ( string $ address , string $ name = '' ) : bool { return $ this -> PHPMailer -> addAddress ( $ address , $ name ) ; }

Add a recipient.

@param string $address
@param string $name

@return bool


public function addReplyTo(string $address, string $name = ''): bool
    {
        return $this->PHPMailer->addReplyTo($address, $name);
    }

public function addReplyTo ( string $ address , string $ name = '' ) : bool { return $ this -> PHPMailer -> addReplyTo ( $ address , $ name ) ; }

Add a Reply-To address.

@param string $address
@param string $name

@return bool


public function addCC(string $address, string $name = ''): bool
    {
        return $this->PHPMailer->addCC($address, $name);
    }

public function addCC ( string $ address , string $ name = '' ) : bool { return $ this -> PHPMailer -> addCC ( $ address , $ name ) ; }

Add a copy recipient.

@param string $address
@param string $name

@return bool


public function addBCC(string $address, string $name = ''): bool
    {
        return $this->PHPMailer->addBCC($address, $name);
    }

public function addBCC ( string $ address , string $ name = '' ) : bool { return $ this -> PHPMailer -> addBCC ( $ address , $ name ) ; }

Add a blind copy recipient.

@param string $address
@param string $name

@return bool


public function addAttachment(string $path, string $name = ''): bool
    {
        return $this->PHPMailer->addAttachment($path, $name);
    }

public function addAttachment ( string $ path , string $ name = '' ) : bool { return $ this -> PHPMailer -> addAttachment ( $ path , $ name ) ; }

Add an attachment from the filesystem.

@param string $path
@param string $name

@throws Exception

@return bool


public function run(string $sync = null): int
    {
        $containerCache = console()->matchCommand(ContainerCacheCommand::COMMAND);
        $consoleCache   = console()->matchCommand(ConsoleCacheCommand::COMMAND);
        $eventsCache    = console()->matchCommand(EventsCacheCommand::COMMAND);
        $routesCache    = console()->matchCommand(RoutesCacheCommand::COMMAND);

        console()->dispatchCommand($containerCache);
        console()->dispatchCommand($consoleCache);
        console()->dispatchCommand($eventsCache);
        console()->dispatchCommand($routesCache);

        $configCache = console()->matchCommand(ConfigCacheCommand::COMMAND);
        console()->dispatchCommand($configCache);

        if (null !== $sync && config()['app']['debug']) {
            $files = [
                config()['console']['cacheFilePath'],
                config()['container']['cacheFilePath'],
                config()['events']['cacheFilePath'],
                config()['routing']['cacheFilePath'],
                config()['cacheFilePath'],
            ];

            foreach ($files as $file) {
                copy($file, str_replace('site', 'sync', $file));
                output()->writeMessage('Copied: ' . $file, true);
            }
        }

        return 0;
    }

public
function
run
(
string
$
sync
=
)
:
int
{
$
containerCache
=
console
(
)
->
matchCommand
(
ContainerCacheCommand
::
COMMAND
)
;
$
consoleCache
=
console
(
)
->
matchCommand
(
ConsoleCacheCommand
::
COMMAND
)
;
$
eventsCache
=
console
(
)
->
matchCommand
(
EventsCacheCommand
::
COMMAND
)
;
$
routesCache
=
console
(
)
->
matchCommand
(
RoutesCacheCommand
::
COMMAND
)
;
console
(
)
->
dispatchCommand
(
$
containerCache
)
;
console
(
)
->
dispatchCommand
(
$
consoleCache
)
;
console
(
)
->
dispatchCommand
(
$
eventsCache
)
;
console
(
)
->
dispatchCommand
(
$
routesCache
)
;
$
configCache
=
console
(
)
->
matchCommand
(
ConfigCacheCommand
::
COMMAND
)
;
console
(
)
->
dispatchCommand
(
$
configCache
)
;
if
(
!==
$
sync
&&
config
(
)
[
'app'
]
[
'debug'
]
)
{
$
files
=
[
config
(
)
[
'console'
]
[
'cacheFilePath'
]
,
config
(
)
[
'container'
]
[
'cacheFilePath'
]
,
config
(
)
[
'events'
]
[
'cacheFilePath'
]
,
config
(
)
[
'routing'
]
[
'cacheFilePath'
]
,
config
(
)
[
'cacheFilePath'
]
,
]
;
foreach
(
$
files
as
$
file
)
{
copy
(
$
file
,
str_replace
(
'site'
,
'sync'
,
$
file
)
)
;
output
(
)
->
writeMessage
(
'Copied: '
.
$
file
,
true
)
;
}
}
return
0
;
}

Generate all cache files.

@param string $sync [optional] Whether to sync the cached files

@throws CommandNotFound

@return int


public static function setReferer($uri = null)
    {
        if (empty($uri)) $uri = UrlHelper::getRequestUrl();
        CarteBlanche::getContainer()->get('session')->set('referer', $uri);
        return true;
    }

public static function setReferer ( $ uri = null ) { if ( empty ( $ uri ) ) $ uri = UrlHelper :: getRequestUrl ( ) ; CarteBlanche :: getContainer ( ) -> get ( 'session' ) -> set ( 'referer' , $ uri ) ; return true ; }

Store the referer URL in session

@param   string $uri The referer URI to store
@return  bool


public static function getReferer()
    {
        return (CarteBlanche::getContainer()->get('session')->has('referer') ?
            CarteBlanche::getContainer()->get('session')->get('referer') : null);
    }

public static function getReferer ( ) { return ( CarteBlanche :: getContainer ( ) -> get ( 'session' ) -> has ( 'referer' ) ? CarteBlanche :: getContainer ( ) -> get ( 'session' ) -> get ( 'referer' ) : null ) ; }

Get the referer URL in session

@return string The referer value in session


public function buildUrl($param = null, $value = null, $separator = '&')
    {
        if (!is_array($param) && !empty($value)) {
            $param = array( $param=>$value );
        }

        $default_args = array(
            'controller' => CarteBlanche::getConfig('routing.mvc.default_controller'),
            'action' => CarteBlanche::getConfig('routing.mvc.default_action')
        );
        if (!empty($param)) {
            foreach ($param as $_var=>$_val) {
                if (!empty($_val)) {
                    $_meth = 'fromUrl'.TextHelper::toCamelCase($_var);
                    if (method_exists($this, $_meth)) {
                        $_val = call_user_func_array(array($this, $_meth), array($_val));
                    }
                    if (array_key_exists($_var, $default_args) && (
                        $_val===$default_args[$_var] || strtolower($_val)===$default_args[$_var] || parent::urlEncode($_val)===$default_args[$_var]
                    )) {
                        unset($param[$_var]);
                    }
                }
            }
        }

        return parent::generateUrl($param, CarteBlanche::getPath('root_file'), '', $separator);
    }

public function buildUrl ( $ param = null , $ value = null , $ separator = '&' ) { if ( ! is_array ( $ param ) && ! empty ( $ value ) ) { $ param = array ( $ param => $ value ) ; } $ default_args = array ( 'controller' => CarteBlanche :: getConfig ( 'routing.mvc.default_controller' ) , 'action' => CarteBlanche :: getConfig ( 'routing.mvc.default_action' ) ) ; if ( ! empty ( $ param ) ) { foreach ( $ param as $ _var => $ _val ) { if ( ! empty ( $ _val ) ) { $ _meth = 'fromUrl' . TextHelper :: toCamelCase ( $ _var ) ; if ( method_exists ( $ this , $ _meth ) ) { $ _val = call_user_func_array ( array ( $ this , $ _meth ) , array ( $ _val ) ) ; } if ( array_key_exists ( $ _var , $ default_args ) && ( $ _val === $ default_args [ $ _var ] || strtolower ( $ _val ) === $ default_args [ $ _var ] || parent :: urlEncode ( $ _val ) === $ default_args [ $ _var ] ) ) { unset ( $ param [ $ _var ] ) ; } } } } return parent :: generateUrl ( $ param , CarteBlanche :: getPath ( 'root_file' ) , '' , $ separator ) ; }

Build an application URL with a set of arguments

The class will pass arguments values to any `$this->toUrlParam($value)` method for the
parameter named `param`.

@param string/array $param The parameter name if it's single, an array of parameters and their values otherwise
@param string $value The value for the parameter if it's single
@param string $separator The argument/value separator (default is escaped ampersand : '&')
@return string The URL built


protected function downloadPackage()
    {
        $this->crowdinClient->api('export')->execute();
        $path = $this->createArchiveDirectory();

        /** @var Download $download */
        $download = $this->crowdinClient->api('download');
        $download->setCopyDestination($path);
        $download->setPackage(self::CROWDIN_PACKAGE);
        $download->execute();

        $this->archive->setFilename(self::CROWDIN_PACKAGE);
        $this->archive->setPath($path);
    }

protected
function
downloadPackage
(
)
{
$
this
->
crowdinClient
->
api
(
'export'
)
->
execute
(
)
;
$
path
=
$
this
->
createArchiveDirectory
(
)
;
/** @var Download $download */
$
download
=
$
this
->
crowdinClient
->
api
(
'download'
)
;
$
download
->
setCopyDestination
(
$
path
)
;
$
download
->
setPackage
(
self
::
CROWDIN_PACKAGE
)
;
$
download
->
execute
(
)
;
$
this
->
archive
->
setFilename
(
self
::
CROWDIN_PACKAGE
)
;
$
this
->
archive
->
setPath
(
$
path
)
;
}

Download a fresh Crowdin package

@throws \Exception


protected function extractPackage($projectPath)
    {
        $this->archive->setExtractPath($projectPath);
        $this->archive->extract()->remove();
    }

protected function extractPackage ( $ projectPath ) { $ this -> archive -> setExtractPath ( $ projectPath ) ; $ this -> archive -> extract ( ) -> remove ( ) ; }

Extract the Crowdin package

@param $projectPath


protected function resetDefaultLocaleTranslations()
    {
        $translations = $this->translationsFinder->getDefaultLocaleTranslations();
        foreach ($translations as $translation) {
            $this->gitHandler->reset($translation->getPathname());
        }
    }

protected function resetDefaultLocaleTranslations ( ) { $ translations = $ this -> translationsFinder -> getDefaultLocaleTranslations ( ) ; foreach ( $ translations as $ translation ) { $ this -> gitHandler -> reset ( $ translation -> getPathname ( ) ) ; } }

Undo changes possibly made to the default locale translations


protected function _strpos( $haystack, $needle ) {
		return function_exists( 'mb_strpos' ) ? mb_strpos( $haystack, $needle ) : strpos( $haystack, $needle );
	}

protected function _strpos ( $ haystack , $ needle ) { return function_exists ( 'mb_strpos' ) ? mb_strpos ( $ haystack , $ needle ) : strpos ( $ haystack , $ needle ) ; }

Find position of first occurrence of string in a string.

@param  string $haystack
@param  string $needle
@return bool|int

Find position of first occurrence of string in a string .


public function createSidebarMenu(Request $request)
    {
        $menu = $this->factory->createItem('root', array(
            'childrenAttributes' => array(
                'class' => 'big-menu',
            )
        ));
        $section = 'sidebar';
        $menu->addChild('home',array(
            'route' => '',//Route
            'labelAttributes' => array('icon' => 'icon-home'),
        ))->setLabel($this->translate(sprintf('app.backend.menu.%s.home', $section)));

        $this->addExampleMenu($menu, $section);

        $menu->addChild('support', array(
            'route' => self::ROUTE_DEFAULT,
            'labelAttributes' => array('icon' => 'icon-info'),
        ))->setLabel($this->translate(sprintf('app.backend.menu.%s.support', 'sidebar')));
        return $menu;
    }

public function createSidebarMenu ( Request $ request ) { $ menu = $ this -> factory -> createItem ( 'root' , array ( 'childrenAttributes' => array ( 'class' => 'big-menu' , ) ) ) ; $ section = 'sidebar' ; $ menu -> addChild ( 'home' , array ( 'route' => '' , //Route 'labelAttributes' => array ( 'icon' => 'icon-home' ) , ) ) -> setLabel ( $ this -> translate ( sprintf ( 'app.backend.menu.%s.home' , $ section ) ) ) ; $ this -> addExampleMenu ( $ menu , $ section ) ; $ menu -> addChild ( 'support' , array ( 'route' => self :: ROUTE_DEFAULT , 'labelAttributes' => array ( 'icon' => 'icon-info' ) , ) ) -> setLabel ( $ this -> translate ( sprintf ( 'app.backend.menu.%s.support' , 'sidebar' ) ) ) ; return $ menu ; }

Builds backend sidebar menu.

@param Request $request

@return ItemInterface


function addExampleMenu(ItemInterface $menu, $section) {
        $child = $this->factory->createItem('example',
                    $this->getSubLevelOptions(array(
                    'uri' => null,
                    'labelAttributes' => array('icon' => 'icon-book',),
                    ))
                )
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.main', $section)));
        $child
                ->addChild('example.company', array(
                    'route' => '',
                    ))
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.company', $section)));
        $child
                ->addChild('example.technical_reports', array(
                    'route' => '',
                    ))
                ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.technical_reports', $section)));

            $subchild = $this->factory->createItem('subexample',
                        $this->getSubLevelOptions(array(
                        'uri' => null,
                        'labelAttributes' => array('icon' => 'icon-book',),
                        ))
                    )
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.main', $section)));
            $subchild
                    ->addChild('example.other.admin', array(
                        'route' => self::ROUTE_DEFAULT,
                        ))
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.admin', $section)));

            $subchild->addChild('example.other.groups', array(
                        'route' => self::ROUTE_DEFAULT,
                    ))
                    ->setLabel($this->translate(sprintf('app.backend.menu.%s.example.other.groups', $section)));

            $child->addChild($subchild);

        $menu->addChild($child);
    }

Construye el menu de ejemplo

@param \Knp\Menu\ItemInterface $menu
@param type $section


public function register() {
        $this->loadEntitiesFrom(__DIR__);

        $this->app->singleton('migration.repository', function($app) {
            return new DoctrineMigrationRepository(
                function() use($app) {
                    return $app->make(EntityManagerInterface::class);
                },
                function() use($app) {
                    return $app->make(SchemaTool::class);
                },
                function() use($app) {
                    return $app->make(ClassMetadataFactory::class);
                }
            );
        });
        $this->app->bind(MigrationRepositoryInterface::class, 'migration.repository');
    }

public function register ( ) { $ this -> loadEntitiesFrom ( __DIR__ ) ; $ this -> app -> singleton ( 'migration.repository' , function ( $ app ) { return new DoctrineMigrationRepository ( function ( ) use ( $ app ) { return $ app -> make ( EntityManagerInterface :: class ) ; } , function ( ) use ( $ app ) { return $ app -> make ( SchemaTool :: class ) ; } , function ( ) use ( $ app ) { return $ app -> make ( ClassMetadataFactory :: class ) ; } ) ; } ) ; $ this -> app -> bind ( MigrationRepositoryInterface :: class , 'migration.repository' ) ; }


public function publishPages($urls)
    {
        LivePubHelper::init_pub();
        $r = $this->realPublishPages($urls);
        LivePubHelper::stop_pub();
        return $r;
    }

public function publishPages ( $ urls ) { LivePubHelper :: init_pub ( ) ; $ r = $ this -> realPublishPages ( $ urls ) ; LivePubHelper :: stop_pub ( ) ; return $ r ; }

Wrapper for parent funciton. Switches on and off livepub publishing.

@param  array $urls Relative URLs
@return array Result, keyed by URL. Keys:
- "statuscode": The HTTP status code
- "redirect": A redirect location (if applicable)
- "path": The filesystem path where the cache has been written

Wrapper for parent funciton . Switches on and off livepub publishing .


public function update($params = array())
    {
        $this->adapter->execute($this->toSql(), array_merge($this->params(), $this->params(true), $params));

        return true;
    }

public function update ( $ params = array ( ) ) { $ this -> adapter -> execute ( $ this -> toSql ( ) , array_merge ( $ this -> params ( ) , $ this -> params ( true ) , $ params ) ) ; return true ; }


public function load($context, $filePath = null)
    {
        if (isset($filePath)) {
            $this->filePath = $filePath;
        }
        if (!isset($this->_messages)) {
            $this->loadAll();
        }
        return isset($this->_messages[$context]) ? $this->_messages[$context] : [];
    }

public function load ( $ context , $ filePath = null ) { if ( isset ( $ filePath ) ) { $ this -> filePath = $ filePath ; } if ( ! isset ( $ this -> _messages ) ) { $ this -> loadAll ( ) ; } return isset ( $ this -> _messages [ $ context ] ) ? $ this -> _messages [ $ context ] : [ ] ; }

Loads messages from a PO file.
@param string      $context message context
@param string|null $filePath file path
@return array message translations. Array keys are source messages and array values are translated messages:
source message => translated message.
@throws InvalidConfigException


public function getCategories()
    {
        if (!isset($this->_messages)) {
            $this->loadAll();
        }
        $categories = array_keys($this->_messages);
        sort($categories);
        return $categories;
    }

public function getCategories ( ) { if ( ! isset ( $ this -> _messages ) ) { $ this -> loadAll ( ) ; } $ categories = array_keys ( $ this -> _messages ) ; sort ( $ categories ) ; return $ categories ; }

Get all categories list
@return string[]


protected function getFileName(Response $response)
    {
        $headers = $response->getHeaders();
        $contentDisposition = isset($headers['Content-Disposition'][0]) ? $headers['Content-Disposition'][0] : null;

        if ($contentDisposition && preg_match('/filename="(.+)"/', $contentDisposition, $filename)) {
            return $filename[1];
        }

        return null;
    }

protected function getFileName ( Response $ response ) { $ headers = $ response -> getHeaders ( ) ; $ contentDisposition = isset ( $ headers [ 'Content-Disposition' ] [ 0 ] ) ? $ headers [ 'Content-Disposition' ] [ 0 ] : null ; if ( $ contentDisposition && preg_match ( '/filename="(.+)"/' , $ contentDisposition , $ filename ) ) { return $ filename [ 1 ] ; } return null ; }

Retrieve the filename from headers.

@param Response $response

@return string


protected function validateUploadedFiles(array $uploadedFiles): void
    {
        foreach ($uploadedFiles as $file) {
            if (\is_array($file)) {
                $this->validateUploadedFiles($file);

                continue;
            }

            if (! $file instanceof UploadedFile) {
                throw new InvalidUploadedFile(
                    'Invalid leaf in uploaded files structure'
                );
            }
        }
    }

Validate uploaded files.

@param array $uploadedFiles The uploaded files

@throws \Valkyrja\HttpMessage\Exceptions\InvalidUploadedFile

@return void


protected function initResultObject()
    {
        if(!array_key_exists('default', $this->config)) {
            return null;
        }
        // init default value from data
        foreach ($this->config['default'] as $defaultKey => $defaultValue) {
            Tools::runSetter($this->resultObject, $defaultKey, $defaultValue);
        }
    }

protected
function
initResultObject
(
)
{
if
(
!
array_key_exists
(
'default'
,
$
this
->
config
)
)
{
return
;
}
// init default value from data
foreach
(
$
this
->
config
[
'default'
]
as
$
defaultKey
=>
$
defaultValue
)
{
Tools
::
runSetter
(
$
this
->
resultObject
,
$
defaultKey
,
$
defaultValue
)
;
}
}

Result object initialisation
@return null


private function getPattern(string $patternId, array $patternData): array
    {
        if (array_key_exists('default', $patternData) && $patternData['default'] === true) {
            return ['pattern' => sprintf('/%s/', $patternId), 'version' => $patternId];
        }
        return ['pattern' => sprintf('/%s/', $patternData['pattern']), 'version' => array_key_exists('version', $patternData) ? $patternData['version'] : $patternId];
    }

private function getPattern ( string $ patternId , array $ patternData ) : array { if ( array_key_exists ( 'default' , $ patternData ) && $ patternData [ 'default' ] === true ) { return [ 'pattern' => sprintf ( '/%s/' , $ patternId ) , 'version' => $ patternId ] ; } return [ 'pattern' => sprintf ( '/%s/' , $ patternData [ 'pattern' ] ) , 'version' => array_key_exists ( 'version' , $ patternData ) ? $ patternData [ 'version' ] : $ patternId ] ; }

Get pattern form array
@param string $patternId ID in config
@param array $patternData array from yaml file
@return array


protected function setAttributes(array $info)
    {
        $result = $this->detector->getResultObject();
        if (array_key_exists('attributes', $info)) {
            foreach ($info['attributes'] as $attributeKey => $attributeValue) {
                Tools::runSetter($result, $attributeKey, $attributeValue);
            }
        }
    }

protected function setAttributes ( array $ info ) { $ result = $ this -> detector -> getResultObject ( ) ; if ( array_key_exists ( 'attributes' , $ info ) ) { foreach ( $ info [ 'attributes' ] as $ attributeKey => $ attributeValue ) { Tools :: runSetter ( $ result , $ attributeKey , $ attributeValue ) ; } } }

Set attributes of result object
@param array $info Array


protected function detectByKey($keyName = 'family'): array
    {
        foreach ($this->config as $key => $data) {
            if ($key === 'default') {
                continue;
            }
            $detectedData = $this->detectByType($key);
            if (!empty($detectedData)) {
                return array_merge($detectedData, [$keyName => $key]);
            }
        }
        return [];
    }

protected function detectByKey ( $ keyName = 'family' ) : array { foreach ( $ this -> config as $ key => $ data ) { if ( $ key === 'default' ) { continue ; } $ detectedData = $ this -> detectByType ( $ key ) ; if ( ! empty ( $ detectedData ) ) { return array_merge ( $ detectedData , [ $ keyName => $ key ] ) ; } } return [ ] ; }

Detect by Key
@param string $keyName
@return array


public function onShell(): bool {
    $check = true;
    if (PHP_SAPI != Environment::SERVER_CLI) {
      $check = false;
    }
    return $check;
  }

public function onShell ( ) : bool { $ check = true ; if ( PHP_SAPI != Environment :: SERVER_CLI ) { $ check = false ; } return $ check ; }

- Check script execute on shell
@return bool Case yes return true, or false case other


public function getConfig()
    {
        if (!isset($config)) {
            $this->config = $this->getServiceLocator()->get('FzyCommon\Config');
        }

        return $this->config;
    }

public function getConfig ( ) { if ( ! isset ( $ config ) ) { $ this -> config = $ this -> getServiceLocator ( ) -> get ( 'FzyCommon\Config' ) ; } return $ this -> config ; }

Get the application config as a Params object
@return Params


public function DMSLatitude($format = '%d %d %F %s') {

    $lat = $this->convertDecToDMS($this->latitude());

    $direction = 'N';
    if ($lat['degrees'] < 0) {
      $direction = 'S';
    }

    return sprintf($format, $lat['degrees'], $lat['minutes'], $lat['seconds'], $direction);
  }

public
function
DMSLatitude
(
$
format
=
'%d %d %F %s'
)
{
$
lat
=
$
this
->
convertDecToDMS
(
$
this
->
latitude
(
)
)
;
$
direction
=
'N'
;
if
(
$
lat
[
'degrees'
]
<
0
)
{
$
direction
=
'S'
;
}
return
sprintf
(
$
format
,
$
lat
[
'degrees'
]
,
$
lat
[
'minutes'
]
,
$
lat
[
'seconds'
]
,
$
direction
)
;
}

Get the current latitude in Degrees, Minutes, Seconds notation.

@param string $format
The format string to use for the response. Defaults to %d %d %F %s

@return string
A string with the current latitude in DMS format.

Get the current latitude in Degrees Minutes Seconds notation .


public function DMSLongitude($format = '%d %d %F %s') {
    $long = $this->convertDecToDMS($this->longitude());

    $direction = 'E';
    if ($long['degrees'] < 0) {
      $direction = 'W';
    }

    return sprintf($format, $long['degrees'], $long['minutes'], $long['seconds'], $direction);
  }

public
function
DMSLongitude
(
$
format
=
'%d %d %F %s'
)
{
$
long
=
$
this
->
convertDecToDMS
(
$
this
->
longitude
(
)
)
;
$
direction
=
'E'
;
if
(
$
long
[
'degrees'
]
<
0
)
{
$
direction
=
'W'
;
}
return
sprintf
(
$
format
,
$
long
[
'degrees'
]
,
$
long
[
'minutes'
]
,
$
long
[
'seconds'
]
,
$
direction
)
;
}

Get the current longitude in Degrees, Minutes, Seconds notation.

@param string $format
The format string to use for the response. Defaults to %d %d %F %s

@return string
A string with the current longitude in DMS format.

Get the current longitude in Degrees Minutes Seconds notation .


public function latitudeRange($distance) {
    $long = deg2rad($this->longitude());
    $lat = deg2rad($this->latitude());

    $radius = $this->earthRadius($this->latitude());
    $angle = $distance / $radius;
    $rightangle = pi() / 2;

    $minlat = $lat - $angle;
    if ($minlat < -$rightangle) { // wrapped around the south pole
      $overshoot = -$minlat - $rightangle;
      $minlat = -$rightangle + $overshoot;
      if ($minlat > $maxlat) { $maxlat = $minlat; }
      $minlat = -$rightangle;
    }

    $maxlat = $lat + $angle;
    if ($maxlat > $rightangle) { // wrapped around the north pole
      $overshoot = $maxlat - $rightangle;
      $maxlat = $rightangle - $overshoot;
      if ($maxlat < $minlat) { $minlat = $maxlat; }
      $maxlat = $rightangle;
    }

    return array(
      'min' => rad2deg($minlat),
      'max' => rad2deg($maxlat),
    );
  }

public
function
latitudeRange
(
$
distance
)
{
$
long
=
deg2rad
(
$
this
->
longitude
(
)
)
;
$
lat
=
deg2rad
(
$
this
->
latitude
(
)
)
;
$
radius
=
$
this
->
earthRadius
(
$
this
->
latitude
(
)
)
;
$
angle
=
$
distance
/
$
radius
;
$
rightangle
=
pi
(
)
/
2
;
$
minlat
=
$
lat
$
angle
;
if
(
$
minlat
<
$
rightangle
)
{
// wrapped around the south pole
$
overshoot
=
$
minlat
$
rightangle
;
$
minlat
=
$
rightangle
+
$
overshoot
;
if
(
$
minlat
>
$
maxlat
)
{
$
maxlat
=
$
minlat
;
}
$
minlat
=
$
rightangle
;
}
$
maxlat
=
$
lat
+
$
angle
;
if
(
$
maxlat
>
$
rightangle
)
{
// wrapped around the north pole
$
overshoot
=
$
maxlat
$
rightangle
;
$
maxlat
=
$
rightangle
$
overshoot
;
if
(
$
maxlat
<
$
minlat
)
{
$
minlat
=
$
maxlat
;
}
$
maxlat
=
$
rightangle
;
}
return
array
(
'min'
=>
rad2deg
(
$
minlat
)
,
'max'
=>
rad2deg
(
$
maxlat
)
,
)
;
}

Find a range of latitudes given a center point.

This is useful when you have a center point and want to find a range to
query against a set. For example, you want to find all the businesses to
display on the glowing rectangle (mobile device) given a center point and
radius.

Note, this are just quickly calculated estimates.

@param float $distance
The distance in meters from the center point to calculate.

@return array
An array with the two bounding values (floats) for the range.

Find a range of latitudes given a center point .


public function longitudeRange($distance) {
    $long = deg2rad($this->longitude());
    $lat = deg2rad($this->latitude());

    $radius = $this->earthRadius($this->latitude());
    $angle = $distance / $radius;
    $diff = asin(sin($angle) / cos($lat));

    $minlong = $long - $diff;
    if ($minlong < -pi()) {
      $minlong = $minlong + pi() * 2;
    }

    $maxlong = $long + $diff;
    if ($maxlong > pi()) {
      $maxlong = $maxlong - pi() * 2;
    }

    return array(
      'min' => rad2deg($minlong),
      'max' => rad2deg($maxlong),
    );
  }

public function longitudeRange ( $ distance ) { $ long = deg2rad ( $ this -> longitude ( ) ) ; $ lat = deg2rad ( $ this -> latitude ( ) ) ; $ radius = $ this -> earthRadius ( $ this -> latitude ( ) ) ; $ angle = $ distance / $ radius ; $ diff = asin ( sin ( $ angle ) / cos ( $ lat ) ) ; $ minlong = $ long - $ diff ; if ( $ minlong < - pi ( ) ) { $ minlong = $ minlong + pi ( ) * 2 ; } $ maxlong = $ long + $ diff ; if ( $ maxlong > pi ( ) ) { $ maxlong = $ maxlong - pi ( ) * 2 ; } return array ( 'min' => rad2deg ( $ minlong ) , 'max' => rad2deg ( $ maxlong ) , ) ; }

Find a range of longitude given a center point.

This is useful when you have a center point and want to find a range to
query against a set. For example, you want to find all the businesses to
display on the glowing rectangle (mobile device) given a center point and
radius.

Note, this are just quickly calculated estimates.

@param float $distance
The distance in meters from the center point to calculate.

@return array
An array with the two bounding values (floats) for the range.

Find a range of longitude given a center point .


public function distance(LocationInterface $location, $method = 'default') {

    if (!isset($this->distanceCache[$method])) {

      if (!isset($this->distanceMethods[$method])) {
        throw new Exception('Distance method not registered.');
      }
      elseif (!class_exists($this->distanceMethods[$method])) {
        throw new Exception('The class associated with the name does not exist.');
      }

      // @todo: Should this verify the proper interface is implemented? If not
      // it will simply explode.

      $this->distanceCache[$method] = new $this->distanceMethods[$method];
    }

    return $this->distanceCache[$method]->distance($this, $location);
  }

Get the distance between this location and another one.

@param \Lootils\Geo\LocationInterface $location
The other location object to diff the distance of.
@param string $method
The registered method to use for this calculation. Because the Earth is
an irregular ellipse there are multiple math equations attempting to
best calculate the distance.

@return float
The estimated distance between the two locations in meters.

Get the distance between this location and another one .


public function matches(array $data)
    {
        foreach ($this->filters as $filter) {
            if ($filter($data)) {
                return true;
            }
        }

        return false;
    }

public function matches ( array $ data ) { foreach ( $ this -> filters as $ filter ) { if ( $ filter ( $ data ) ) { return true ; } } return false ; }

Loop through all the filters and only return if all match

@param array $data

@return bool


public function createTablesFromConfig($config)
    {
        try{
            foreach ($config as $tableName => $className
            ) {
                $this->_addTable(new $className($tableName));
            }
        } catch(\Exception $e) {
            throw $e;
        }

        return $this;
    }

public function createTablesFromConfig ( $ config ) { try { foreach ( $ config as $ tableName => $ className ) { $ this -> _addTable ( new $ className ( $ tableName ) ) ; } } catch ( \ Exception $ e ) { throw $ e ; } return $ this ; }

Creates tables from config

@param array $config Array config
array('connection_name'=>array(
'tables' => array(
'table_name' => 'table_class',
)))

@throws \Exception

@return $this


public function bundleMultipleSchemas($config)
    {
        foreach ($config as $alias => $schemaClassName) {
            $schema = new $schemaClassName();
            $this->_tables = array_merge($this->getTables(), $schema->getTables());
        }

        return $this;
    }

public function bundleMultipleSchemas ( $ config ) { foreach ( $ config as $ alias => $ schemaClassName ) { $ schema = new $ schemaClassName ( ) ; $ this -> _tables = array_merge ( $ this -> getTables ( ) , $ schema -> getTables ( ) ) ; } return $ this ; }

Bundle multiple schemas

@param array $config Array config
array('connection_name'=>array(
'schema_name' => 'schema_class',
))

@return $this


public function getPoint($name)
    {
        return isset($this->_points[$name]) ? $this->_points[$name] : null;
    }

public function getPoint ( $ name ) { return isset ( $ this -> _points [ $ name ] ) ? $ this -> _points [ $ name ] : null ; }

Get a point of the object

@param   string                  $name
@return  \Maths\PointInterface


public static function publish(Application $app): void
    {
        $app->console()->addCommand(
            (new Command())
                ->setPath(static::PATH)
                ->setName(static::COMMAND)
                ->setDescription(static::SHORT_DESCRIPTION)
                ->setClass(static::class)
        );
    }

public static function publish ( Application $ app ) : void { $ app -> console ( ) -> addCommand ( ( new Command ( ) ) -> setPath ( static :: PATH ) -> setName ( static :: COMMAND ) -> setDescription ( static :: SHORT_DESCRIPTION ) -> setClass ( static :: class ) ) ; }

Publish the command.

@param Application $app The application

@return void


protected function getMatchingUrlFragment(Request $request, $currentUrlFragment = "")
    {
        $uri = $currentUrlFragment;

        $parentResponse = parent::getMatchingUrlFragment($request, $currentUrlFragment);

        if (preg_match('|^' . $this->url . '([0-9]+)/([a-zA-Z0-9\-]+)|', $uri, $matches)) {
            if ($this->checkForPotentialAction($matches[2])) {
                $this->urlAction = $matches[2];
                $this->isCollection = false;

                return $matches[0];
            }
        }

        if (preg_match("|^" . $this->url . "([^/]+)/|", $uri, $match)) {
            if (is_numeric($match[1]) || isset($this->additionalLeafClassNameMap[$match[1]])) {
                $this->urlAction = $match[1];
                $this->isCollection = false;

                return $match[0];
            }
        }

        return $parentResponse;
    }

protected function getMatchingUrlFragment ( Request $ request , $ currentUrlFragment = "" ) { $ uri = $ currentUrlFragment ; $ parentResponse = parent :: getMatchingUrlFragment ( $ request , $ currentUrlFragment ) ; if ( preg_match ( '|^' . $ this -> url . '([0-9]+)/([a-zA-Z0-9\-]+)|' , $ uri , $ matches ) ) { if ( $ this -> checkForPotentialAction ( $ matches [ 2 ] ) ) { $ this -> urlAction = $ matches [ 2 ] ; $ this -> isCollection = false ; return $ matches [ 0 ] ; } } if ( preg_match ( "|^" . $ this -> url . "([^/]+)/|" , $ uri , $ match ) ) { if ( is_numeric ( $ match [ 1 ] ) || isset ( $ this -> additionalLeafClassNameMap [ $ match [ 1 ] ] ) ) { $ this -> urlAction = $ match [ 1 ] ; $ this -> isCollection = false ; return $ match [ 0 ] ; } } return $ parentResponse ; }

Should be implemented to return a true or false as to whether this handler supports the given request.

Normally this involves testing the request URI.

@param Request $request
@param string $currentUrlFragment
@return bool

Should be implemented to return a true or false as to whether this handler supports the given request .


protected function generateResponseForRequest($request = null)
    {
        $leafClass = $this->getLeafClassName();

        if ($this->isCollection()) {
            $leaf = new $leafClass($this->getModelCollection());
        } else {
            if (is_callable($leafClass)){
                $leaf = $leafClass($this, $this->getModelObject());
            } else {
                $leaf = new $leafClass($this->getModelObject());
            }
        }

        $response = $leaf->generateResponse($request);

        if (is_string($response)) {
            $htmlResponse = new HtmlResponse($leaf);
            $htmlResponse->setContent($response);
            $response = $htmlResponse;
        }

        return $response;
    }

protected function generateResponseForRequest ( $ request = null ) { $ leafClass = $ this -> getLeafClassName ( ) ; if ( $ this -> isCollection ( ) ) { $ leaf = new $ leafClass ( $ this -> getModelCollection ( ) ) ; } else { if ( is_callable ( $ leafClass ) ) { $ leaf = $ leafClass ( $ this , $ this -> getModelObject ( ) ) ; } else { $ leaf = new $ leafClass ( $ this -> getModelObject ( ) ) ; } } $ response = $ leaf -> generateResponse ( $ request ) ; if ( is_string ( $ response ) ) { $ htmlResponse = new HtmlResponse ( $ leaf ) ; $ htmlResponse -> setContent ( $ response ) ; $ response = $ htmlResponse ; } return $ response ; }

Return the response if appropriate or false if no response could be generated.

@param mixed $request
@return bool

Return the response if appropriate or false if no response could be generated .


function retrieveCacheFirst($url, $accept = false, $forcestring = false, $channel = false)
    {
        $cachefile = $this->config->get('cache_dir') . DIRECTORY_SEPARATOR .
            md5($url) . 'rest.cachefile';

        if (file_exists($cachefile)) {
            return unserialize(implode('', file($cachefile)));
        }

        return $this->retrieveData($url, $accept, $forcestring, $channel);
    }

function retrieveCacheFirst ( $ url , $ accept = false , $ forcestring = false , $ channel = false ) { $ cachefile = $ this -> config -> get ( 'cache_dir' ) . DIRECTORY_SEPARATOR . md5 ( $ url ) . 'rest.cachefile' ; if ( file_exists ( $ cachefile ) ) { return unserialize ( implode ( '' , file ( $ cachefile ) ) ) ; } return $ this -> retrieveData ( $ url , $ accept , $ forcestring , $ channel ) ; }

Retrieve REST data, but always retrieve the local cache if it is available.

This is useful for elements that should never change, such as information on a particular
release
@param string full URL to this resource
@param array|false contents of the accept-encoding header
@param boolean     if true, xml will be returned as a string, otherwise, xml will be
parsed using PEAR_XMLParser
@return string|array

Retrieve REST data but always retrieve the local cache if it is available .


public static function endsWith($string, $with, $caseSensitive = true, $encoding = null)
    {
        if (!$bytes = static::byteLength($with)) {
            return true;
        }
        if ($caseSensitive) {
            // Warning check, see http://php.net/manual/en/function.substr-compare.php#refsect1-function.substr-compare-returnvalues
            if (static::byteLength($string) < $bytes) {
                return false;
            }

            return substr_compare($string, $with, -$bytes, $bytes) === 0;
        }
        if (!isset($encoding)) {
            $encoding = \Reaction::$app ? \Reaction::$app->charset : 'UTF-8';
        }
        return mb_strtolower(mb_substr($string, -$bytes, mb_strlen($string, '8bit'), '8bit'), $encoding) === mb_strtolower($with, $encoding);
    }

Check if given string ends with specified substring.
Binary and multibyte safe.

@param string $string Input string to check
@param string $with Part to search inside of the $string.
@param bool $caseSensitive Case sensitive search. Default is true. When case sensitive is enabled, $with must exactly match the ending of the string in order to get a true value.
@param string $encoding String encoding
@return bool Returns true if first input ends with second input, false otherwise

Check if given string ends with specified substring . Binary and multibyte safe .


public static function countWords($string)
    {
        $result = preg_split('/\s+/u', $string, null, PREG_SPLIT_NO_EMPTY);
        return !empty($result) ? count($result) : 0;
    }

public static function countWords ( $ string ) { $ result = preg_split ( '/\s+/u' , $ string , null , PREG_SPLIT_NO_EMPTY ) ; return ! empty ( $ result ) ? count ( $ result ) : 0 ; }

Counts words in a string.

@param string $string
@return int