protected static function getObjectClassName($object)
    {
        $nameGetters = [
            \ReflectionClass::class => 'getName()',
            \ReflectionMethod::class => 'class',
            \ReflectionProperty::class => 'class',
        ];
        foreach ($nameGetters as $class => $getter) {
            if ($object instanceof $class) {
                $isMethod = substr($getter, -2) === '()';
                if ($isMethod) {
                    $getter = substr($getter, 0, -2);
                    return call_user_func([$object, $getter]);
                }
                return $object->$getter;
            }
        }
        return get_class($object);
    }

protected static function getObjectClassName ( $ object ) { $ nameGetters = [ \ ReflectionClass :: class => 'getName()' , \ ReflectionMethod :: class => 'class' , \ ReflectionProperty :: class => 'class' , ] ; foreach ( $ nameGetters as $ class => $ getter ) { if ( $ object instanceof $ class ) { $ isMethod = substr ( $ getter , - 2 ) === '()' ; if ( $ isMethod ) { $ getter = substr ( $ getter , 0 , - 2 ) ; return call_user_func ( [ $ object , $ getter ] ) ; } return $ object -> $ getter ; } } return get_class ( $ object ) ; }

Get class name of object or its reflection
@param object $object
@return mixed|string


protected static function parseDocCommentSummary($reflection)
    {
        $docLines = preg_split('~\R~u', $reflection->getDocComment());
        if (isset($docLines[1])) {
            return trim($docLines[1], "\t *");
        }

        return '';
    }

protected
static
function
parseDocCommentSummary
(
$
reflection
)
{
$
docLines
=
preg_split
(
'~\R~u'
,
$
reflection
->
getDocComment
(
)
)
;
if
(
isset
(
$
docLines
[
1
]
)
)
{
return
trim
(
$
docLines
[
1
]
,
"\t *"
)
;
}
return
''
;
}

Returns the first line of PHPDoc block.

@param \ReflectionClass|\ReflectionMethod|\ReflectionProperty  $reflection
@return string

Returns the first line of PHPDoc block .


protected static function getClassDoc($object, $parseMethod = 'parseDocCommentSummary')
    {
        try {
            $reflection = new \ReflectionClass($object);
            $docData = static::$parseMethod($reflection);
        } catch (\ReflectionException $exception) {
            $docData = null;
        }
        return $docData;
    }

protected static function getClassDoc ( $ object , $ parseMethod = 'parseDocCommentSummary' ) { try { $ reflection = new \ ReflectionClass ( $ object ) ; $ docData = static :: $ parseMethod ( $ reflection ) ; } catch ( \ ReflectionException $ exception ) { $ docData = null ; } return $ docData ; }

Get class PHPDoc parsed
@param object $object
@param string $parseMethod
@return string|array|null


protected static function getMethodPropertyDoc($method, $object = null, $type = self::REFLECTION_METHOD, $parseMethod = self::DOC_COMMENT_SHORT)
    {
        try {
            //Method is already a \ReflectionMethod|\ReflectionProperty
            if ($method instanceof \ReflectionMethod || $method instanceof \ReflectionProperty) {
                $reflection = $method;
            //Method is string
            } else {
                //Check that object is not a \ReflectionClass
                $object = $object instanceof \ReflectionClass ? $object->getName() : $object;
                $reflection = $type === static::REFLECTION_METHOD
                    ? new \ReflectionMethod($object, $method)
                    : new \ReflectionProperty($object, $method);
            }
            $docData = static::$parseMethod($reflection);
        } catch (\ReflectionException $exception) {
            $docData = null;
        }
        return $docData;
    }

Get method or property PHPDoc parsed
@param string|\ReflectionMethod|\ReflectionProperty $method
@param object|null                                  $object
@param string                                       $type
@param string                                       $parseMethod
@return string|array|null


public function initByConfig($key, $config)
    {
        if(empty($config))
        {
            throw new Exception('db config is empty');
        }
        $driver = 'Li\\'.ucfirst($config['driver']);

        if(!(isset($this->$key) && $this->$key instanceof $driver))
        {
            $this->$key =  new $driver($config);
        }

    }

public
function
initByConfig
(
$
key
,
$
config
)
{
if
(
empty
(
$
config
)
)
{
throw
new
Exception
(
'db config is empty'
)
;
}
$
driver
=
'Li\\'
.
ucfirst
(
$
config
[
'driver'
]
)
;
if
(
!
(
isset
(
$
this
->
$
key
)
&&
$
this
->
$
key
instanceof
$
driver
)
)
{
$
this
->
$
key
=
new
$
driver
(
$
config
)
;
}
}

init db instance by config
@param $key string the db index
@param $config mixed the config


private function _mapNameSpace($foundationClass)
    {
        if (isset($this->_nsMap[$foundationClass])) {
            return $this->_nsMap[$foundationClass];
        }

        return reset($this->_nsMap);
    }

private function _mapNameSpace ( $ foundationClass ) { if ( isset ( $ this -> _nsMap [ $ foundationClass ] ) ) { return $ this -> _nsMap [ $ foundationClass ] ; } return reset ( $ this -> _nsMap ) ; }

Accepts foundation class, maps to a FlashMessenger namespace
@param  string $foundationClass
@return string

Accepts foundation class maps to a FlashMessenger namespace


function _unIndent($str)
    {
        // remove leading newlines
        $str = preg_replace('/^[\r\n]+/', '', $str);
        // find whitespace at the beginning of the first line
        $indent_len = strspn($str, " \t");
        $indent = substr($str, 0, $indent_len);
        $data = '';
        // remove the same amount of whitespace from following lines
        foreach (explode("\n", $str) as $line) {
            if (substr($line, 0, $indent_len) == $indent) {
                $data .= substr($line, $indent_len) . "\n";
            } else {
                $data .= $line . "\n";
            }
        }
        return $data;
    }

Unindent given string

@param string $str The string that has to be unindented.
@return string
@access private


function postProcess($data, $element)
    {
        if ($element == 'notes') {
            return trim($this->_unIndent($data));
        }
        return trim($data);
    }

function postProcess ( $ data , $ element ) { if ( $ element == 'notes' ) { return trim ( $ this -> _unIndent ( $ data ) ) ; } return trim ( $ data ) ; }

post-process data

@param string $data
@param string $element element name


private function extractPhotoArray($source)
    {
        if ($source->stat == 'fail') {
            return;
        }

        $data  = &$source->photo;

        $photo                     = [];
        $photo['id']               = $data->id;
        $photo['title']            = $data->title->_content;
        $photo['description']      = $data->description->_content;
        $photo['url']              = $data->urls->url[0]->_content;
        $photo['created']          = (string) $data->dates->posted;
        $photo['views']            = $data->views;
        $images                    = $this->fetchImages($photo['id']);
        $photo['source']           = $images[1];
        $photo['source_thumbnail'] = $images[0];

        return $photo;

    }

private function extractPhotoArray ( $ source ) { if ( $ source -> stat == 'fail' ) { return ; } $ data = & $ source -> photo ; $ photo = [ ] ; $ photo [ 'id' ] = $ data -> id ; $ photo [ 'title' ] = $ data -> title -> _content ; $ photo [ 'description' ] = $ data -> description -> _content ; $ photo [ 'url' ] = $ data -> urls -> url [ 0 ] -> _content ; $ photo [ 'created' ] = ( string ) $ data -> dates -> posted ; $ photo [ 'views' ] = $ data -> views ; $ images = $ this -> fetchImages ( $ photo [ 'id' ] ) ; $ photo [ 'source' ] = $ images [ 1 ] ; $ photo [ 'source_thumbnail' ] = $ images [ 0 ] ; return $ photo ; }

Specific data are stored into an array and are returned, when it receive an failure, returns null.

@param  object $data
@return array|null

Specific data are stored into an array and are returned when it receive an failure returns null .


private function fetchImages($photoId)
    {
        $query = array_merge(
            $this->defaultQuery,
            [
                'method'   => 'flickr.photos.getSizes',
                'photo_id' => $photoId,
            ]
        );

        $body = $this->newRequest()
            ->setQuery($query)
            ->GET()
            ->getBody('array');

        return $this->extractImagesArray($body);

    }

private function fetchImages ( $ photoId ) { $ query = array_merge ( $ this -> defaultQuery , [ 'method' => 'flickr.photos.getSizes' , 'photo_id' => $ photoId , ] ) ; $ body = $ this -> newRequest ( ) -> setQuery ( $ query ) -> GET ( ) -> getBody ( 'array' ) ; return $ this -> extractImagesArray ( $ body ) ; }

This function makes the request to get images sources from a photo and returns them as an array.

@param  string $photoId
@return array

This function makes the request to get images sources from a photo and returns them as an array .


private function extractImagesArray($source)
    {
        $sizes  = array_get($source, 'sizes.size');
        $images = array_where($sizes, function ($key, $value) {
            return in_array($value['label'], ['Original', 'Small 320']);
        });

        return array_fetch($images, 'source');

    }

private
function
extractImagesArray
(
$
source
)
{
$
sizes
=
array_get
(
$
source
,
'sizes.size'
)
;
$
images
=
array_where
(
$
sizes
,
function
(
$
key
,
$
value
)
{
return
in_array
(
$
value
[
'label'
]
,
[
'Original'
,
'Small 320'
]
)
;
}
)
;
return
array_fetch
(
$
images
,
'source'
)
;
}

Extracts an array of images from the photo array and returns them.

@param  array $source
@return array

Extracts an array of images from the photo array and returns them .


protected function findPlaceholderStartPos($path) {
        $brFgPos = strpos($path, '{');
        $brSqPos = strpos($path, '[');
        if ($brFgPos === false && $brSqPos === false) {
            return false;
        }
        $len = strlen($path);
        $positions = [
            $brFgPos !== false ? $brFgPos : $len,
            $brSqPos !== false ? $brSqPos : $len,
        ];
        return min($positions);
    }

protected function findPlaceholderStartPos ( $ path ) { $ brFgPos = strpos ( $ path , '{' ) ; $ brSqPos = strpos ( $ path , '[' ) ; if ( $ brFgPos === false && $ brSqPos === false ) { return false ; } $ len = strlen ( $ path ) ; $ positions = [ $ brFgPos !== false ? $ brFgPos : $ len , $ brSqPos !== false ? $ brSqPos : $ len , ] ; return min ( $ positions ) ; }

Finds a position with first placeholder
@param string $path
@return bool|int


protected function buildRoutePath($path, &$params) {
        $path = $this->replacePlaceholders($path, $params);
        $path = $this->searchInRouter($path, $params);
        return $path;
    }

protected function buildRoutePath ( $ path , & $ params ) { $ path = $ this -> replacePlaceholders ( $ path , $ params ) ; $ path = $ this -> searchInRouter ( $ path , $ params ) ; return $ path ; }

Build route path with placeholders replace and searching in router paths
@param string $path
@param array  $params
@return string


protected function searchInRouter($path, &$params) {
        if (isset(\Reaction::$app->router->routePaths[$path])) {
            $paramsKeys = array_keys($params);
            $routes = \Reaction::$app->router->routePaths[$path];
            foreach ($routes as $routeData) {
                $intersect = array_intersect($paramsKeys, $routeData['params']);
                if (count($intersect) === count($routeData['params'])) {
                    $path = $this->replacePlaceholders($routeData['exp'], $params);
                    break;
                }
            }
            return $path;
        }
        return $path;
    }

protected function searchInRouter ( $ path , & $ params ) { if ( isset ( \ Reaction :: $ app -> router -> routePaths [ $ path ] ) ) { $ paramsKeys = array_keys ( $ params ) ; $ routes = \ Reaction :: $ app -> router -> routePaths [ $ path ] ; foreach ( $ routes as $ routeData ) { $ intersect = array_intersect ( $ paramsKeys , $ routeData [ 'params' ] ) ; if ( count ( $ intersect ) === count ( $ routeData [ 'params' ] ) ) { $ path = $ this -> replacePlaceholders ( $ routeData [ 'exp' ] , $ params ) ; break ; } } return $ path ; } return $ path ; }

Search in router for predefined paths
@param string $path
@param array  $params
@return string


protected function replacePlaceholders($path, &$params) {
        if (strpos($path, '{') === false) {
            return $path;
        }
        $path = preg_replace_callback('/(\{([a-zA-Z0-9]+)\})/i', function($matches) use (&$params) {
            $match = $matches[1];
            $key = $matches[2];
            if (!isset($params[$key])) {
                return $match;
            }
            $replace = $params[$key];
            unset($params[$key]);
            return $replace;
        }, $path);
        return $path;
    }

protected function replacePlaceholders ( $ path , & $ params ) { if ( strpos ( $ path , '{' ) === false ) { return $ path ; } $ path = preg_replace_callback ( '/(\{([a-zA-Z0-9]+)\})/i' , function ( $ matches ) use ( & $ params ) { $ match = $ matches [ 1 ] ; $ key = $ matches [ 2 ] ; if ( ! isset ( $ params [ $ key ] ) ) { return $ match ; } $ replace = $ params [ $ key ] ; unset ( $ params [ $ key ] ) ; return $ replace ; } , $ path ) ; return $ path ; }

Replace placeholders in path
@param string $path
@param array  $params
@return string


public function init()
    {
        parent::init();
        if ($this->sourceLanguage === null) {
            $this->sourceLanguage = Reaction::$app->sourceLanguage;
        }
    }

public function init ( ) { parent :: init ( ) ; if ( $ this -> sourceLanguage === null ) { $ this -> sourceLanguage = Reaction :: $ app -> sourceLanguage ; } }


public function preloadMessages($category, $languages = [])
    {
        if ($category === '*') {
            $categoriesFind = $this->findAllCategories();
        } else {
            $categoriesFind = strpos($category, '*') > 0 ? $this->findCategoriesByPattern($category) : resolve([$category]);
        }
        return $categoriesFind
            ->otherwise(function() { return []; })
            ->then(function($categories) use ($languages) {
                $promises = [];
                foreach ($categories as $category) {
                    foreach ($languages as $language) {
                        $key = $language . '/' . $category;
                        $promises[$key] = $this->loadMessages($category, $language);
                    }
                }
                if (empty($promises)) {
                    return [];
                }
                return all($promises)
                    ->then(function($results) {
                        $this->_messages = Reaction\Helpers\ArrayHelper::merge($this->_messages, $results);
                        return $results;
                    });
            });
    }

public function preloadMessages ( $ category , $ languages = [ ] ) { if ( $ category === '*' ) { $ categoriesFind = $ this -> findAllCategories ( ) ; } else { $ categoriesFind = strpos ( $ category , '*' ) > 0 ? $ this -> findCategoriesByPattern ( $ category ) : resolve ( [ $ category ] ) ; } return $ categoriesFind -> otherwise ( function ( ) { return [ ] ; } ) -> then ( function ( $ categories ) use ( $ languages ) { $ promises = [ ] ; foreach ( $ categories as $ category ) { foreach ( $ languages as $ language ) { $ key = $ language . '/' . $ category ; $ promises [ $ key ] = $ this -> loadMessages ( $ category , $ language ) ; } } if ( empty ( $ promises ) ) { return [ ] ; } return all ( $ promises ) -> then ( function ( $ results ) { $ this -> _messages = Reaction \ Helpers \ ArrayHelper :: merge ( $ this -> _messages , $ results ) ; return $ results ; } ) ; } ) ; }

Preload all messages from source
@param string $category Category or wildcard
@param array $languages Languages used to preload
@return ExtendedPromiseInterface


protected function findCategoriesByPattern($pattern)
    {
        return $this->findAllCategories()
            ->then(function($categories) use ($pattern) {
                $matches = [];
                foreach ($categories as $category) {
                    if (Reaction\Helpers\StringHelper::matchWildcard($pattern, $category)) {
                        $matches[] = $category;
                    }
                }
                return $matches;
            });
    }

protected function findCategoriesByPattern ( $ pattern ) { return $ this -> findAllCategories ( ) -> then ( function ( $ categories ) use ( $ pattern ) { $ matches = [ ] ; foreach ( $ categories as $ category ) { if ( Reaction \ Helpers \ StringHelper :: matchWildcard ( $ pattern , $ category ) ) { $ matches [ ] = $ category ; } } return $ matches ; } ) ; }

Find categories by string pattern|wildcard
@param string $pattern
@return ExtendedPromiseInterface


public function __isset(string $name): bool
    {
        $methodName = str_replace('_', '', ucwords($name, '_'));
        $methodName = 'isset' . $methodName;

        if (method_exists($this, $methodName)) {
            return $this->$methodName();
        }

        return property_exists($this, $name);
    }

public function __isset ( string $ name ) : bool { $ methodName = str_replace ( '_' , '' , ucwords ( $ name , '_' ) ) ; $ methodName = 'isset' . $ methodName ; if ( method_exists ( $ this , $ methodName ) ) { return $ this -> $ methodName ( ) ; } return property_exists ( $ this , $ name ) ; }

Check if a property is set.

@param string $name The property to check

@return bool


public function sendExceptionResponse($exception): void
    {
        if (! headers_sent()) {
            if ($exception instanceof HttpException) {
                header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));

                foreach ($exception->getHeaders() as $name => $value) {
                    header($name . ': ' . $value, false);
                }
            }

            header('Content-Type: text/html; charset=' . $this->charset);
        }

        echo $this->html($this->getContent($exception), $this->getStylesheet());
    }

public
function
sendExceptionResponse
(
$
exception
)
:
void
{
if
(
!
headers_sent
(
)
)
{
if
(
$
exception
instanceof
HttpException
)
{
header
(
sprintf
(
'HTTP/1.0 %s'
,
$
exception
->
getStatusCode
(
)
)
)
;
foreach
(
$
exception
->
getHeaders
(
)
as
$
name
=>
$
value
)
{
header
(
$
name
.
': '
.
$
value
,
false
)
;
}
}
header
(
'Content-Type: text/html; charset='
.
$
this
->
charset
)
;
}
echo
$
this
->
html
(
$
this
->
getContent
(
$
exception
)
,
$
this
->
getStylesheet
(
)
)
;
}

Send response.

@param \Throwable $exception

@return void


public function getContent(Throwable $exception): string
    {
        $title = 'Whoops, looks like something went wrong.';

        if (
            $exception instanceof HttpException
            && $exception->getStatusCode() === 404
        ) {
            $title = 'Sorry, the page you are looking for could not be found.';
        }

        $content = '';

        if ($this->displayErrors) {
            try {
                $exceptions = [
                    $exception,
                ];
                $e          = $exception;

                while ($e = $e->getPrevious()) {
                    $exceptions[] = $e;
                }

                $count = \count($exceptions);
                $total = $count;

                /**
                 * @var int
                 * @var \Throwable $e
                 */
                foreach ($exceptions as $position => $e) {
                    $ind     = $count - $position;
                    $class   = $this->formatClass(\get_class($e));
                    $message = nl2br($this->escapeHtml($e->getMessage()));
                    $content .= sprintf(
                        <<<'EOF'

                            %d/%d
                            %s%s:
                            %s

EOF
                        ,
                        $ind,
                        $total,
                        $class,
                        $this->formatPath(
                            $e->getTrace()[0]['file'] ?? 'Unknown file',
                            $e->getTrace()[0]['line'] ?? 0
                        ),
                        $message
                    );

                    foreach ($e->getTrace() as $trace) {
                        $traceClass    = $trace['class'] ?? '';
                        $traceArgs     = $trace['args'] ?? [];
                        $traceType     = $trace['type'] ?? '';
                        $traceFunction = $trace['function'] ?? '';

                        $content .= '
';

                        if ($trace['function']) {
                            $content .= sprintf(
                                'at %s%s%s(%s)',
                                $this->formatClass($traceClass),
                                $traceType,
                                $traceFunction,
                                $this->formatArgs($traceArgs)
                            );
                        }

                        if (isset($trace['file'], $trace['line'])) {
                            $content .= $this->formatPath(
                                $trace['file'],
                                $trace['line']
                            );
                        }

                        $content .= "
\n";
                    }

                    $content .= "
\n
\n";
                }
            } catch (Exception $e) {
                // Something nasty happened and we cannot throw an exception anymore
                $title = sprintf(
                    'Exception thrown when handling an exception (%s: %s)',
                    \get_class($e),
                    $this->escapeHtml($e->getMessage())
                );
            }
        }

        return <<<EOF

$title

                $content

EOF;
    }

/**
                 * @var int
                 * @var \Throwable $e
                 */

<<<EOF

$title

                $content

EOF

Gets the HTML content associated with the given exception.

@param \Throwable $exception A FlattenException instance

@return string The content as a string

Gets the HTML content associated with the given exception .


protected function formatPath(string $path, int $line): string
    {
        $path = $this->escapeHtml($path);
        $file = preg_match('#[^/\\\\]*$#', $path, $file)
            ? $file[0]
            : $path;

        if ($linkFormat = $this->fileLinkFormat) {
            $link = strtr(
                $this->escapeHtml($linkFormat),
                ['%f' => $path, '%l' => $line]
            );

            return sprintf(
                ' in %s line %d',
                $link,
                $file,
                $line
            );
        }

        return sprintf(
            ' in %s line %d',
            $path,
            $file,
            $line
        );
    }

Format path.

@param string $path
@param int    $line

@return string


protected function formatArgs(array $args): string
    {
        $result = [];

        foreach ($args as $key => $item) {
            if (\is_object($item)) {
                $formattedValue = sprintf(
                    'object(%s)',
                    $this->formatClass(\get_class($item))
                );
            } elseif (\is_array($item)) {
                $formattedValue = sprintf(
                    'array(%s)',
                    $this->formatArgs($item)
                );
            } elseif (\is_string($item)) {
                $formattedValue = sprintf("'%s'", $this->escapeHtml($item));
            } elseif (null === $item) {
                $formattedValue = 'null';
            } elseif (\is_bool($item)) {
                $formattedValue = ''
                    . strtolower(var_export($item, true))
                    . '';
            } elseif (\is_resource($item)) {
                $formattedValue = 'resource';
            } else {
                $formattedValue = str_replace(
                    "\n",
                    '',
                    var_export($this->escapeHtml((string) $item), true)
                );
            }

            $result[] = \is_int($key)
                ? $formattedValue
                : sprintf("'%s' => %s", $key, $formattedValue);
        }

        return implode(', ', $result);
    }

protected
function
formatArgs
(
array
$
args
)
:
string
{
$
result
=
[
]
;
foreach
(
$
args
as
$
key
=>
$
item
)
{
if
(
\
is_object
(
$
item
)
)
{
$
formattedValue
=
sprintf
(
'object(%s)'
,
$
this
->
formatClass
(
\
get_class
(
$
item
)
)
)
;
}
elseif
(
\
is_array
(
$
item
)
)
{
$
formattedValue
=
sprintf
(
'array(%s)'
,
$
this
->
formatArgs
(
$
item
)
)
;
}
elseif
(
\
is_string
(
$
item
)
)
{
$
formattedValue
=
sprintf
(
"'%s'"
,
$
this
->
escapeHtml
(
$
item
)
)
;
}
elseif
(
===
$
item
)
{
$
formattedValue
=
'null'
;
}
elseif
(
\
is_bool
(
$
item
)
)
{
$
formattedValue
=
''
.
strtolower
(
var_export
(
$
item
,
true
)
)
.
''
;
}
elseif
(
\
is_resource
(
$
item
)
)
{
$
formattedValue
=
'resource'
;
}
else
{
$
formattedValue
=
str_replace
(
"\n"
,
''
,
var_export
(
$
this
->
escapeHtml
(
(
string
)
$
item
)
,
true
)
)
;
}
$
result
[
]
=
\
is_int
(
$
key
)
$
formattedValue
:
sprintf
(
"'%s' => %s"
,
$
key
,
$
formattedValue
)
;
}
return
implode
(
', '
,
$
result
)
;
}

Formats an array as a string.

@param array $args The argument array

@return string


protected function escapeHtml(string $str): string
    {
        return htmlspecialchars(
            $str,
            ENT_QUOTES | ENT_SUBSTITUTE,
            $this->charset
        );
    }

protected function escapeHtml ( string $ str ) : string { return htmlspecialchars ( $ str , ENT_QUOTES | ENT_SUBSTITUTE , $ this -> charset ) ; }

Escape HTML.

@param string $str

@return string


public function with(array $data, array $rules) {
        $this->validator = $this->factory->make($data, $rules);
    }

public function with ( array $ data , array $ rules ) { $ this -> validator = $ this -> factory -> make ( $ data , $ rules ) ; }

Sets the data to be validated.

@param array $data
@param array $rules
@return mixed


public function transforms($string)
    {
        if (!is_string($string)) {
            throw new InvalidArgumentException('A string is required');
        }
        if (false == preg_match('#^[a-zA-Z0-9]+$#', $string)) {
            throw new InvalidArgumentException('A valid string is required');
        }
        $inputs = [];
        $splitted = str_split($string);

        foreach ($splitted as $value) {
            $inputs[] = new Input($value);
        }

        return $inputs;
    }

public
function
transforms
(
$
string
)
{
if
(
!
is_string
(
$
string
)
)
{
throw
new
InvalidArgumentException
(
'A string is required'
)
;
}
if
(
false
==
preg_match
(
'#^[a-zA-Z0-9]+$#'
,
$
string
)
)
{
throw
new
InvalidArgumentException
(
'A valid string is required'
)
;
}
$
inputs
=
[
]
;
$
splitted
=
str_split
(
$
string
)
;
foreach
(
$
splitted
as
$
value
)
{
$
inputs
[
]
=
new
Input
(
$
value
)
;
}
return
$
inputs
;
}

Transform a string to a collection of Input.

@param string $string

@return InputInterface[]

Transform a string to a collection of Input .


public function handleDisconnect(ConnectionInterface $connection, LoggerInterface $logger)
    {
        $timers = $this->getTimers();
        if ($timers->contains($connection)) {
            $this->getLogger()->debug('Detaching activity listener for disconnected connection');
            $timers->offsetGet($connection)->cancel();
            $timers->detach($connection);
        }
    }

Forget about a connection on disconnect.

@param \Phergie\Irc\ConnectionInterface $connection
@param \Psr\Log\LoggerInterface $logger

Forget about a connection on disconnect .


public function handleReceived(Event $event, Queue $queue)
    {
        $connection = $event->getConnection();
        $timers = $this->getTimers();
        if ($timers->contains($connection)) {
            $timers->offsetGet($connection)->cancel();
        } else {
            $this->getLogger()->debug('Attaching activity listener for connection');
        }

        $timer = $this->getLoop()->addTimer($this->wait, array($this, 'callbackPhoneHome'));
        $timer->setData($connection);
        $timers->attach($connection, $timer);
    }

Neutralise the existing timer, if present, and create a new timer.

@param \Phergie\Irc\Event\EventInterface $event
@param \Phergie\Irc\Bot\React\EventQueueInterface $queue

Neutralise the existing timer if present and create a new timer .


public function callbackPhoneHome(TimerInterface $caller)
    {
        $connection = $caller->getData();

        $this->getLogger()->debug('Inactivity period reached, sending CTCP PING');
        $this->getEventQueueFactory()->getEventQueue($connection)->ctcpPing($connection->getNickname(), time());

        $timer = $this->getLoop()->addTimer($this->timeout, array($this, 'callbackGrimReaper'));
        $timer->setData($connection);
        $this->getTimers()->attach($connection, $timer);
    }

Callback called after the inactivity period is reached.

@param \React\EventLoop\Timer\TimerInterface $caller

Callback called after the inactivity period is reached .


public function callbackGrimReaper(TimerInterface $caller)
    {
        $connection = $caller->getData();

        $this->getLogger()->debug('CTCP PING timeout reached, closing connection');
        $this->getEventQueueFactory()->getEventQueue($connection)->ircQuit();
    }

Callback called after the CTCP PING timeout is reached.

@param \React\EventLoop\Timer\TimerInterface $caller

Callback called after the CTCP PING timeout is reached .


protected function getProxyCommandHandler(ServiceLocatorInterface $serviceLocator, string $key): object
    {
        $eventStore = $serviceLocator->getService(EventStoreInterface::class);
        $eventPublisher = $serviceLocator->getService(EventPublisherInterface::class);
        $aggregate = $serviceLocator->getService($key);

        /**
         * @var EventStoreInterface            $eventStore
         * @var EventPublisherInterface        $eventPublisher
         * @var EventSourcedAggregateInterface $aggregate
         */
        return new ProxyCommandHandler(
            new EventStoreRepository($eventStore, $eventPublisher, $aggregate)
        );
    }

Get proxy command handler for aggregate.

@param ServiceLocatorInterface $serviceLocator
@param string                  $key
@return CommandHandlerInterface
@throws \ExtendsFramework\ServiceLocator\ServiceLocatorException

Get proxy command handler for aggregate .


public function cb_configAction()
    {
        $config = $this->getContainer()->get('config')->dump();
        $reflection_cb = new \ReflectionClass('\CarteBlanche\App\Kernel');
        $constants = $reflection_cb->getConstants();

        $mode_data = \CarteBlanche\CarteBlanche::getKernelMode(true);
        return array(self::$views_dir.'app_config', array(
            'title' => $this->trans('Application full config'),
            'debug' => isset($mode_data['debug']) ? $mode_data['debug'] : false,
            'constants'=>$constants,
            'config' => $config,
        ));
    }

public
function
cb_configAction
(
)
{
$
config
=
$
this
->
getContainer
(
)
->
get
(
'config'
)
->
dump
(
)
;
$
reflection_cb
=
new
\
ReflectionClass
(
'\CarteBlanche\App\Kernel'
)
;
$
constants
=
$
reflection_cb
->
getConstants
(
)
;
$
mode_data
=
\
CarteBlanche
\
CarteBlanche
::
getKernelMode
(
true
)
;
return
array
(
self
::
$
views_dir
.
'app_config'
,
array
(
'title'
=>
$
this
->
trans
(
'Application full config'
)
,
'debug'
=>
isset
(
$
mode_data
[
'debug'
]
)
$
mode_data
[
'debug'
]
:
false
,
'constants'
=>
$
constants
,
'config'
=>
$
config
,
)
)
;
}

Page of application configuration

@return string The view content


final public function loadBundles()
    {
        $projectBundleConfig = [];
        if (is_readable($this->getConfigDir() . '/bundles.yml')) {
            $projectBundleConfig = Yaml::parse(
                file_get_contents($this->getConfigDir() . '/bundles.yml')
            );

            return $projectBundleConfig;
        }

        return $projectBundleConfig;
    }

final public function loadBundles ( ) { $ projectBundleConfig = [ ] ; if ( is_readable ( $ this -> getConfigDir ( ) . '/bundles.yml' ) ) { $ projectBundleConfig = Yaml :: parse ( file_get_contents ( $ this -> getConfigDir ( ) . '/bundles.yml' ) ) ; return $ projectBundleConfig ; } return $ projectBundleConfig ; }

Load bundles from project configuration

@return array|mixed
@throws \Symfony\Component\Yaml\Exception\ParseException


protected function loadMessages() {
		if ( $this->messages === null ) {
			$this->messages = array();
			foreach ( glob( "{$this->messageDirectory}/*.json" ) as $file ) {
				$lang = strtolower( substr( basename( $file ), 0, -5 ) );
				if ( $lang === 'qqq' ) {
					// Ignore message documentation
					continue;
				}

				if ( is_readable( $file ) ) {
					$json = file_get_contents( $file );
					if ( $json === false ) {
						$this->logger->error( 'Error reading file', array(
							'method' => __METHOD__,
							'file' => $file,
						) );
						continue;
					}

					$data = json_decode( $json, true );
					if ( $data === null ) {
						$this->logger->error( 'Error parsing json', array(
							'method' => __METHOD__,
							'file' => $file,
							'json_error' => json_last_error(),
						) );
						continue;
					}

					// Discard metadata
					unset( $data['@metadata'] );

					if ( empty( $data ) ) {
						// Ignore empty languages
						continue;
					}

					$this->messages[$lang] = $data;
				}
			}
		}
	}

protected
function
loadMessages
(
)
{
if
(
$
this
->
messages
===
)
{
$
this
->
messages
=
array
(
)
;
foreach
(
glob
(
"{$this->messageDirectory}/*.json"
)
as
$
file
)
{
$
lang
=
strtolower
(
substr
(
basename
(
$
file
)
,
0
,
5
)
)
;
if
(
$
lang
===
'qqq'
)
{
// Ignore message documentation
continue
;
}
if
(
is_readable
(
$
file
)
)
{
$
json
=
file_get_contents
(
$
file
)
;
if
(
$
json
===
false
)
{
$
this
->
logger
->
error
(
'Error reading file'
,
array
(
'method'
=>
__METHOD__
,
'file'
=>
$
file
,
)
)
;
continue
;
}
$
data
=
json_decode
(
$
json
,
true
)
;
if
(
$
data
===
)
{
$
this
->
logger
->
error
(
'Error parsing json'
,
array
(
'method'
=>
__METHOD__
,
'file'
=>
$
file
,
'json_error'
=>
json_last_error
(
)
,
)
)
;
continue
;
}
// Discard metadata
unset
(
$
data
[
'@metadata'
]
)
;
if
(
empty
(
$
data
)
)
{
// Ignore empty languages
continue
;
}
$
this
->
messages
[
$
lang
]
=
$
data
;
}
}
}
}


public function setHttpHeaders(array $inHttpHeaders, $inMerge=false) {
        if ($inMerge) {
            $this->__httpHeaders = array_merge($this->__httpHeaders, $inHttpHeaders);
        } else {
            $this->__httpHeaders = $inHttpHeaders;
        }
        return $this;
    }

public function setHttpHeaders ( array $ inHttpHeaders , $ inMerge = false ) { if ( $ inMerge ) { $ this -> __httpHeaders = array_merge ( $ this -> __httpHeaders , $ inHttpHeaders ) ; } else { $ this -> __httpHeaders = $ inHttpHeaders ; } return $ this ; }

Set the HTTP headers for the request.

@param array $inHttpHeaders The HTTP headers to set.
See {@url https://developer.mozilla.org/fr/docs/HTTP/Headers} for the list of HTTP headers.
@param bool $inMerge This parameter determines whether the given list of headers should be merged to the existing one or not.
If the value if false, then the given list of headers will replace the existing one.
Otherwise, the given list of headers will be merged into the existing one.
@return $this


public function setServerCgiEnvironmentVariables(array $inServerCgiEnvironmentVariables, $inMerge=false) {
        if ($inMerge) {
            $this->__serverCgiEnvironmentVariables = array_merge($this->__serverCgiEnvironmentVariables, $inServerCgiEnvironmentVariables);
        } else {
            $this->__serverCgiEnvironmentVariables = $inServerCgiEnvironmentVariables;
        }
        return $this;
    }

public function setServerCgiEnvironmentVariables ( array $ inServerCgiEnvironmentVariables , $ inMerge = false ) { if ( $ inMerge ) { $ this -> __serverCgiEnvironmentVariables = array_merge ( $ this -> __serverCgiEnvironmentVariables , $ inServerCgiEnvironmentVariables ) ; } else { $ this -> __serverCgiEnvironmentVariables = $ inServerCgiEnvironmentVariables ; } return $ this ; }

Set the server CGI environment variables.

@param array $inServerCgiEnvironmentVariables
See {@url http://php.net/manual/fr/reserved.variables.server.php} for the list of variables.
@param bool $inMerge This parameter determines whether the given list of variables should be merged to the existing one or not.
If the value if false, then the given list of variables will replace the existing one.
Otherwise, the given list of variables will be merged into the existing one.
@return $this

Set the server CGI environment variables .


public function post($inRequestUri, $inPostParameters=[]) {

        // Prepare the content of the request's body.
        $bodyContent = [];
        foreach ($inPostParameters as $_name => $_value) {
            $bodyContent[] = $_name . '=' . urlencode($_value);
        }
        $bodyContent = implode('&', $bodyContent);

        // Prepare the request's headers.
        if (! array_key_exists('Content-Type', $this->__httpHeaders)) {
            $this->__httpHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
        }
        if (! array_key_exists('Content-Length', $this->__httpHeaders)) {
            $this->__httpHeaders['Content-Length'] = strlen($bodyContent);
        }

        return $this->request('POST', $inRequestUri, '', $bodyContent);
    }

Execute a POST request.

@param string $inRequestUri The request URI (example: "/hello/toto").
@param array $inPostParameters List of parameters to pass.
@return string The content of the standard output.
@see \Slim\Http\Request::getParsedBody for a detailed description of how the request body is parsed.
The parsing relies on the value of the 'Content-Type' header.
It should be "application/x-www-form-urlencoded".
@note Please keep in mind that:
- HTTP headers can be configured through the method SoftRequester::setHttpHeaders().
- Server CGI environment variables can be configured through the method SoftRequester::setServerCgiEnvironmentVariables().
@see Requester::setHttpHeaders()
@see Requester::setServerCgiEnvironmentVariables()


public function jsonRpc($inRequestUri, $inParameters=[]) {
        $bodyContent = json_encode($inParameters);

        // Prepare the request's headers.
        if (! array_key_exists('Content-Type', $this->__httpHeaders)) {
            $this->__httpHeaders['Content-Type'] = 'application/jsonrequest';
        }
        if (! array_key_exists('Accept', $this->__httpHeaders)) {
            $this->__httpHeaders['Accept'] = 'application/jsonrequest';
        }
        if (! array_key_exists('Content-Length', $this->__httpHeaders)) {
            $this->__httpHeaders['Content-Length'] = strlen($bodyContent);
        }
        return $this->request('POST', $inRequestUri, '', $bodyContent);
    }

public
function
jsonRpc
(
$
inRequestUri
,
$
inParameters
=
[
]
)
{
$
bodyContent
=
json_encode
(
$
inParameters
)
;
// Prepare the request's headers.
if
(
!
array_key_exists
(
'Content-Type'
,
$
this
->
__httpHeaders
)
)
{
$
this
->
__httpHeaders
[
'Content-Type'
]
=
'application/jsonrequest'
;
}
if
(
!
array_key_exists
(
'Accept'
,
$
this
->
__httpHeaders
)
)
{
$
this
->
__httpHeaders
[
'Accept'
]
=
'application/jsonrequest'
;
}
if
(
!
array_key_exists
(
'Content-Length'
,
$
this
->
__httpHeaders
)
)
{
$
this
->
__httpHeaders
[
'Content-Length'
]
=
strlen
(
$
bodyContent
)
;
}
return
$
this
->
request
(
'POST'
,
$
inRequestUri
,
''
,
$
bodyContent
)
;
}

Send a JSON RPC request.

@param string $inRequestUri The request URI (example: "/hello/toto").
@param array $inParameters The structure that will be converted into JSON, and that contains the data to send.
@return string string The content of the standard output.
@note Please keep in mind that:
- HTTP headers can be configured through the method SoftRequester::setHttpHeaders().
- Server CGI environment variables can be configured through the method SoftRequester::setServerCgiEnvironmentVariables().
@see Requester::setHttpHeaders()
@see Requester::setServerCgiEnvironmentVariables()


public function connect()
    {
/*
        $this->db = new \SQLiteDatabase(
            $this->db_name,
            isset($this->db_options['chmod']) ? $this->db_options['chmod'] : 0644,
            $err
        );
        if ($err) throw new ErrorException(
            sprintf('Can not connect or create SQLite database "%s" [%s]!', $this->db_name, $err)
        );
*/
        try {
            $this->db = new \SQLite3($this->db_name);
        } catch (\Exception $e) {
            throw $e;
        }

        $this->db_name = str_replace(array(
            CarteBlanche::getPath('root_path'),
            CarteBlanche::getPath('db_dir')
        ), '', $this->db_name);
        return $this->db;
    }


static function escape($str = null, $double_quotes = false)
    {
        return sqlite_escape_string(
            true===$double_quotes ? str_replace('"', '""', $str) : $str
        );
    }

static function escape ( $ str = null , $ double_quotes = false ) { return sqlite_escape_string ( true === $ double_quotes ? str_replace ( '"' , '""' , $ str ) : $ str ) ; }

Escape a string using the internal PHP sqlite function

@param string $str The string to escape
@param bool $double_quotes If true, the double-quotes will be doubled for escaping
@return string The escaped string
@see http://www.php.net/manual/en/function.sqlite-escape-string.php


public function init()
    {
        if ($this->sourcePath !== null) {
            $this->sourcePath = rtrim(Reaction::$app->getAlias($this->sourcePath), '/\\');
        }
        if ($this->basePath !== null) {
            $this->basePath = rtrim(Reaction::$app->getAlias($this->basePath), '/\\');
        }
        if ($this->baseUrl !== null) {
            $this->baseUrl = rtrim(Reaction::$app->getAlias($this->baseUrl), '/');
        }
    }

public function init ( ) { if ( $ this -> sourcePath !== null ) { $ this -> sourcePath = rtrim ( Reaction :: $ app -> getAlias ( $ this -> sourcePath ) , '/\\' ) ; } if ( $ this -> basePath !== null ) { $ this -> basePath = rtrim ( Reaction :: $ app -> getAlias ( $ this -> basePath ) , '/\\' ) ; } if ( $ this -> baseUrl !== null ) { $ this -> baseUrl = rtrim ( Reaction :: $ app -> getAlias ( $ this -> baseUrl ) , '/' ) ; } }

Initializes the bundle.
If you override this method, make sure you call the parent implementation in the last.

Initializes the bundle . If you override this method make sure you call the parent implementation in the last .


public function hasSlugField()
    {
        foreach($this->_table_structure as $_field=>$field_structure) {
            if (isset($field_structure['slug']) && $field_structure['slug']===true) {
                return true;
            }
        }
        return false;
    }

public function hasSlugField ( ) { foreach ( $ this -> _table_structure as $ _field => $ field_structure ) { if ( isset ( $ field_structure [ 'slug' ] ) && $ field_structure [ 'slug' ] === true ) { return true ; } } return false ; }

Does the table have a slug field

@return bool True if the model has a slug field


public function getSpecialFields($field, $value = true)
    {
        $fields = array();
        foreach($this->_table_structure as $_field=>$field_structure) {
            if (isset($field_structure[$field]) && $field_structure[$field]===$value) {
                $fields[] = $_field;
            }
        }
        return $fields;
    }

public function getSpecialFields ( $ field , $ value = true ) { $ fields = array ( ) ; foreach ( $ this -> _table_structure as $ _field => $ field_structure ) { if ( isset ( $ field_structure [ $ field ] ) && $ field_structure [ $ field ] === $ value ) { $ fields [ ] = $ _field ; } } return $ fields ; }

Gets a table special field if found

@param string $field The field name to search
@param mixed $value The corresponding value of the field
@return array The special search fields list if found


public function getFieldsByType($type)
    {
        $fields = array();
        foreach($this->_table_structure as $_field=>$field_structure) {
            if (isset($field_structure['type']) && $field_structure['type']==$type) {
                $fields[] = $_field;
            }
        }
        return $fields;
    }

public function getFieldsByType ( $ type ) { $ fields = array ( ) ; foreach ( $ this -> _table_structure as $ _field => $ field_structure ) { if ( isset ( $ field_structure [ 'type' ] ) && $ field_structure [ 'type' ] == $ type ) { $ fields [ ] = $ _field ; } } return $ fields ; }

Gets a list of fields by their type

@param string $type The field's type to search
@return array The array of the fields matching the type if found


public function date($time = null)
    {
        if (!isset($time)) {
            $time = time();
        } elseif (!is_numeric($time) && (-1 === $time = strtotime($time))) {
            return false;
        }

        // RFC822 or RFC850
        $format = ini_get('y2k_compliance') ? 'D, d M Y' : 'l, d-M-y';

        return gmdate($format .' H:i:s \G\M\T', $time);
    }

public
function
date
(
$
time
=
)
{
if
(
!
isset
(
$
time
)
)
{
$
time
=
time
(
)
;
}
elseif
(
!
is_numeric
(
$
time
)
&&
(
1
===
$
time
=
strtotime
(
$
time
)
)
)
{
return
false
;
}
// RFC822 or RFC850
$
format
=
ini_get
(
'y2k_compliance'
)
'D, d M Y'
:
'l, d-M-y'
;
return
gmdate
(
$
format
.
' H:i:s \G\M\T'
,
$
time
)
;
}

Formats a RFC compliant GMT date HTTP header.  This function honors the
"y2k_compliance" php.ini directive and formats the GMT date corresponding
to either RFC850 or RFC822.

@param mixed $time unix timestamp or date (default = current time)

@return string|boolean GMT date string, or FALSE for an invalid
$time parameter

Formats a RFC compliant GMT date HTTP header . This function honors the y2k_compliance php . ini directive and formats the GMT date corresponding to either RFC850 or RFC822 .


public function negotiateLanguage($supported, $default = 'en-US')
    {
        $supp = array();
        foreach ($supported as $lang => $isSupported) {
            if ($isSupported) {
                $supp[strtolower($lang)] = $lang;
            }
        }

        if (!count($supp)) {
            return $default;
        }

        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $match = $this->matchAccept(
                $_SERVER['HTTP_ACCEPT_LANGUAGE'],
                $supp
            );
            if (!is_null($match)) {
                return $match;
            }
        }

        if (isset($_SERVER['REMOTE_HOST'])) {
            $lang = strtolower(end($h = explode('.', $_SERVER['REMOTE_HOST'])));
            if (isset($supp[$lang])) {
                return $supp[$lang];
            }
        }

        return $default;
    }

public function negotiateLanguage ( $ supported , $ default = 'en-US' ) { $ supp = array ( ) ; foreach ( $ supported as $ lang => $ isSupported ) { if ( $ isSupported ) { $ supp [ strtolower ( $ lang ) ] = $ lang ; } } if ( ! count ( $ supp ) ) { return $ default ; } if ( isset ( $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] ) ) { $ match = $ this -> matchAccept ( $ _SERVER [ 'HTTP_ACCEPT_LANGUAGE' ] , $ supp ) ; if ( ! is_null ( $ match ) ) { return $ match ; } } if ( isset ( $ _SERVER [ 'REMOTE_HOST' ] ) ) { $ lang = strtolower ( end ( $ h = explode ( '.' , $ _SERVER [ 'REMOTE_HOST' ] ) ) ) ; if ( isset ( $ supp [ $ lang ] ) ) { return $ supp [ $ lang ] ; } } return $ default ; }

Negotiates language with the user's browser through the Accept-Language
HTTP header or the user's host address.  Language codes are generally in
the form "ll" for a language spoken in only one country, or "ll-CC" for a
language spoken in a particular country.  For example, U.S. English is
"en-US", while British English is "en-UK".  Portugese as spoken in
Portugal is "pt-PT", while Brazilian Portugese is "pt-BR".

Quality factors in the Accept-Language: header are supported, e.g.:
Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8

<code>
require_once 'HTTP2.php';
$http = new HTTP2();
$langs = array(
'en'    => 'locales/en',
'en-US' => 'locales/en',
'en-UK' => 'locales/en',
'de'    => 'locales/de',
'de-DE' => 'locales/de',
'de-AT' => 'locales/de',
);
$neg = $http->negotiateLanguage($langs);
$dir = $langs[$neg];
</code>

@param array  $supported An associative array of supported languages,
whose values must evaluate to true.
@param string $default   The default language to use if none is found.

@return string The negotiated language result or the supplied default.

Negotiates language with the user s browser through the Accept - Language HTTP header or the user s host address . Language codes are generally in the form ll for a language spoken in only one country or ll - CC for a language spoken in a particular country . For example U . S . English is en - US while British English is en - UK . Portugese as spoken in Portugal is pt - PT while Brazilian Portugese is pt - BR .


public function negotiateCharset($supported, $default = 'ISO-8859-1')
    {
        $supp = array();
        foreach ($supported as $charset) {
            $supp[strtolower($charset)] = $charset;
        }

        if (!count($supp)) {
            return $default;
        }

        if (isset($_SERVER['HTTP_ACCEPT_CHARSET'])) {
            $match = $this->matchAccept(
                $_SERVER['HTTP_ACCEPT_CHARSET'],
                $supp
            );

            if (!is_null($match)) {
                return $match;
            }
        }

        return $default;
    }

public function negotiateCharset ( $ supported , $ default = 'ISO-8859-1' ) { $ supp = array ( ) ; foreach ( $ supported as $ charset ) { $ supp [ strtolower ( $ charset ) ] = $ charset ; } if ( ! count ( $ supp ) ) { return $ default ; } if ( isset ( $ _SERVER [ 'HTTP_ACCEPT_CHARSET' ] ) ) { $ match = $ this -> matchAccept ( $ _SERVER [ 'HTTP_ACCEPT_CHARSET' ] , $ supp ) ; if ( ! is_null ( $ match ) ) { return $ match ; } } return $ default ; }

Negotiates charset with the user's browser through the Accept-Charset
HTTP header.

Quality factors in the Accept-Charset: header are supported, e.g.:
Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8

<code>
require_once 'HTTP2.php';
$http = new HTTP2();
$charsets = array(
'UTF-8',
'ISO-8859-1',
);
$charset = $http->negotiateCharset($charsets);
</code>

@param array  $supported An array of supported charsets
@param string $default   The default charset to use if none is found.

@return string The negotiated language result or the supplied default.
@author Philippe Jausions <jausions@php.net>

Negotiates charset with the user s browser through the Accept - Charset HTTP header .


public function negotiateMimeType($supported, $default)
    {
        $supp = array();
        foreach ($supported as $type) {
            $supp[strtolower($type)] = $type;
        }

        if (!count($supp)) {
            return $default;
        }

        if (isset($_SERVER['HTTP_ACCEPT'])) {
            $accepts = $this->sortAccept($_SERVER['HTTP_ACCEPT']);

            foreach ($accepts as $type => $q) {
                if (substr($type, -2) != '/*') {
                    if (isset($supp[$type])) {
                        return $supp[$type];
                    }
                    continue;
                }
                if ($type == '*/*') {
                    return array_shift($supp);
                }
                list($general, $specific) = explode('/', $type);
                $general .= '/';
                $len = strlen($general);
                foreach ($supp as $mime => $t) {
                    if (strncasecmp($general, $mime, $len) == 0) {
                        return $t;
                    }
                }
            }
        }

        return $default;
    }

public function negotiateMimeType ( $ supported , $ default ) { $ supp = array ( ) ; foreach ( $ supported as $ type ) { $ supp [ strtolower ( $ type ) ] = $ type ; } if ( ! count ( $ supp ) ) { return $ default ; } if ( isset ( $ _SERVER [ 'HTTP_ACCEPT' ] ) ) { $ accepts = $ this -> sortAccept ( $ _SERVER [ 'HTTP_ACCEPT' ] ) ; foreach ( $ accepts as $ type => $ q ) { if ( substr ( $ type , - 2 ) != '/*' ) { if ( isset ( $ supp [ $ type ] ) ) { return $ supp [ $ type ] ; } continue ; } if ( $ type == '*/*' ) { return array_shift ( $ supp ) ; } list ( $ general , $ specific ) = explode ( '/' , $ type ) ; $ general .= '/' ; $ len = strlen ( $ general ) ; foreach ( $ supp as $ mime => $ t ) { if ( strncasecmp ( $ general , $ mime , $ len ) == 0 ) { return $ t ; } } } } return $ default ; }

Negotiates content type with the user's browser through the Accept
HTTP header.

Quality factors in the Accept: header are supported, e.g.:
Accept: application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8

<code>
require_once 'HTTP2.php';
$http = new HTTP2();
$contentType = array(
'application/xhtml+xml',
'application/xml',
'text/html',
'text/plain',
);
$mime = $http->negotiateMimeType($contentType);
</code>

@param array  $supported An associative array of supported MIME types.
@param string $default   The default type to use if none match.

@return string The negotiated MIME type result or the supplied default.
@author Philippe Jausions <jausions@php.net>

Negotiates content type with the user s browser through the Accept HTTP header .


protected function matchAccept($header, $supported)
    {
        $matches = $this->sortAccept($header);
        foreach ($matches as $key => $q) {
            if (isset($supported[$key])) {
                return $supported[$key];
            }
        }
        // If any (i.e. "*") is acceptable, return the first supported format
        if (isset($matches['*'])) {
            return array_shift($supported);
        }
        return null;
    }

Parses a weighed "Accept" HTTP header and matches it against a list
of supported options

@param string $header    The HTTP "Accept" header to parse
@param array  $supported A list of supported values

@return string|NULL a matched option, or NULL if no match

Parses a weighed Accept HTTP header and matches it against a list of supported options


protected function sortAccept($header)
    {
        $matches = array();
        foreach (explode(',', $header) as $option) {
            $option = array_map('trim', explode(';', $option));

            $l = strtolower($option[0]);
            if (isset($option[1])) {
                $q = (float) str_replace('q=', '', $option[1]);
            } else {
                $q = null;
                // Assign default low weight for generic values
                if ($l == '*/*') {
                    $q = 0.01;
                } elseif (substr($l, -1) == '*') {
                    $q = 0.02;
                }
            }
            // Unweighted values, get high weight by their position in the
            // list
            $matches[$l] = isset($q) ? $q : 1000 - count($matches);
        }
        arsort($matches, SORT_NUMERIC);
        return $matches;
    }

Parses and sorts a weighed "Accept" HTTP header

@param string $header The HTTP "Accept" header to parse

@return array Sorted list of "accept" options

Parses and sorts a weighed Accept HTTP header


public function head($url, $timeout = 10)
    {
        $p = parse_url($url);
        if (!isset($p['scheme'])) {
            $p = parse_url($this->absoluteURI($url));
        } elseif ($p['scheme'] != 'http') {
            throw new InvalidArgumentException(
                'Unsupported protocol: '. $p['scheme']
            );
        }

        $port = isset($p['port']) ? $p['port'] : 80;

        if (!$fp = @fsockopen($p['host'], $port, $eno, $estr, $timeout)) {
            throw new HTTP2_Exception("Connection error: $estr ($eno)");
        }

        $path  = !empty($p['path']) ? $p['path'] : '/';
        $path .= !empty($p['query']) ? '?' . $p['query'] : '';

        fputs($fp, "HEAD $path HTTP/1.0\r\n");
        fputs($fp, 'Host: ' . $p['host'] . ':' . $port . "\r\n");
        fputs($fp, "Connection: close\r\n\r\n");

        $response = rtrim(fgets($fp, 4096));
        if (preg_match("|^HTTP/[^\s]*\s(.*?)\s|", $response, $status)) {
            $headers['response_code'] = $status[1];
        }
        $headers['response'] = $response;

        while ($line = fgets($fp, 4096)) {
            if (!trim($line)) {
                break;
            }
            if (($pos = strpos($line, ':')) !== false) {
                $header = substr($line, 0, $pos);
                $value  = trim(substr($line, $pos + 1));

                $headers[$header] = $value;
            }
        }
        fclose($fp);
        return $headers;
    }

public
function
head
(
$
url
,
$
timeout
=
10
)
{
$
p
=
parse_url
(
$
url
)
;
if
(
!
isset
(
$
p
[
'scheme'
]
)
)
{
$
p
=
parse_url
(
$
this
->
absoluteURI
(
$
url
)
)
;
}
elseif
(
$
p
[
'scheme'
]
!=
'http'
)
{
throw
new
InvalidArgumentException
(
'Unsupported protocol: '
.
$
p
[
'scheme'
]
)
;
}
$
port
=
isset
(
$
p
[
'port'
]
)
$
p
[
'port'
]
:
80
;
if
(
!
$
fp
=
@
fsockopen
(
$
p
[
'host'
]
,
$
port
,
$
eno
,
$
estr
,
$
timeout
)
)
{
throw
new
HTTP2_Exception
(
"Connection error: $estr ($eno)"
)
;
}
$
path
=
!
empty
(
$
p
[
'path'
]
)
$
p
[
'path'
]
:
'/'
;
$
path
.=
!
empty
(
$
p
[
'query'
]
)
'?'
.
$
p
[
'query'
]
:
''
;
fputs
(
$
fp
,
"HEAD $path HTTP/1.0\r\n"
)
;
fputs
(
$
fp
,
'Host: '
.
$
p
[
'host'
]
.
':'
.
$
port
.
"\r\n"
)
;
fputs
(
$
fp
,
"Connection: close\r\n\r\n"
)
;
$
response
=
rtrim
(
fgets
(
$
fp
,
4096
)
)
;
if
(
preg_match
(
"|^HTTP/[^\s]*\s(.*?)\s|"
,
$
response
,
$
status
)
)
{
$
headers
[
'response_code'
]
=
$
status
[
1
]
;
}
$
headers
[
'response'
]
=
$
response
;
while
(
$
line
=
fgets
(
$
fp
,
4096
)
)
{
if
(
!
trim
(
$
line
)
)
{
break
;
}
if
(
(
$
pos
=
strpos
(
$
line
,
':'
)
)
!==
false
)
{
$
header
=
substr
(
$
line
,
0
,
$
pos
)
;
$
value
=
trim
(
substr
(
$
line
,
$
pos
+
1
)
)
;
$
headers
[
$
header
]
=
$
value
;
}
}
fclose
(
$
fp
)
;
return
$
headers
;
}

Sends a "HEAD" HTTP command to a server and returns the headers
as an associative array.

Example output could be:
<code>
Array
(
[response_code] => 200          // The HTTP response code
[response] => HTTP/1.1 200 OK   // The full HTTP response string
[Date] => Fri, 11 Jan 2002 01:41:44 GMT
[Server] => Apache/1.3.20 (Unix) PHP/4.1.1
[X-Powered-By] => PHP/4.1.1
[Connection] => close
[Content-Type] => text/html
)
</code>

@param string  $url     A valid URL, e.g.: http://pear.php.net/credits.php
@param integer $timeout Timeout in seconds (default = 10)

@return array Returns associative array of response headers on success

@throws HTTP2_Exception          When connecting fails
@throws InvalidArgumentException When the protocol is not uspported

@see HTTP_Client::head()
@see HTTP_Request

Sends a HEAD HTTP command to a server and returns the headers as an associative array .


protected function convertCharset($from, $to, $str)
    {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($str, $to, $from);
        } else if (function_exists('iconv')) {
            return iconv($from, $to, $str);
        }
        return $str;
    }

protected function convertCharset ( $ from , $ to , $ str ) { if ( function_exists ( 'mb_convert_encoding' ) ) { return mb_convert_encoding ( $ str , $ to , $ from ) ; } else if ( function_exists ( 'iconv' ) ) { return iconv ( $ from , $ to , $ str ) ; } return $ str ; }

Convert the given string from one into another charset.
Uses mb_convert_encoding or iconv if available.

@param string $from Source charset the string is in
@param string $to   Target character set
@param string $str  String to convert

@return string converted string

Convert the given string from one into another charset . Uses mb_convert_encoding or iconv if available .


static function getEntityManager($emname)
    {
        $_this = self::getInstance();
        $emname = $_this->buildEntityName($emname);

        $known_manager = $_this->registry->getEntry($emname, 'entityManager');
        if ($known_manager) {
            return $known_manager;
        } else {
    //			$manager = $_this->buildEntityManager($emname);
            $manager = CarteBlanche::getContainer()->get('entity_manager')
                ->getStorageEngine($emname);
            $_this->registry->setEntry($emname, $manager, 'entityManager');
            return $manager;
        }
    }

Get an entityManager
@param string $emname The name of the entity manager to search
@return object Returns an object to manage the entity


static function getObjectsStructure($dbname = null)
    {
        $_this = self::getInstance();
        $dbname = $_this->buildEntityName($dbname);

        $known_structure = $_this->registry->getEntry($dbname, 'objectStructure');
        if ($known_structure) {
            return $known_structure;
        } else {
            $structure = $_this->buildObjectsStructure($dbname);
            $_this->registry->setEntry($dbname, $structure, 'objectStructure');
            return $structure;
        }
    }

static function getObjectsStructure ( $ dbname = null ) { $ _this = self :: getInstance ( ) ; $ dbname = $ _this -> buildEntityName ( $ dbname ) ; $ known_structure = $ _this -> registry -> getEntry ( $ dbname , 'objectStructure' ) ; if ( $ known_structure ) { return $ known_structure ; } else { $ structure = $ _this -> buildObjectsStructure ( $ dbname ) ; $ _this -> registry -> setEntry ( $ dbname , $ structure , 'objectStructure' ) ; return $ structure ; } }

Get the objects structure from a specific database
@param string $dbname The name of the database to search
@return array Returns an array of the objects structure (FALSE if nothing is found)


static function getAutoObject($tablename = null, $dbname = null)
    {
        if (empty($tablename)) return false;
        $tables = self::getObjectsStructure( $dbname );
        if ($tables) {
            foreach ($tables as $_tbl_name=>$_tbl_obj) {
                if ($_tbl_obj->getTableName()==$tablename) {
                    return $_tbl_obj;
                }
            }
        }
        return false;
    }

static function getAutoObject ( $ tablename = null , $ dbname = null ) { if ( empty ( $ tablename ) ) return false ; $ tables = self :: getObjectsStructure ( $ dbname ) ; if ( $ tables ) { foreach ( $ tables as $ _tbl_name => $ _tbl_obj ) { if ( $ _tbl_obj -> getTableName ( ) == $ tablename ) { return $ _tbl_obj ; } } } return false ; }

Get a table entry from a specific database
@param string $tablename The name of the table to search
@param string $dbname The name of the database to search
@return array Returns an array of the table structure (FALSE if nothing is find)


static function getTableStructure($tablename = null, $dbname = null)
    {
        $_tbl_obj = self::getAutoObject( $tablename, $dbname );
        if (!empty($_tbl_obj)) {
            return $_tbl_obj->getStructureEntry('structure');
        }
        return false;
    }

static function getTableStructure ( $ tablename = null , $ dbname = null ) { $ _tbl_obj = self :: getAutoObject ( $ tablename , $ dbname ) ; if ( ! empty ( $ _tbl_obj ) ) { return $ _tbl_obj -> getStructureEntry ( 'structure' ) ; } return false ; }

Get a table structure from a specific database
@param string $tablename The name of the table to search
@param string $dbname The name of the database to search
@return array Returns an array of the table structure (FALSE if nothing is find)


static function getModel($tablename = null, $dbname = null)
    {
        $_tbl_obj = self::getAutoObject( $tablename, $dbname );
        if (!empty($_tbl_obj)) {
            return $_tbl_obj->getModel();
        }
        return false;
    }

static function getModel ( $ tablename = null , $ dbname = null ) { $ _tbl_obj = self :: getAutoObject ( $ tablename , $ dbname ) ; if ( ! empty ( $ _tbl_obj ) ) { return $ _tbl_obj -> getModel ( ) ; } return false ; }

Get an auto-object model
@param string $tablename The name of the table to search
@param string $dbname The name of the database to search
@return array Returns an instance of the model (FALSE if nothing is find)


protected function buildObjectsStructure($dbname = null)
    {
        $dbname = str_replace(array(CarteBlanche::getPath('root_path'), CarteBlanche::getPath('config_dir')), '', $dbname);
        $tables_def = CarteBlanche::getConfig($dbname.'_database.db_structure');
        $tables_def_file = Locator::locateConfig($tables_def);

        if ($tables_def_file && @file_exists($tables_def_file) && @is_file($tables_def_file)) {
            $table = array();
            include $tables_def_file;
            if (!empty($tables)) {
                $tables_stacks=array();
                foreach ($tables as $_tbl) {
                    $_t_n = $_tbl['table'];
                    $tables_stacks[$_t_n] = new \CarteBlanche\Library\AutoObject\AutoObject( $_t_n, $_tbl, $_t_n, $dbname );
                    $this->registry->setEntry(
                        $_tbl['table'],
                        $tables_stacks[$_t_n],
                        $dbname
                    );
                }
                return $tables_stacks;
            } else
                throw new \RuntimeException(
                    sprintf('Tables definition can\'t be found in file "%s"!', $tables_def)
                );
        } else
            throw new \RuntimeException(
                sprintf('Tables definition file "%s" can\'t be found!', $tables_def)
            );
    }

Build the objects structure from a specific entity
@param string $dbname The name of the database to build
@return array Returns an array of the objects structure (FALSE if nothing is found)


protected function prepareError($code)
  {
    $min = $this->getArgValue('min');
    $max = $this->getArgValue('max');
    $error = Translation::get($code);
    $error = str_replace('%min%', $min, $error);
    $error = str_replace('%max%', $max, $error);
    return $error;
  }

protected function prepareError ( $ code ) { $ min = $ this -> getArgValue ( 'min' ) ; $ max = $ this -> getArgValue ( 'max' ) ; $ error = Translation :: get ( $ code ) ; $ error = str_replace ( '%min%' , $ min , $ error ) ; $ error = str_replace ( '%max%' , $ max , $ error ) ; return $ error ; }

Formatte un texte d'erreur

@param string $code  Code erreur (cf. fichier langue formvalidators.ini)
@return string


public function check($budgets, \DateTimeImmutable $date)
    {
        foreach ($budgets as $budget) {
            $this->checkBudget($budget, $date);

            if ($budget->hasChildren()) {
                foreach ($budget->getChildren() as $child) {
                    $this->checkBudget($child, $date);
                }
            }
        }
    }

public function check ( $ budgets , \ DateTimeImmutable $ date ) { foreach ( $ budgets as $ budget ) { $ this -> checkBudget ( $ budget , $ date ) ; if ( $ budget -> hasChildren ( ) ) { foreach ( $ budget -> getChildren ( ) as $ child ) { $ this -> checkBudget ( $ child , $ date ) ; } } } }

Check for new budget month to add

@param  Budget[] $budgets
@param  \DateTimeImmutable $date
@return BudgetMonth[]


protected function checkBudget(Budget $budget, \DateTimeImmutable $date)
    {
        try {

            $this->addWhere('budget_id', $budget->getId());
            $this->addWhere('budget_month_date', $date->format('Y-m-d'));
            $this->selectOne();

        } catch (ExceptionNoData $exception) {

            //~ If not exist, create this budget month
            //$dateNow   = new \DateTimeImmutable();
            $dateStart = new \DateTimeImmutable($budget->getDateStart());
            $dateEnd   = null;
            if (!empty($budget->getDateEnd())) {
                $dateEnd = new \DateTimeImmutable($budget->getDateEnd());
            }

            $isInRecurrence = $budget->isRecurrent() && $dateStart < $date && ($dateEnd === null || $dateEnd >= $date) && $budget->hasMonth((int) $date->format('m'));
            $isFirstMonth   = ($dateStart == $date);

            if ($isInRecurrence || $isFirstMonth) {
                $budgetMonth = $this->newDataInstance();
                $budgetMonth->setBudgetId($budget->getId());
                $budgetMonth->setDate($date->format('Y-m-d'));
                $budgetMonth->setAmount($budget->getAmountDefault());
                $this->insert($budgetMonth);
            }
        }
    }

//$dateNow   = new \DateTimeImmutable();

Check for budget

@param Budget             $budget
@param \DateTimeImmutable $date
@return void


public function findByBudgetId($budgetId, \DateTimeImmutable $date)
    {
        $this->addWhere('budget_id', $budgetId);
        $this->addWhere('budget_month_date', $date->format('Y-m-d'));

        $result = $this->selectOne();

        return $result;
    }

public function findByBudgetId ( $ budgetId , \ DateTimeImmutable $ date ) { $ this -> addWhere ( 'budget_id' , $ budgetId ) ; $ this -> addWhere ( 'budget_month_date' , $ date -> format ( 'Y-m-d' ) ) ; $ result = $ this -> selectOne ( ) ; return $ result ; }

Get budget month by budget id & month

@param  int $budgetId
@param  \DateTimeImmutable $date
@return BudgetMonth


public function setIdParent($idParent)
    {
        $idParent = (int) $idParent;

        if ($this->idParent < 0) {
            throw new \UnderflowException('Value of "idParent" must be greater than 0');
        }

        if ($this->exists() && $this->idParent !== $idParent) {
            $this->updated['idParent'] = true;
        }

        $this->idParent = $idParent;

        return $this;
    }

Set value for field "account_id_parent"

@param  int $idParent
@return $this
@throws \UnderflowException


public function setIsMain($isMain)
    {
        $isMain = (bool) $isMain;

        if ($this->exists() && $this->isMain !== $isMain) {
            $this->updated['isMain'] = true;
        }

        $this->isMain = $isMain;

        return $this;
    }

public function setIsMain ( $ isMain ) { $ isMain = ( bool ) $ isMain ; if ( $ this -> exists ( ) && $ this -> isMain !== $ isMain ) { $ this -> updated [ 'isMain' ] = true ; } $ this -> isMain = $ isMain ; return $ this ; }

Set value for field "account_is_main"

@param  bool $isMain
@return $this


public function getAccountUser($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinOneCacheAccountUser) {
            $mapper = new AccountUserMapper($this->dependencyContainer->getDatabase('money'));
            $this->joinOneCacheAccountUser = $mapper->findByKeys(array(
                'account_id' => $this->getId(),
            ));
        }

        return $this->joinOneCacheAccountUser;
    }

public function getAccountUser ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinOneCacheAccountUser ) { $ mapper = new AccountUserMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ this -> joinOneCacheAccountUser = $ mapper -> findByKeys ( array ( 'account_id' => $ this -> getId ( ) , ) ) ; } return $ this -> joinOneCacheAccountUser ; }

Get AccountUser data object.

@param  bool $isForceReload
@return AccountUser


public function getBank($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinOneCacheBank) {
            $mapper = new BankMapper($this->dependencyContainer->getDatabase('money'));
            $this->joinOneCacheBank = $mapper->findByKeys(array(
                'bank_id' => $this->getBankId(),
            ));
        }

        return $this->joinOneCacheBank;
    }

public function getBank ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinOneCacheBank ) { $ mapper = new BankMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ this -> joinOneCacheBank = $ mapper -> findByKeys ( array ( 'bank_id' => $ this -> getBankId ( ) , ) ) ; } return $ this -> joinOneCacheBank ; }

Get Bank data object.

@param  bool $isForceReload
@return Bank


public function parse(Account $account, $file)
    {
        $file = new \SplFileObject($file);
        $file->setCsvControl($this->csvDelimiter, $this->csvEnclosure, $this->csvEscape);
        $file->setFlags(\SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_CSV);

        $transactionMapper = new TransactionMapper(Database::get('money'));
        $transactions      = array();

        $file->seek($this->startAtLine);
        while (!$file->eof()) {

            $this->setLine($file->current());
            $transactions[] = $this->createTransaction($transactionMapper, $account);

            $file->next();
        }

        if ($this->dropNbLastLines > 0) {
            $transactions = array_slice($transactions, 0, -$this->dropNbLastLines);
        }

        return $transactions;
    }

public function parse ( Account $ account , $ file ) { $ file = new \ SplFileObject ( $ file ) ; $ file -> setCsvControl ( $ this -> csvDelimiter , $ this -> csvEnclosure , $ this -> csvEscape ) ; $ file -> setFlags ( \ SplFileObject :: DROP_NEW_LINE | \ SplFileObject :: READ_AHEAD | \ SplFileObject :: SKIP_EMPTY | \ SplFileObject :: READ_CSV ) ; $ transactionMapper = new TransactionMapper ( Database :: get ( 'money' ) ) ; $ transactions = array ( ) ; $ file -> seek ( $ this -> startAtLine ) ; while ( ! $ file -> eof ( ) ) { $ this -> setLine ( $ file -> current ( ) ) ; $ transactions [ ] = $ this -> createTransaction ( $ transactionMapper , $ account ) ; $ file -> next ( ) ; } if ( $ this -> dropNbLastLines > 0 ) { $ transactions = array_slice ( $ transactions , 0 , - $ this -> dropNbLastLines ) ; } return $ transactions ; }

Parse data from file.

@param  Account $account
@param  string $file
@return Transaction[]


public function getTypeIcon()
    {
        switch ($this->getType()) {
            case 'CB':
                $icon = 'credit-card';
                break;
            case 'VIR':
                $icon = 'arrow-circle-o-' . ($this->isNegativeAmount() ? 'up' : 'down');
                break;
            case 'PRE':
                $icon = 'arrow-circle-up';
                break;
            case 'CHQ':
                $icon = 'money';
                break;
            case 'PPL':
                $icon = 'paypal';
                break;
            default:
                $icon = 'money';
        }

        return $icon;
    }

public function getTypeIcon ( ) { switch ( $ this -> getType ( ) ) { case 'CB' : $ icon = 'credit-card' ; break ; case 'VIR' : $ icon = 'arrow-circle-o-' . ( $ this -> isNegativeAmount ( ) ? 'up' : 'down' ) ; break ; case 'PRE' : $ icon = 'arrow-circle-up' ; break ; case 'CHQ' : $ icon = 'money' ; break ; case 'PPL' : $ icon = 'paypal' ; break ; default : $ icon = 'money' ; } return $ icon ; }


public function buildQuery(QC $qc, $type = null) {
        if (!$type) $type = $qc->getType();

        $methodName = 'build' . ucfirst($type);
        if (method_exists($this, $methodName)) {
            $result = $this->$methodName($qc);
        } else {
            throw new MysqlDBAdapterException('Invalid method specified: '.$type);
        }
        return $result;
    }

public
function
buildQuery
(
QC
$
qc
,
$
type
=
)
{
if
(
!
$
type
)
$
type
=
$
qc
->
getType
(
)
;
$
methodName
=
'build'
.
ucfirst
(
$
type
)
;
if
(
method_exists
(
$
this
,
$
methodName
)
)
{
$
result
=
$
this
->
$
methodName
(
$
qc
)
;
}
else
{
throw
new
MysqlDBAdapterException
(
'Invalid method specified: '
.
$
type
)
;
}
return
$
result
;
}

Process query to SQL
@param QC $qc
@param mixed $type
@return mixed
@throws MysqlDBAdapterException


protected function escapeOne($value, $type = false) {
        if ($type === false) {
            $type = gettype($value);
        }
        if (strpos($value, '#sql#') !== false) {
            return substr($value, 5);
        }
        if (in_array($type, array('integer'))) {
            return $value;
        } elseif ($type == 'boolean') {
            return intval($value);
        } elseif ($type == 'NULL') {
            return 'null';
        } else {
            return $this->_dbh->quote($value);
        }
    }

protected function escapeOne ( $ value , $ type = false ) { if ( $ type === false ) { $ type = gettype ( $ value ) ; } if ( strpos ( $ value , '#sql#' ) !== false ) { return substr ( $ value , 5 ) ; } if ( in_array ( $ type , array ( 'integer' ) ) ) { return $ value ; } elseif ( $ type == 'boolean' ) { return intval ( $ value ) ; } elseif ( $ type == 'NULL' ) { return 'null' ; } else { return $ this -> _dbh -> quote ( $ value ) ; } }

Escape on value using database driver specific

@param mixed $value to be escaped
@param mixed $type force type definition
@return mixed escaped


public static function createRedirect(
        string $uri = null,
        int $status = StatusCode::FOUND,
        array $headers = []
    ): RedirectResponse {
        return new static('', $status, $headers, $uri);
    }

public static function createRedirect ( string $ uri = null , int $ status = StatusCode :: FOUND , array $ headers = [ ] ) : RedirectResponse { return new static ( '' , $ status , $ headers , $ uri ) ; }

Create a new redirect response.

@param string $uri     [optional] The URI to redirect to
@param int    $status  [optional] The response status code
@param array  $headers [optional] An array of response headers

@throws \InvalidArgumentException
@throws \Valkyrja\Http\Exceptions\InvalidStatusCodeException

@return \Valkyrja\Http\RedirectResponse


public function secure(string $path = null): RedirectResponse
    {
        // If not path was set
        if (null === $path) {
            // If the uri is already set
            if (null !== $this->uri) {
                // Set the path to it
                $path = $this->uri;
            } else {
                // Otherwise set the path to the current path w/ query string
                $path = request()->getPath();
            }
        }

        // If the path doesn't start with a /
        if ('/' !== $path[0]) {
            // Set the uri as the path
            $this->setUri($path);

            // Return out of the method
            return $this;
        }

        // Set the uri to https with the host and path
        $this->setUri('https://' . request()->getHttpHost() . $path);

        return $this;
    }

Set the redirect uri to secure.

@param string $path The path

@return \Valkyrja\Http\RedirectResponse


public function back(): RedirectResponse
    {
        $refererUri = request()->headers()->get('Referer');

        // Ensure the route being redirected to is a valid internal route
        if (! router()->isInternalUri($refererUri)) {
            // If not set as the index
            $refererUri = '/';
        }

        $this->setUri($refererUri ?: '/');

        return $this;
    }

Redirect back to the referer.

@return \Valkyrja\Http\RedirectResponse


public function throw(): void
    {
        throw new HttpRedirectException(
            $this->statusCode,
            $this->uri,
            null,
            $this->headers->all()
        );
    }

public function throw ( ) : void { throw new HttpRedirectException ( $ this -> statusCode , $ this -> uri , null , $ this -> headers -> all ( ) ) ; }

Throw this redirect.

@throws \Valkyrja\Http\Exceptions\HttpRedirectException


protected function filterCommands(array &$commands, int &$longestLength, string $namespace = null): void
    {
        $globalCommands = [];

        /** @var \Valkyrja\Console\Command $command */
        foreach ($commands as $key => $command) {
            $parts            = explode(':', $command->getName());
            $commandName      = $parts[1] ?? null;
            $commandNamespace = $commandName ? $parts[0] : 'global';

            // If there was a namespace passed to the command (commands
            // namespace)  and the namespace for this command doesn't match
            // what was passed then get rid of it so only commands in the
            // namespace are shown.
            if ($commandNamespace !== $namespace && null !== $namespace) {
                unset($commands[$key]);

                continue;
            }

            $longestLength = max(\strlen($command->getName()), $longestLength);

            // If this is a global namespaced command
            if ('global' === $commandNamespace) {
                // Set it in the global commands array so when we show the list
                // of commands global commands will be at the top
                $globalCommands[] = $command;

                // Unset from the commands list to avoid duplicates
                unset($commands[$key]);
            }
        }

        // Sort the global commands by name
        $this->sortCommands($globalCommands);
        // Sort the rest of the commands by name
        $this->sortCommands($commands);

        // Set the commands as the merged results of the global and other
        // commands with the global commands at the top of the list
        $commands = array_merge($globalCommands, $commands);
    }

Filter the commands by type and name.

@param array  $commands      The commands
@param int    $longestLength The longest length
@param string $namespace     [optional] The namespace to show commands
for

@return void


protected function sortCommands(array &$commands): void
    {
        usort(
            $commands,
            function (Command $item1, Command $item2) {
                return $item1->getName() <=> $item2->getName();
            }
        );
    }

protected function sortCommands ( array & $ commands ) : void { usort ( $ commands , function ( Command $ item1 , Command $ item2 ) { return $ item1 -> getName ( ) <=> $ item2 -> getName ( ) ; } ) ; }

Sort commands by name.

@param array $commands The commands

@return void


protected function commandSection(Command $command, string &$previousSection): void
    {
        $parts          = explode(':', $command->getName());
        $commandName    = $parts[1] ?? null;
        $currentSection = $commandName ? $parts[0] : 'global';

        if ($previousSection !== $currentSection) {
            output()->formatter()->cyan();
            output()->writeMessage(static::TAB);
            output()->writeMessage($currentSection, true);

            $previousSection = $currentSection;
        }
    }

protected function commandSection ( Command $ command , string & $ previousSection ) : void { $ parts = explode ( ':' , $ command -> getName ( ) ) ; $ commandName = $ parts [ 1 ] ?? null ; $ currentSection = $ commandName ? $ parts [ 0 ] : 'global' ; if ( $ previousSection !== $ currentSection ) { output ( ) -> formatter ( ) -> cyan ( ) ; output ( ) -> writeMessage ( static :: TAB ) ; output ( ) -> writeMessage ( $ currentSection , true ) ; $ previousSection = $ currentSection ; } }

The command section.

@param Command $command         The current command
@param string  $previousSection The previous section

@return void


function initSession() {

        static $initSessionCalled = false;

        if($initSessionCalled == true){
            return;
        }

        $initSessionCalled = true;
        $currentCookieParams = session_get_cookie_params();
        $domainInfo = $this->domain->getDomainInfo();

        session_set_cookie_params(
            $currentCookieParams["lifetime"],
            $currentCookieParams["path"],
            '.'.$domainInfo->rootCanonicalDomain, //leading dot according to http://www.faqs.org/rfcs/rfc2109.html
            $currentCookieParams["secure"],
            $currentCookieParams["httponly"]
        );

        session_name($this->sessionName);

        if (isset($_COOKIE[$this->sessionName])) {
            //Only start the session automatically, if the user sent us a cookie.
            $this->startSession();
        }
    }

Initialize the session parametesr. Only opens the session automatically
if the user sent us a cookie that looks like it contains a reference to a session.
That avoids creating sessions for users who are not logged in.

Initialize the session parametesr . Only opens the session automatically if the user sent us a cookie that looks like it contains a reference to a session . That avoids creating sessions for users who are not logged in .


public static function start($name = null)
    {
        if (null === $name) {
            static::$time = -static::getTime();
        } else {
            static::$times[$name] = -static::getTime();
        }
    }

public static function start ( $ name = null ) { if ( null === $ name ) { static :: $ time = - static :: getTime ( ) ; } else { static :: $ times [ $ name ] = - static :: getTime ( ) ; } }

Start time. If name is null, start global timer.

@param  string $name
@return void

Start time . If name is null start global timer .


public static function get($name = null)
    {
        if (null === $name) {
            $time = static::$time;
        } elseif (isset(static::$times[$name])) {
            $time = static::$times[$name];
        } else {
            throw new \LogicException('Timer with given name does not exist!');
        }

        return ($time + static::getTime());
    }

public
static
function
get
(
$
name
=
)
{
if
(
===
$
name
)
{
$
time
=
static
::
$
time
;
}
elseif
(
isset
(
static
::
$
times
[
$
name
]
)
)
{
$
time
=
static
::
$
times
[
$
name
]
;
}
else
{
throw
new
\
LogicException
(
'Timer with given name does not exist!'
)
;
}
return
(
$
time
+
static
::
getTime
(
)
)
;
}

Get Time time.

@param  string $name
@return float


public static function display($name = null, $round = 3)
    {
        $time = round(static::get($name), $round);
        $name = ($name === null ? 'GLOBAL' : $name);

        if (PHP_SAPI !== 'cli') {
            echo '

    Timer[' . $name . ']:  ' . $time . ' s

';
        } else {
            echo ' ### Timer[' . $name . ']: ' . $time . 's ###' . PHP_EOL;
        }
    }

Display timer value

@param  string $name
@param  int    $round
@return void


public function initializeProvided(string $itemId): void
    {
        /** @var \Valkyrja\Support\Providers\Provides $provider */
        $provider = self::$provided[$itemId];

        // Register the provider
        $this->register($provider, true);
    }

Initialize a provided item.

@param string $itemId The item

@return void


public static function init(Composer\Autoload\ClassLoader $composer = null, $configsPath = null, $appType = StaticApplicationInterface::APP_TYPE_WEB)
    {
        static::initBasic($composer, $configsPath, $appType);
        static::initStaticApp();
    }

public static function init ( Composer \ Autoload \ ClassLoader $ composer = null , $ configsPath = null , $ appType = StaticApplicationInterface :: APP_TYPE_WEB ) { static :: initBasic ( $ composer , $ configsPath , $ appType ) ; static :: initStaticApp ( ) ; }

Initialize whole application
@param \Composer\Autoload\ClassLoader $composer
@param string                         $configsPath Path where to look for config files
@param string                         $appType Application type (web|console)


public static function initBasic(Composer\Autoload\ClassLoader $composer = null, $configsPath = null, $appType = StaticApplicationInterface::APP_TYPE_WEB)
    {
        if (!isset($composer)) {
            $composer = static::locateClassLoader();
        }
        if (!isset($configsPath)) {
            $configsPath = static::locateConfigsPath();
        }
        if (!isset($composer)) {
            throw new \Reaction\Exceptions\InvalidArgumentException("Missing \$composer option");
        }
        if (!isset($configsPath)) {
            throw new \Reaction\Exceptions\InvalidArgumentException("Missing \$configsPath option");
        }
        static::$composer = $composer;
        static::$configsPath = $configsPath;
        static::$appType = $appType;
        static::initConfigReader();
        static::initAnnotationReader();
        static::initContainer();
    }

public
static
function
initBasic
(
Composer
\
Autoload
\
ClassLoader
$
composer
=
,
$
configsPath
=
,
$
appType
=
StaticApplicationInterface
::
APP_TYPE_WEB
)
{
if
(
!
isset
(
$
composer
)
)
{
$
composer
=
static
::
locateClassLoader
(
)
;
}
if
(
!
isset
(
$
configsPath
)
)
{
$
configsPath
=
static
::
locateConfigsPath
(
)
;
}
if
(
!
isset
(
$
composer
)
)
{
throw
new
\
Reaction
\
Exceptions
\
InvalidArgumentException
(
"Missing \$composer option"
)
;
}
if
(
!
isset
(
$
configsPath
)
)
{
throw
new
\
Reaction
\
Exceptions
\
InvalidArgumentException
(
"Missing \$configsPath option"
)
;
}
static
::
$
composer
=
$
composer
;
static
::
$
configsPath
=
$
configsPath
;
static
::
$
appType
=
$
appType
;
static
::
initConfigReader
(
)
;
static
::
initAnnotationReader
(
)
;
static
::
initContainer
(
)
;
}

Initialize basic components
@param \Composer\Autoload\ClassLoader|null $composer
@param string|null                         $configsPath
@param string                              $appType


protected static function locateConfigsPath()
    {
        $cwd = getcwd();
        $defaultDir = DIRECTORY_SEPARATOR . 'Config';
        $path = $cwd . $defaultDir;
        if (!file_exists($path) || !is_dir($path)) {
            return null;
        }
        return $path;
    }

protected static function locateConfigsPath ( ) { $ cwd = getcwd ( ) ; $ defaultDir = DIRECTORY_SEPARATOR . 'Config' ; $ path = $ cwd . $ defaultDir ; if ( ! file_exists ( $ path ) || ! is_dir ( $ path ) ) { return null ; } return $ path ; }


protected static function locateClassLoader()
    {
        $cwd = getcwd();
        $path = $cwd . DIRECTORY_SEPARATOR . 'vendor/autoload.php';
        if (!file_exists($path) || !is_file($path)) {
            return null;
        }
        return include $path;
    }

protected static function locateClassLoader ( ) { $ cwd = getcwd ( ) ; $ path = $ cwd . DIRECTORY_SEPARATOR . 'vendor/autoload.php' ; if ( ! file_exists ( $ path ) || ! is_file ( $ path ) ) { return null ; } return include $ path ; }

Get composer class loader
@return null|\Composer\Autoload\ClassLoader


public static function create($type, array $params = [])
    {
        if (is_string($type)) {
            return static::$di->getOrCreate($type, $params);
        } elseif (is_array($type) && isset($type['class'])) {
            $class = $type['class'];
            unset($type['class']);
            return static::$di->getOrCreate($class, $params, $type);
        } elseif (is_callable($type, true)) {
            return static::$di->invoke($type, $params);
        } elseif (is_array($type)) {
            throw new \Reaction\DI\Exceptions\InvalidConfigException('Object configuration must be an array containing a "class" element.');
        }

        throw new \Reaction\DI\Exceptions\InvalidConfigException('Unsupported configuration type: ' . gettype($type));
    }

Create instance of class
@param string|array $type Class name or indexed parameters array with key "class"
@param array        $params Constructor parameters indexed array
@return object|mixed
@throws \Reaction\DI\Exceptions\InvalidConfigException(


protected static function getConfigReader($flush = false)
    {
        if ($flush || !isset(static::$config)) {
            $conf = [
                'path' => static::$configsPath,
                'appType' => static::$appType,
            ];
            static::$config = new \Reaction\Base\ConfigReader($conf);
        }
        return static::$config;
    }

protected static function getConfigReader ( $ flush = false ) { if ( $ flush || ! isset ( static :: $ config ) ) { $ conf = [ 'path' => static :: $ configsPath , 'appType' => static :: $ appType , ] ; static :: $ config = new \ Reaction \ Base \ ConfigReader ( $ conf ) ; } return static :: $ config ; }

Get instance of config reader
@param bool $flush
@return \Reaction\Base\ConfigReader


protected static function initContainer()
    {
        $config = static::getConfigReader()->get('container');
        Container::setDefaultContainer(new Container($config));
        static::$di = Container::getDefaultContainer();
    }

protected static function initContainer ( ) { $ config = static :: getConfigReader ( ) -> get ( 'container' ) ; Container :: setDefaultContainer ( new Container ( $ config ) ) ; static :: $ di = Container :: getDefaultContainer ( ) ; }


public static function initStaticApp()
    {
        $config = static::getConfigReader()->get('appStatic');
        $config['class'] = StaticApplicationInterface::class;
        //Use config after creation, so Reaction::$app will be available inside StaticApplicationInterface components
        $appLateConfig = [];
        $appLateConfigKeys = ['components'];
        foreach ($appLateConfigKeys as $appKey) {
            if (isset($config[$appKey])) {
                $appLateConfig[$appKey] = $config[$appKey];
                unset($config[$appKey]);
            }
        }
        static::$app = static::create($config);
        Container::setDefaultServiceLocator(static::$app);
        if (!empty($appLateConfig)) {
            static::configure(static::$app, $appLateConfig);
        }
    }


protected function tokensMatch(Request $request)
    {
        $token = $this->getTokenFromRequest($request);
        $storedToken = $this->getToken();

        return  is_string($storedToken) &&
                is_string($token) &&
                hash_equals($storedToken, $token);
    }

protected function tokensMatch ( Request $ request ) { $ token = $ this -> getTokenFromRequest ( $ request ) ; $ storedToken = $ this -> getToken ( ) ; return is_string ( $ storedToken ) && is_string ( $ token ) && hash_equals ( $ storedToken , $ token ) ; }

Determine if the storage and input CSRF tokens match.

@param  Request $request
@return boolean

Determine if the storage and input CSRF tokens match .


protected function getTokenFromRequest(Request $request)
    {
        $token = $request->getParameter($this->key) ?: $request->getHeader('X-CSRF-TOKEN');

        return $token;
    }

protected function getTokenFromRequest ( Request $ request ) { $ token = $ request -> getParameter ( $ this -> key ) ? : $ request -> getHeader ( 'X-CSRF-TOKEN' ) ; return $ token ; }

Get the CSRF token from the request.

@param  Request $request
@return string


public function init()
    {
        $config = $this->getConfig();

        if (!isset($config['api_key'])) {
            throw new \Exception('Unable to locate darksky_api_key in bot configuration.');
        }

        $this->darksky = new \DarkSky($config['api_key']);
        $plugin = $this;    // PHP 5.3, you suck.

        // Look at all this weather!
        $this->bot->onChannel('/^!ds (\w+)(.*)/', function(Event $event) use ($plugin) {
            $matches = $event->getMatches();
            switch($cmd = $matches[0]) {
                case 'now':
                case 'current':
                    $plugin->getCurrentWeather(trim($matches[1]), $event);
                    break;

                case 'forecast':
                case 'at':
                    $plugin->getPrecipitation(trim($matches[1]), $event);
                    break;

                default:
                    $plugin->addErrorMsg($event, "Unknown command: $cmd");
                    break;
            }
        });
    }

Uses the DarkSky API to retrieve weather data


public function getCurrentWeather($where, $event)
    {
        if (!$found = $this->getLatLongForLocation($where)) {
            $this->addLatLongError($event);
            return;
        }

        try {
            list($lat, $long) = $found;
            $forecast = $this->darksky->getBriefForecast($lat, $long);

            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf('[Weather for %s] Currently: %s, %s degrees. For the next hour: %s',
                        $where,
                        $forecast['currentSummary'],
                        $forecast['currentTemp'],
                        $forecast['hourSummary']
                    )
                )
            );
        } catch (\Exception $ex) {
            $this->addErrorMsg($event, "Oops, I'm unable to get the weather for that location...");
            return;
        }
    }

Gets the current weather and a simple prediction for the next hour.

@param string $where The location to lookup
@param \Philip\IRC\Event $event The event to handle

@return void

Gets the current weather and a simple prediction for the next hour .


public function getPrecipitation($match, $event)
    {
        $location = explode('@', $match);
        $where = trim($location[0]);
        $when  = trim($location[1]);

        if (!$found = $this->getLatLongForLocation($where)) {
            $this->addLatLongError($event);
            return;
        }

        try {
            $time = new \DateTime($when);
            list($lat, $long) = $found;
            $precipitation = $this->darksky->getPrecipitation(array(
                'lat'  => $lat,
                'long' => $long,
                'time' => $time->getTimestamp()
            ));

            $chanceOfRain = $precipitation['precipitation'][0]['probability'] * 100;
            $intensity = $precipitation['precipitation'][0]['intensity'];

            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf('[Weather for %s @ %s] %s (%d%% chance of rain)',
                        $where,
                        $time->format('g:ia'),
                        $this->getEnglishIntensity($intensity),
                        $chanceOfRain
                    )
                )
            );
        } catch (\Exception $ex) {
            $this->addErrorMsg($event, "Oops. I'm unable to get the precipitation for that location at that time...");
            return;
        }
    }

Gets the precipitation at a specific place and time.

@param string $match The remainder of the match (holds location info)
@param \Philip\IRC\Event $event The event to handle.

@return void

Gets the precipitation at a specific place and time .