public function execute($lazy = true)
    {
        $sql = $this->getSql();
        $rawSql = $this->getRawSql();

        if ($sql == '') {
            return reject(false);
        }

        $execPromise = $this->internalExecute($rawSql, [], $lazy);
        $needResCount = $this->needResultsCount();
        $thenCallback = function($results = []) use ($needResCount) {
            $result = $needResCount ? count($results) : true;
            return $this->refreshTableSchema()->then(
                function() use ($result) {
                    return $result;
                }
            );
        };
        return $execPromise instanceof LazyPromiseInterface
            ? $execPromise->thenLazy($thenCallback)
            : $execPromise->then($thenCallback);
    }

public function execute ( $ lazy = true ) { $ sql = $ this -> getSql ( ) ; $ rawSql = $ this -> getRawSql ( ) ; if ( $ sql == '' ) { return reject ( false ) ; } $ execPromise = $ this -> internalExecute ( $ rawSql , [ ] , $ lazy ) ; $ needResCount = $ this -> needResultsCount ( ) ; $ thenCallback = function ( $ results = [ ] ) use ( $ needResCount ) { $ result = $ needResCount ? count ( $ results ) : true ; return $ this -> refreshTableSchema ( ) -> then ( function ( ) use ( $ result ) { return $ result ; } ) ; } ; return $ execPromise instanceof LazyPromiseInterface ? $ execPromise -> thenLazy ( $ thenCallback ) : $ execPromise -> then ( $ thenCallback ) ; }

Executes the SQL statement.
This method should only be used for executing non-query SQL statement, such as `INSERT`, `DELETE`, `UPDATE` SQLs.
No result set will be returned.
@param bool $lazy Use LazyPromise
@return ExtendedPromiseInterface|LazyPromiseInterface

Executes the SQL statement . This method should only be used for executing non - query SQL statement such as INSERT DELETE UPDATE SQLs . No result set will be returned .


protected function logQuery($category)
    {
        if ($this->db->enableLogging) {
            $rawSql = $this->getRawSql();
            $message = sprintf("SQL: \"%s\"\nCategory: %s", $rawSql, $category);
            \Reaction::info($message);
        }
        if (!$this->db->enableProfiling) {
            return [false, isset($rawSql) ? $rawSql : null];
        }

        return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
    }

protected
function
logQuery
(
$
category
)
{
if
(
$
this
->
db
->
enableLogging
)
{
$
rawSql
=
$
this
->
getRawSql
(
)
;
$
message
=
sprintf
(
"SQL: \"%s\"\nCategory: %s"
,
$
rawSql
,
$
category
)
;
\
Reaction
::
info
(
$
message
)
;
}
if
(
!
$
this
->
db
->
enableProfiling
)
{
return
[
false
,
isset
(
$
rawSql
)
$
rawSql
:
]
;
}
return
[
true
,
isset
(
$
rawSql
)
$
rawSql
:
$
this
->
getRawSql
(
)
]
;
}

Logs the current database query if query logging is enabled and returns
the profiling token if profiling is enabled.
@param string $category the log category.
@return array array of two elements, the first is boolean of whether profiling is enabled or not.
The second is the rawSql if it has been created.

Logs the current database query if query logging is enabled and returns the profiling token if profiling is enabled .


public function queryScalar()
    {
        return $this->queryInternal(static::FETCH_FIELD)->thenLazy(
            function($result) {
                if (is_resource($result) && get_resource_type($result) === 'stream') {
                    return stream_get_contents($result);
                }
                return $result;
            }
        );
    }

public function queryScalar ( ) { return $ this -> queryInternal ( static :: FETCH_FIELD ) -> thenLazy ( function ( $ result ) { if ( is_resource ( $ result ) && get_resource_type ( $ result ) === 'stream' ) { return stream_get_contents ( $ result ) ; } return $ result ; } ) ; }

Executes the SQL statement and returns the value of the first column in the first row of data.
This method is best used when only a single value is needed for a query.
@return LazyPromiseInterface the value of the first column in the first row of the query result.
False is returned if there is no value.

Executes the SQL statement and returns the value of the first column in the first row of data . This method is best used when only a single value is needed for a query .


protected function queryInternal($fetchMethod, $fetchMode = null, $lazy = true)
    {
        $fetchMode = isset($fetchMode) ? $fetchMode : $this->fetchMode;
        list($profile, $rawSql) = $this->logQuery(__METHOD__);

        $self = $this;
        $execPromise = $this->internalExecute($this->sql, $this->params, $lazy);
        if ($execPromise instanceof LazyPromiseInterface) {
            return $execPromise->thenLazy(
                function($results) use ($fetchMethod, $fetchMode) {
                    return $this->fetchResults($results, $fetchMethod, $fetchMode);
                }
            );
        } else {
            $profileId = $profile ? \Reaction::$app->logger->profile('Query: ' . $rawSql) : null;
            return $execPromise->then(
                function($results) use ($self, $fetchMethod, $fetchMode) {
                    return $self->fetchResults($results, $fetchMethod, $fetchMode);
                }
            )->then(
                function($data) use ($profileId) {
                    \Reaction::profileEnd($profileId);
                    return $data;
                },
                function($error = null) use ($profileId) {
                    \Reaction::profileEnd($profileId);
                    return reject($error);
                }
            );
        }
    }

protected
function
queryInternal
(
$
fetchMethod
,
$
fetchMode
=
,
$
lazy
=
true
)
{
$
fetchMode
=
isset
(
$
fetchMode
)
$
fetchMode
:
$
this
->
fetchMode
;
list
(
$
profile
,
$
rawSql
)
=
$
this
->
logQuery
(
__METHOD__
)
;
$
self
=
$
this
;
$
execPromise
=
$
this
->
internalExecute
(
$
this
->
sql
,
$
this
->
params
,
$
lazy
)
;
if
(
$
execPromise
instanceof
LazyPromiseInterface
)
{
return
$
execPromise
->
thenLazy
(
function
(
$
results
)
use
(
$
fetchMethod
,
$
fetchMode
)
{
return
$
this
->
fetchResults
(
$
results
,
$
fetchMethod
,
$
fetchMode
)
;
}
)
;
}
else
{
$
profileId
=
$
profile
\
Reaction
::
$
app
->
logger
->
profile
(
'Query: '
.
$
rawSql
)
:
;
return
$
execPromise
->
then
(
function
(
$
results
)
use
(
$
self
,
$
fetchMethod
,
$
fetchMode
)
{
return
$
self
->
fetchResults
(
$
results
,
$
fetchMethod
,
$
fetchMode
)
;
}
)
->
then
(
function
(
$
data
)
use
(
$
profileId
)
{
\
Reaction
::
profileEnd
(
$
profileId
)
;
return
$
data
;
}
,
function
(
$
error
=
)
use
(
$
profileId
)
{
\
Reaction
::
profileEnd
(
$
profileId
)
;
return
reject
(
$
error
)
;
}
)
;
}
}

Performs the actual DB query of a SQL statement.
@param string $fetchMethod method of PDOStatement to be called
@param int    $fetchMode the result fetch mode. Please refer to [PHP manual](http://www.php.net/manual/en/function.PDOStatement-setFetchMode.php)
for valid fetch modes. If this parameter is null, the value set in [[fetchMode]] will be used.
@param bool   $lazy Use LazyPromise
@return ExtendedPromiseInterface|LazyPromiseInterface with the method execution result

Performs the actual DB query of a SQL statement .


protected function checkQueryByPattern($pattern, $sql = null) {
        if (!isset($sql)) {
            $sql = $this->getSql();
        }
        if ($sql === "") {
            return false;
        }
        return preg_match($pattern, $sql) > 0;
    }

protected function checkQueryByPattern ( $ pattern , $ sql = null ) { if ( ! isset ( $ sql ) ) { $ sql = $ this -> getSql ( ) ; } if ( $ sql === "" ) { return false ; } return preg_match ( $ pattern , $ sql ) > 0 ; }

Check query string by pattern
@param string      $pattern
@param string|null $sql
@return bool
@internal


protected function internalExecute($sql, $params = [], $lazy = true)
    {
        return isset($this->connection)
            ? $this->connection->executeSql($sql, $params, $lazy)
            : $this->db->executeSql($sql, $params, $lazy);
    }

protected function internalExecute ( $ sql , $ params = [ ] , $ lazy = true ) { return isset ( $ this -> connection ) ? $ this -> connection -> executeSql ( $ sql , $ params , $ lazy ) : $ this -> db -> executeSql ( $ sql , $ params , $ lazy ) ; }

Execute SQL statement internally
@param string $sql
@param array  $params
@param bool   $lazy
@return ExtendedPromiseInterface


protected function invokeClosure(array $arguments, Closure $action)
    {
        $reflection = new ReflectionFunction($action);
        $parameters = [];

        foreach ($reflection->getParameters() as $parameter)
        {
            if (isset($arguments[$parameter->name]))
            {
                $parameters[] = $arguments[$parameter->name];
            }
            elseif ($parameter->isDefaultValueAvailable())
            {
                $parameters[] = $parameter->getDefaultValue();
            }
            else
            {
                $message = "{$parameter->name} argument cannot be resolved.";
                throw new DispatcherException($message, $arguments, $action);
            }
        }

        return $reflection->invokeArgs($parameters);
    }

Invoke closure using arguments.

@param array   $arguments
@param Closure $action

@throws DispatcherException
@return mixed


function _checkLayer($layer = null)
    {
        if (!empty($layer) && $layer != 'default') {
            $layers = $this->config->getLayers();
            if (!in_array($layer, $layers)) {
                return " only the layers: \"" . implode('" or "', $layers) . "\" are supported";
            }
        }

        return false;
    }

function
_checkLayer
(
$
layer
=
)
{
if
(
!
empty
(
$
layer
)
&&
$
layer
!=
'default'
)
{
$
layers
=
$
this
->
config
->
getLayers
(
)
;
if
(
!
in_array
(
$
layer
,
$
layers
)
)
{
return
" only the layers: \""
.
implode
(
'" or "'
,
$
layers
)
.
"\" are supported"
;
}
}
return
false
;
}

Checks if a layer is defined or not

@param string $layer The layer to search for
@return mixed False on no error or the error message


protected function prepareDom()
    {
        $dom_refs = array(
            'page_menu', 'page_content', 'page_header', 'page_footer', 'page_title'
        );
        foreach($dom_refs as $_ref) {
            HtmlHelper::getNewId($_ref, true);
        }
        return $this;
    }

protected function prepareDom ( ) { $ dom_refs = array ( 'page_menu' , 'page_content' , 'page_header' , 'page_footer' , 'page_title' ) ; foreach ( $ dom_refs as $ _ref ) { HtmlHelper :: getNewId ( $ _ref , true ) ; } return $ this ; }

Prepare the required DOM IDs used by the global template

@return self


public function distribute()
    {
        $this
            ->_processSessionValues()
            ->_processQueryArguments()
            ;

        // if kernerl has booting errors, treat them first
        if (CarteBlanche::getContainer()->get('kernel')->hasBootErrors()) {
            $routing = array(CarteBlanche::getContainer()->get('kernel')->getBootErrors());
            if (CarteBlanche::getContainer()->get('request')->isCli()) {
                $routing['controller'] = CarteBlanche::getConfig('routing.cli.default_controller');
                $routing['action'] = CarteBlanche::getConfig('routing.cli.booterrors_action');
            } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) {
                $routing['controller'] = CarteBlanche::getConfig('routing.ajax.default_controller');
                $routing['action'] = CarteBlanche::getConfig('routing.ajax.booterrors_action');
            } else {
                $routing['controller'] = CarteBlanche::getConfig('routing.mvc.default_controller');
                $routing['action'] = CarteBlanche::getConfig('routing.mvc.booterrors_action');
            }
        } else {
            $routing = CarteBlanche::getContainer()->get('router')
                ->distribute()
                ->getRouteParsed();

            // controller
            if (empty($routing['controller'])) {
                if (CarteBlanche::getContainer()->get('request')->isCli()) {
                    $routing['controller'] = CarteBlanche::getConfig('routing.cli.default_controller');
                } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) {
                    $routing['controller'] = CarteBlanche::getConfig('routing.ajax.default_controller');
                } else {
                    $routing['controller'] = CarteBlanche::getConfig('routing.mvc.default_controller');
                }
            }

            // action
            if (empty($routing['action'])) {
                if (CarteBlanche::getContainer()->get('request')->isCli()) {
                    $routing['action'] = CarteBlanche::getConfig('routing.cli.default_action');
                } elseif (CarteBlanche::getContainer()->get('request')->isAjax()) {
                    $routing['action'] = CarteBlanche::getConfig('routing.ajax.default_action');
                } else {
                    $routing['action'] = CarteBlanche::getConfig('routing.mvc.default_action');
                }
            }
        }

        // arguments
        $primary_args = $routing;
        unset($primary_args['all']);
        $args = isset($routing['all']) ? array_merge($primary_args, $routing['all']) : $primary_args;

        // dispatch
        return $this->dispatch(
            $routing['controller'], $routing['action'], $args
        );
    }

Distribute the current request route

@return void


public function renderError($params = null, $code = 404, $exception = null)
    {
        $mode_data = CarteBlanche::getKernelMode(true);
        if (!is_array($mode_data)
            || !isset($mode_data['debug'])
            || false==$mode_data['debug']
        ) {
            $action = 'error'.$code.'Action';
            $_ctrl = CarteBlanche::getContainer()
                ->get('locator')->locateController('Error');
            if (!empty($_ctrl) && class_exists($_ctrl)) {
                $_routes['controller'] = $_ctrl;
                $this->setController(new $_ctrl(CarteBlanche::getContainer()));
            } else {
                trigger_error("Controller 'Error' can't be found!", E_USER_ERROR);
            }

            // don't execute `shutdown` kernel steps
            CarteBlanche::getContainer()->get('kernel')
                ->setShutdown(false);

            return CodeHelper::fetchArguments(
                $action, $params, $this->getController()
            );
        } else {
            if (!empty($exception)) {
                if (!isset($params['message'])) $params['message'] = '';
                $params['message'] .= method_exists($exception, 'getAppMessage') ?
                    $exception->getAppMessage() : $exception->getMessage();
            }
            $debug = \CarteBlanche\App\Debugger::getInstance();
            $this->renderDebug($params, null, false);
            $params['title'] = $debug->getDebuggerTitle();
            $tpl = 'profiler/template_profiler';

            // don't execute `shutdown` kernel steps
//            CarteBlanche::getContainer()->get('kernel')->setShutdown(false);

            return $this->view($tpl, $params, true, true);
        }
    }

Render an application error page view

@param   array       $params     An array of the parameters passed for the view parsing (passed by reference)
@param   int         $code       The error code
@param   null/string $exception    The exception info
@return  mixed
@see     self::render()
@see     self::view()


public function renderDebug(&$params = null, $dbg = 'all', $parse_template = true)
    {
        $all_debug_infos = array( 'backtrace', 'php', 'server', 'session', 'constants', 'headers', 'system', 'router', 'registry', 'db' );
        if (!is_array($dbg)) {
            if ($dbg=='all' || $dbg==1) $dbg = $all_debug_infos;
            else $dbg = array( $dbg );
        }
        $debug = \CarteBlanche\App\Debugger::getInstance();
        foreach($dbg as $_dbg_info) {
            switch($_dbg_info) {
                case 'router':
                    $debug->addStack('object', CarteBlanche::getContainer()->get('router'), 'Router Object Dump');
                    break;
                case 'registry':
                    $debug->addStack('object', CarteBlanche::getContainer()->get('config')->getRegistry(), 'Registry Object Dump');
                    break;
                case 'db':
                    $debug->addStack('object', CarteBlanche::getContainer()->get('database'), 'Database Object Dump');
                    break;
                default:break;
            }
        }
        $params['debug'] = $debug;
        if ($parse_template) {
            $url_ref = str_replace('&', '&', $_SERVER['HTTP_REFERER']);
            $params['return_url'] = $url_ref;
            $debug->setDebuggerTitle( 'CarteBlanche - Debugging request '.str_replace(_ROOTHTTP, '/', $url_ref).'' );
            $params['title'] = $debug->getDebuggerTitle();
            $tpl = 'profiler/template_profiler';
            return $this->view( $tpl, $params, true, true);
        }
        return;
    }

'CarteBlanche - Debugging request <a href="'

Render a debug application page view

@param   array           $params         An array of the parameters passed for the view parsing (passed by reference)
@param   string/array    $dbg            Which object variable to debug (default is 'all')
@param   bool            $parse_template Parse the debug template or not (default is TRUE)
@return  string
@see     self::render()


public function view($view = null, array $params = array(), $display = false, $exit = false)
    {
        $view_file = CarteBlanche::getContainer()
            ->get('locator')->locateView( $view );
        CarteBlanche::getContainer()->get('config')
            ->getRegistry()->loadStack('views');
        CarteBlanche::getContainer()->get('config')
            ->getRegistry()->setEntry(uniqid(), array(
                'tpl'=>$view,
                'params'=>$params
            ));
        CarteBlanche::getContainer()->get('config')
            ->getRegistry()->saveStack('views', true);
        $output = CarteBlanche::getContainer()->get('template_engine')
            ->render($view_file, $params, $display, $exit);

        if ($display===true) {
            CarteBlanche::getContainer()->get('response')
                ->addContent(null, $output)
                ->send();
            return;
        } else {
            return $output;
        }
    }

public function view ( $ view = null , array $ params = array ( ) , $ display = false , $ exit = false ) { $ view_file = CarteBlanche :: getContainer ( ) -> get ( 'locator' ) -> locateView ( $ view ) ; CarteBlanche :: getContainer ( ) -> get ( 'config' ) -> getRegistry ( ) -> loadStack ( 'views' ) ; CarteBlanche :: getContainer ( ) -> get ( 'config' ) -> getRegistry ( ) -> setEntry ( uniqid ( ) , array ( 'tpl' => $ view , 'params' => $ params ) ) ; CarteBlanche :: getContainer ( ) -> get ( 'config' ) -> getRegistry ( ) -> saveStack ( 'views' , true ) ; $ output = CarteBlanche :: getContainer ( ) -> get ( 'template_engine' ) -> render ( $ view_file , $ params , $ display , $ exit ) ; if ( $ display === true ) { CarteBlanche :: getContainer ( ) -> get ( 'response' ) -> addContent ( null , $ output ) -> send ( ) ; return ; } else { return $ output ; } }

Render a view

@param   string      $view      The view filename in `$views_dir`
@param   array       $params    An array of the parameters passed for the view parsing
@param   bool        $display   Display the view or return it (default is FALSE)
@param   bool        $exit      Exit after rendering (default is FALSE)
@return  string|void
@see     \TemplateEngine\TemplateEngine::render()


public function init()
    {
        $this->addResponses();

        $config = $this->bot->getConfig();

        // detects someone speaking to the bot
        $responses = $this->responses;
        $address_re = "/(^{$config['nick']}(.+)|(.+){$config['nick']}[!.?]*)$/i";
        $this->bot->onChannel($address_re, function(Event $event) use ($responses) {
            $matches = $event->getMatches();
            $message = $matches[1] ? $matches[1] : $matches[2];

            foreach ($responses as $regex => $function) {
                if (preg_match($regex, $message, $matches)) {
                    $event->addResponse(
                        Response::msg($event->getRequest()->getSource(), $function($matches))
                    );
                }
            }
        });
    }

Init the plugin and start listening to messages


private function addResponses()
    {
        // workaround for $this being unavailable in closures
        $plugin = $this;

        // basic response
        $this->addResponse('/i (love|<3) (you|u)/i', function($matches) {
            return 'Shutup baby, I know it!';
        });

        // matches things like "bot: you're the greatest thing ever!" and saves the attribute for later
        $this->addResponse('/(you are|you\'re) (the |a |an )*([\w ]+)/i', function($matches) use ($plugin) {
            $plugin->addAttribute(trim($matches[2] .' '. trim($matches[3])));
            return "No, *you're* {$matches[2]} ". trim($matches[3]) .'!';
        });

        // matches things like "bot is amazing!" and saves the attribute for later
        $this->addResponse('/is (the |a |an )*([\w ]+)/i', function($matches) use ($plugin) {
            $plugin->addAttribute(trim($matches[1] .' '. trim($matches[2])));
            return "No, *you're* {$matches[1]} ". trim($matches[2]) .'!';
        });

        // responds to things like "who is bot?" with a remembered attribute
        $this->addResponse('/(what|who) (are you|is)/i', function($matches) use ($plugin) {
            return "I'm ". $plugin->getRandomAttribute();
        });
    }


public function registerShortCode($tag, $callback)
    {
        if (is_callable($callback)) {
            $this->shortCodesTags[$tag] = $callback;
        }

        return $this;
    }

public function registerShortCode ( $ tag , $ callback ) { if ( is_callable ( $ callback ) ) { $ this -> shortCodesTags [ $ tag ] = $ callback ; } return $ this ; }

Register short code

@param string   $tag      tag name
@param callable $callback callback that will be triggered when tag will be processed

@return $this


public function removeShortCode($tag)
    {
        if (isset($this->shortCodesTags[$tag])) {
            unset($this->shortCodesTags[$tag]);
        }

        return $this;
    }

public function removeShortCode ( $ tag ) { if ( isset ( $ this -> shortCodesTags [ $ tag ] ) ) { unset ( $ this -> shortCodesTags [ $ tag ] ) ; } return $ this ; }

Remove short code

@param string $tag tag to be removed

@return $this


public function parseShortCodeTag($matches)
    {
        // allow [[foo]] syntax for escaping a tag
        if ($matches[1] == '[' && $matches[6] == ']') {
            return substr($matches[0], 1, -1);
        }

        $tag        = $matches[2];
        $attributes = $this->parseShortCodeAttributes($matches[3]);

        if (isset($matches[5])) {
            // enclosing tag - extra parameter
            return $matches[1] . call_user_func(
                $this->shortCodesTags[$tag],
                $attributes,
                $matches[5],
                $tag,
                $this
            ) . $matches[6];
        } else {
            // self-closing tag
            return $matches[1] . call_user_func(
                $this->shortCodesTags[$tag],
                $attributes,
                null,
                $tag,
                $this
            ) . $matches[6];
        }
    }

Parse short code tag

@param array $matches

@return string


protected function parseShortCodeAttributes($text)
    {
        $attributes = array();
        $pattern    =
            '/(\w+)\s*=\s*"([^"]*)"(?:\s|$)|(\w+)\s*=\s*\'([^\']*)\'(?:\s' .
            '|$)|(\w+)\s*=\s*([^\s\'"]+)(?:\s|$)|"([^"]*)"(?:\s|$)|(\S+)(?:\s|$)/';
        $text       = preg_replace("/[\x{00a0}\x{200b}]+/u", " ", $text);
        if (preg_match_all($pattern, $text, $matches, PREG_SET_ORDER)) {
            foreach ($matches as $match) {
                if (!empty($match[1])) {
                    $attributes[strtolower($match[1])] = stripcslashes($match[2]);
                } elseif (!empty($match[3])) {
                    $attributes[strtolower($match[3])] = stripcslashes($match[4]);
                } elseif (!empty($match[5])) {
                    $attributes[strtolower($match[5])] = stripcslashes($match[6]);
                } elseif (isset($match[7]) and strlen($match[7])) {
                    $attributes[] = stripcslashes($match[7]);
                } elseif (isset($match[8])) {
                    $attributes[] = stripcslashes($match[8]);
                }
            }
        } else {
            $attributes = ltrim($text);
        }

        return $attributes;
    }

Parse short code attributes

@param string $text short code attributes

@return array|string


function getDownloadURL($base, $packageinfo, $prefstate, $installed, $channel = false)
    {
        $states = $this->betterStates($prefstate, true);
        if (!$states) {
            return PEAR::raiseError('"' . $prefstate . '" is not a valid state');
        }

        $channel  = $packageinfo['channel'];
        $package  = $packageinfo['package'];
        $state    = isset($packageinfo['state'])   ? $packageinfo['state']   : null;
        $version  = isset($packageinfo['version']) ? $packageinfo['version'] : null;
        $restFile = $base . 'r/' . strtolower($package) . '/allreleases.xml';

        $info = $this->_rest->retrieveData($restFile, false, false, $channel);
        if (PEAR::isError($info)) {
            return PEAR::raiseError('No releases available for package "' .
                $channel . '/' . $package . '"');
        }

        if (!isset($info['r'])) {
            return false;
        }

        $release = $found = false;
        if (!is_array($info['r']) || !isset($info['r'][0])) {
            $info['r'] = array($info['r']);
        }

        foreach ($info['r'] as $release) {
            if (!isset($this->_rest->_options['force']) && ($installed &&
                  version_compare($release['v'], $installed, '<'))) {
                continue;
            }

            if (isset($state)) {
                // try our preferred state first
                if ($release['s'] == $state) {
                    $found = true;
                    break;
                }
                // see if there is something newer and more stable
                // bug #7221
                if (in_array($release['s'], $this->betterStates($state), true)) {
                    $found = true;
                    break;
                }
            } elseif (isset($version)) {
                if ($release['v'] == $version) {
                    $found = true;
                    break;
                }
            } else {
                if (in_array($release['s'], $states)) {
                    $found = true;
                    break;
                }
            }
        }

        return $this->_returnDownloadURL($base, $package, $release, $info, $found, false, $channel);
    }

Retrieve information about a remote package to be downloaded from a REST server

@param string $base The uri to prepend to all REST calls
@param array $packageinfo an array of format:
<pre>
array(
'package' => 'packagename',
'channel' => 'channelname',
['state' => 'alpha' (or valid state),]
-or-
['version' => '1.whatever']
</pre>
@param string $prefstate Current preferred_state config variable value
@param bool $installed the installed version of this package to compare against
@return array|false|PEAR_Error see {@link _returnDownloadURL()}


function listCategory($base, $category, $info = false, $channel = false)
    {
        // gives '404 Not Found' error when category doesn't exist
        $packagelist = $this->_rest->retrieveData($base.'c/'.urlencode($category).'/packages.xml', false, false, $channel);
        if (PEAR::isError($packagelist)) {
            return $packagelist;
        }

        if (!is_array($packagelist) || !isset($packagelist['p'])) {
            return array();
        }

        if (!is_array($packagelist['p']) ||
            !isset($packagelist['p'][0])) { // only 1 pkg
            $packagelist = array($packagelist['p']);
        } else {
            $packagelist = $packagelist['p'];
        }

        if ($info == true) {
            // get individual package info
            PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
            foreach ($packagelist as $i => $packageitem) {
                $url = sprintf('%s'.'r/%s/latest.txt',
                        $base,
                        strtolower($packageitem['_content']));
                $version = $this->_rest->retrieveData($url, false, false, $channel);
                if (PEAR::isError($version)) {
                    break; // skipit
                }
                $url = sprintf('%s'.'r/%s/%s.xml',
                        $base,
                        strtolower($packageitem['_content']),
                        $version);
                $info = $this->_rest->retrieveData($url, false, false, $channel);
                if (PEAR::isError($info)) {
                    break; // skipit
                }
                $packagelist[$i]['info'] = $info;
            }
            PEAR::popErrorHandling();
        }

        return $packagelist;
    }

List a category of a REST server

@param string $base base URL of the server
@param string $category name of the category
@param boolean $info also download full package info
@return array of packagenames


function _sortReleasesByVersionNumber($a, $b)
    {
        if (version_compare($a['v'], $b['v'], '=')) {
            return 0;
        }

        if (version_compare($a['v'], $b['v'], '>')) {
            return -1;
        }

        if (version_compare($a['v'], $b['v'], '<')) {
            return 1;
        }
    }

function _sortReleasesByVersionNumber ( $ a , $ b ) { if ( version_compare ( $ a [ 'v' ] , $ b [ 'v' ] , '=' ) ) { return 0 ; } if ( version_compare ( $ a [ 'v' ] , $ b [ 'v' ] , '>' ) ) { return - 1 ; } if ( version_compare ( $ a [ 'v' ] , $ b [ 'v' ] , '<' ) ) { return 1 ; } }

Sort releases by version number

@access private


public function getArrayData($id, $sens = 1, $date)
	{
		$this->date = $date;

		$this->uri =  new Uri('/horaires_ligne/index.asp');
		$this->uri->addParam('rub_code', 6);
		$this->uri->addParam('thm_id', 2);
		$this->uri->addParam('gpl_id', 0);
		$this->uri->addParam('lign_id', $id);
		$this->uri->addParam('sens', $sens);
		$this->uri->addParam('date', $this->date->format('d/m/Y'));

		return $this->allHours();
	}

public function getArrayData ( $ id , $ sens = 1 , $ date ) { $ this -> date = $ date ; $ this -> uri = new Uri ( '/horaires_ligne/index.asp' ) ; $ this -> uri -> addParam ( 'rub_code' , 6 ) ; $ this -> uri -> addParam ( 'thm_id' , 2 ) ; $ this -> uri -> addParam ( 'gpl_id' , 0 ) ; $ this -> uri -> addParam ( 'lign_id' , $ id ) ; $ this -> uri -> addParam ( 'sens' , $ sens ) ; $ this -> uri -> addParam ( 'date' , $ this -> date -> format ( 'd/m/Y' ) ) ; return $ this -> allHours ( ) ; }

Get array for an id
@param integer $id Line id
@param integer $sens 1 or 2
@param DateTime $date Schedule date
@return array Schedule in array representation


private function allHours()
	{
		$index = 1;
		$same = false;
		$hours = array();
		while(!$same)
		{
			# Get the page
			$this->uri->addParam('index', $index);
			$request = $this->client->get($this->uri);
			$resource = $request->getResource();
			if(!$resource->code(200))
			{
				return array('error' => 'fail to call Stac website');
			}
			$page = $resource->getContent();

			# Get page array representation
			$array = $this->parser($page);
			if(isset($previousArray))
			{
				# End condition when same page is called
				$compareId = 0;
				do
				{
					$comparePrevious = $previousArray[$compareId]['hours'][0];
					$compareCurrent = $array[$compareId]['hours'][0];
					$compareId++;
				}
				while($comparePrevious === '-');

				if($comparePrevious === $compareCurrent)
				{
					$same = true;
				}
				else
				{
					# Add new array informations
					$previousArray = $array;
					foreach($array as $pKey => $place)
					{
						foreach($place['hours'] as $hour){
							$hours[$pKey]['hours'][] = $hour;
						}
					}
				}
			}
			else
			{
				# First save of informations
				$previousArray = $array;
				$hours = $array;
			}
			$index+=6;
		}
		return $hours;
	}

Get all hours in an array
@return array Schedules line informations


private function parser($page)
	{
		$templateTime = clone $this->date;
		$hours = array();
		$array = array();

		# Get only table
		$page =  preg_replace('#(.+)\<tbody\>(.+)\<\/tbody\>(.+)#siU', '<table>$2</table>', $page);

		# save to DomDocument
		$dom = new DomDocument();
		libxml_use_internal_errors(true);

		# Load and save informations
		$dom->loadHTML($page);
		$raws = $dom->getElementsByTagName('tr');
		foreach($raws as $cKey => $raw)
		{
			if($cKey > 1)
			{
				$cells = $raw->getElementsByTagName('td');
				foreach($cells as $rKey => $cell)
				{
					$hours[$rKey][] = mb_convert_encoding($cell->nodeValue, mb_internal_encoding(), 'ISO-8859-1');
				}
			}
		}

		# Informations restructuration
		foreach($hours[0] as $placeKey => $place)
		{
			$size = count($hours);
			$array[$placeKey] =
			array(
				'place' => $place,
				'hours' => array()
			);
			for($i = 1; $i<$size; $i++)
			{
				$hourValue = $hours[$i][$placeKey];
				$hourValue = ($hourValue == '-') ? null : $hourValue;
				if(null !== $hourValue)
				{
					$cellHour = explode(':', $hourValue);
					$templateTime->setTime(intval($cellHour[0]), intval($cellHour[1]));
					$hourValue = $templateTime->getTimestamp();
				}
				$array[$placeKey]['hours'][] = $hourValue;
			}
		}
		return $array;
	}

private
function
parser
(
$
page
)
{
$
templateTime
=
clone
$
this
->
date
;
$
hours
=
array
(
)
;
$
array
=
array
(
)
;
# Get only table
$
page
=
preg_replace
(
'#(.+)\<tbody\>(.+)\<\/tbody\>(.+)#siU'
,
'<table>$2</table>'
,
$
page
)
;
# save to DomDocument
$
dom
=
new
DomDocument
(
)
;
libxml_use_internal_errors
(
true
)
;
# Load and save informations
$
dom
->
loadHTML
(
$
page
)
;
$
raws
=
$
dom
->
getElementsByTagName
(
'tr'
)
;
foreach
(
$
raws
as
$
cKey
=>
$
raw
)
{
if
(
$
cKey
>
1
)
{
$
cells
=
$
raw
->
getElementsByTagName
(
'td'
)
;
foreach
(
$
cells
as
$
rKey
=>
$
cell
)
{
$
hours
[
$
rKey
]
[
]
=
mb_convert_encoding
(
$
cell
->
nodeValue
,
mb_internal_encoding
(
)
,
'ISO-8859-1'
)
;
}
}
}
# Informations restructuration
foreach
(
$
hours
[
0
]
as
$
placeKey
=>
$
place
)
{
$
size
=
count
(
$
hours
)
;
$
array
[
$
placeKey
]
=
array
(
'place'
=>
$
place
,
'hours'
=>
array
(
)
)
;
for
(
$
i
=
1
;
$
i
<
$
size
;
$
i
++
)
{
$
hourValue
=
$
hours
[
$
i
]
[
$
placeKey
]
;
$
hourValue
=
(
$
hourValue
==
'-'
)
:
$
hourValue
;
if
(
!==
$
hourValue
)
{
$
cellHour
=
explode
(
':'
,
$
hourValue
)
;
$
templateTime
->
setTime
(
intval
(
$
cellHour
[
0
]
)
,
intval
(
$
cellHour
[
1
]
)
)
;
$
hourValue
=
$
templateTime
->
getTimestamp
(
)
;
}
$
array
[
$
placeKey
]
[
'hours'
]
[
]
=
$
hourValue
;
}
}
return
$
array
;
}

Parse a page
@param string $page Page to parse
@return array Schedule line informations for a page


public function findAllAccountByUserId($userId, $excludeVirtual = true)
    {
        $this->addWhere('user_id', $userId);

        if ($excludeVirtual) {
            $this->addWhere('account_id_parent', 0);
        }

        $query = 'SELECT ' . $this->getQueryFields() .
            ' FROM ' . $this->getTable() . ' ' .
            ' INNER JOIN money_account_user USING(account_id) ' .
            $this->getQueryWhere() . ' ' .
            $this->getQueryOrderBy() . ' ' .
            $this->getQueryLimit();

        return $this->query($query);
    }

Get list of account for given user.

@param  int $userId
@param  bool $excludeVirtual
@return \Eureka\Package\Money\DataMapper\Data\Money\Account[]


protected function applicationMessage(): void
    {
        output()->formatter()->magenta();
        output()->writeMessage('Valkyrja Application');
        output()->formatter()->resetColor();
        output()->writeMessage(' version ');
        output()->formatter()->cyan();
        output()->writeMessage(Application::VERSION, true);
        output()->formatter()->resetColor();
    }

protected
function
applicationMessage
(
)
:
void
{
output
(
)
->
formatter
(
)
->
magenta
(
)
;
output
(
)
->
writeMessage
(
'Valkyrja Application'
)
;
output
(
)
->
formatter
(
)
->
resetColor
(
)
;
output
(
)
->
writeMessage
(
' version '
)
;
output
(
)
->
formatter
(
)
->
cyan
(
)
;
output
(
)
->
writeMessage
(
Application
::
VERSION
,
true
)
;
output
(
)
->
formatter
(
)
->
resetColor
(
)
;
}


protected function usageMessage(string $message = null): void
    {
        $message = $message ?? $this->usagePath();

        $this->sectionTitleMessage('Usage');
        output()->writeMessage(static::TAB);
        output()->writeMessage($message, true);
    }

protected function usageMessage ( string $ message = null ) : void { $ message = $ message ?? $ this -> usagePath ( ) ; $ this -> sectionTitleMessage ( 'Usage' ) ; output ( ) -> writeMessage ( static :: TAB ) ; output ( ) -> writeMessage ( $ message , true ) ; }

The usage message and description.

@param string $message [optional] The usage to use instead of default

@return void


protected function usagePath(): string
    {
        $message = static::COMMAND;

        if ($this->getOptions()) {
            $message .= ' [options]';
        }

        foreach ($this->getArguments() as $argument) {
            $message .= ' '
                . ($argument->getMode() === ArgumentMode::OPTIONAL ? '[' : '')
                . '<'
                . $argument->getName()
                . '>'
                . ($argument->getMode() === ArgumentMode::OPTIONAL ? ']' : '');
        }

        return $message;
    }

protected
function
usagePath
(
)
:
string
{
$
message
=
static
::
COMMAND
;
if
(
$
this
->
getOptions
(
)
)
{
$
message
.=
' [options]'
;
}
foreach
(
$
this
->
getArguments
(
)
as
$
argument
)
{
$
message
.=
' '
.
(
$
argument
->
getMode
(
)
===
ArgumentMode
::
OPTIONAL
'['
:
''
)
.
'<'
.
$
argument
->
getName
(
)
.
'>'
.
(
$
argument
->
getMode
(
)
===
ArgumentMode
::
OPTIONAL
']'
:
''
)
;
}
return
$
message
;
}


protected function argumentsSection(Argument ...$arguments): void
    {
        if (! $arguments) {
            $arguments = $this->getArguments();
        }

        if (! $arguments) {
            return;
        }

        $longestLength = 0;

        $this->sectionDivider();
        $this->sectionTitleMessage('Arguments');

        foreach ($arguments as $argument) {
            $longestLength = max(\strlen($argument->getName()), $longestLength);
        }

        foreach ($arguments as $argument) {
            $this->sectionMessage(
                static::TAB . $argument->getName(),
                $argument->getDescription(),
                $longestLength
            );
        }
    }

protected function argumentsSection ( Argument ... $ arguments ) : void { if ( ! $ arguments ) { $ arguments = $ this -> getArguments ( ) ; } if ( ! $ arguments ) { return ; } $ longestLength = 0 ; $ this -> sectionDivider ( ) ; $ this -> sectionTitleMessage ( 'Arguments' ) ; foreach ( $ arguments as $ argument ) { $ longestLength = max ( \ strlen ( $ argument -> getName ( ) ) , $ longestLength ) ; } foreach ( $ arguments as $ argument ) { $ this -> sectionMessage ( static :: TAB . $ argument -> getName ( ) , $ argument -> getDescription ( ) , $ longestLength ) ; } }

The arguments section.

@param Argument[] ...$arguments The argument

@return void


protected function optionsSection(Option ...$options): void
    {
        if (! $options) {
            $options = $this->getOptions();
        }

        if (! $options) {
            return;
        }

        $longestLength = 0;

        $this->sectionDivider();
        $this->sectionTitleMessage('Options');

        foreach ($options as $option) {
            $longestLength =
                max(\strlen($this->getOptionName($option)), $longestLength);
        }

        foreach ($options as $option) {
            $this->sectionMessage(
                $this->getOptionName($option),
                $option->getDescription(),
                $longestLength
            );
        }
    }

protected function optionsSection ( Option ... $ options ) : void { if ( ! $ options ) { $ options = $ this -> getOptions ( ) ; } if ( ! $ options ) { return ; } $ longestLength = 0 ; $ this -> sectionDivider ( ) ; $ this -> sectionTitleMessage ( 'Options' ) ; foreach ( $ options as $ option ) { $ longestLength = max ( \ strlen ( $ this -> getOptionName ( $ option ) ) , $ longestLength ) ; } foreach ( $ options as $ option ) { $ this -> sectionMessage ( $ this -> getOptionName ( $ option ) , $ option -> getDescription ( ) , $ longestLength ) ; } }

The options section.

@param Option[] ...$options The options

@return void


protected function getOptionName(Option $option): string
    {
        $name = '';

        if ($option->getShortcut()) {
            $name .= '-' . $option->getShortcut() . ', ';
        } else {
            $name .= static::DOUBLE_TAB;
        }

        $name .= '--' . $option->getName();

        return $name;
    }

protected
function
getOptionName
(
Option
$
option
)
:
string
{
$
name
=
''
;
if
(
$
option
->
getShortcut
(
)
)
{
$
name
.=
'-'
.
$
option
->
getShortcut
(
)
.
', '
;
}
else
{
$
name
.=
static
::
DOUBLE_TAB
;
}
$
name
.=
'--'
.
$
option
->
getName
(
)
;
return
$
name
;
}

Get an options name for the options section.

@param Option $option The option

@return string

Get an options name for the options section .


public function generateRoll($rollSummary): Roll2d6DrdPlus
    {
        $rollSummary = ToInteger::toInteger($rollSummary);
        $bonusDiceRolls = [];
        $malusDiceRolls = [];
        if ($rollSummary <= 2) { // two ones = malus rolls and one "not valid" malus roll
            $standardDiceRolls = [new Dice1d6Roll(1, 1), new Dice1d6Roll(1, 2)]; // two ones = malus rolls
            $sequenceNumber = 3;
            for ($malusRollsCount = 2 - $rollSummary, $malusRollNumber = 1; $malusRollNumber <= $malusRollsCount; $malusRollNumber++) {
                /** @noinspection PhpUnhandledExceptionInspection */
                $malusDiceRolls[] = new Dice1d6DrdPlusMalusRoll(\random_int(1, 3), $sequenceNumber); // malus roll is valid only in range 1..3
                $sequenceNumber++;
            }
            /** @noinspection PhpUnhandledExceptionInspection */
            $malusDiceRolls[] = new Dice1d6DrdPlusMalusRoll(\random_int(4, 6), $sequenceNumber); // last malus roll was not "valid" - broke the chain
        } elseif ($rollSummary < 12) {
            $randomRange = 12 - $rollSummary; // 1..11
            $firstRandomMinimum = 6 - $randomRange;
            if ($firstRandomMinimum < 1) {
                $firstRandomMinimum = 1;
            }
            $firstRandomMaximum = $rollSummary - $firstRandomMinimum;
            /** @noinspection PhpUnhandledExceptionInspection */
            $firstRoll = \random_int($firstRandomMinimum, $firstRandomMaximum);
            $secondRoll = $rollSummary - $firstRoll;
            $firstDiceRoll = new Dice1d6Roll($firstRoll, 1);
            $secondDiceRoll = new Dice1d6Roll($secondRoll, 2);
            $standardDiceRolls = [$firstDiceRoll, $secondDiceRoll];
        } else { // two sixes = bonus rolls and one "not valid" bonus roll
            $standardDiceRolls = [new Dice1d6Roll(6, 1), new Dice1d6Roll(6, 2)];
            $sequenceNumber = 3;
            for ($bonusRollsCount = $rollSummary - 12, $bonusRollNumber = 1; $bonusRollNumber <= $bonusRollsCount; $bonusRollNumber++) {
                /** @noinspection PhpUnhandledExceptionInspection */
                $bonusDiceRolls[] = new Dice1d6DrdPlusBonusRoll(\random_int(4, 6), $sequenceNumber); // bonus roll is valid only in range 4..6
                $sequenceNumber++;
            }
            /** @noinspection PhpUnhandledExceptionInspection */
            $bonusDiceRolls[] = new Dice1d6DrdPlusBonusRoll(\random_int(1, 3), $sequenceNumber); // last bonus roll was not "valid" - broke the chain
        }

        return $this->createRoll($standardDiceRolls, $bonusDiceRolls, $malusDiceRolls);
    }

Warning! This will generate roll history randomly

@param int|IntegerInterface $rollSummary
@return Roll2d6DrdPlus
@throws \Granam\Integer\Tools\Exceptions\WrongParameterType
@throws \Granam\Integer\Tools\Exceptions\ValueLostOnCast


public function columns(array $columns, $prefixColumnsWithTable = true)
    {
        $this->has_modified_columns = true;
        $this->select->columns($columns, $prefixColumnsWithTable);
        return $this;
    }

public function columns ( array $ columns , $ prefixColumnsWithTable = true ) { $ this -> has_modified_columns = true ; $ this -> select -> columns ( $ columns , $ prefixColumnsWithTable ) ; return $ this ; }

Set the table columns to retrieve

@param array $columns array list of columns, key are used as aliases
@param boolean $prefixColumnsWithTable
@return TableSearch


public function having($predicate, $combination = Predicate\PredicateSet::OP_AND)
    {
        $this->select->having($predicate, $combination);
        return $this;
    }

public function having ( $ predicate , $ combination = Predicate \ PredicateSet :: OP_AND ) { $ this -> select -> having ( $ predicate , $ combination ) ; return $ this ; }

Set a habing option

@param  Where|\Closure|string|array $predicate
@param  string $combination One of the OP_* constants from Predicate\PredicateSet
@return Select

@return TableSearch


public function where($predicate, $combination = null)
    {
        $this->select->where($predicate, $combination);
        return $this;
    }

public function where ( $ predicate , $ combination = null ) { $ this -> select -> where ( $ predicate , $ combination ) ; return $ this ; }

Add a where condition

@param  Where|\Closure|string|array|Predicate\PredicateInterface $predicate
@param  string $combination One of the OP_* constants from Zend\Db\Sql\Predicate\PredicateSet
@throws Zend\Db\Sql\Exception\InvalidArgumentException
@return TableSearch


public function join($table, $on, $columns = [])
    {
        $prefixed_table = $this->prefixTableJoinCondition($table);

        //$this->columns($this->getPrefixedColumns());

        $this->select->join($prefixed_table, $on, $columns, Select::JOIN_INNER);
        return $this;
    }

Add an inner table join to the search

@param  string|array $table
@param  string $on
@param  string|array $columns by default won't retrieve any column from the joined table
@return TableSearch


public function joinLeft($table, $on, $columns = [])
    {
        $prefixed_table = $this->prefixTableJoinCondition($table);
        $this->select->join($prefixed_table, $on, $columns, Select::JOIN_LEFT);
        return $this;
    }

public function joinLeft ( $ table , $ on , $ columns = [ ] ) { $ prefixed_table = $ this -> prefixTableJoinCondition ( $ table ) ; $ this -> select -> join ( $ prefixed_table , $ on , $ columns , Select :: JOIN_LEFT ) ; return $ this ; }

Add an left outer table join to the search

@param  string|array $table
@param  string $on
@param  string|array $columns by default won't retrieve any column from the joined table
@return TableSearch


public function joinRight($table, $on, $columns = [])
    {
        $prefixed_table = $this->prefixTableJoinCondition($table);
        $this->select->join($prefixed_table, $on, $columns, Select::JOIN_RIGHT);
        return $this;
    }

public function joinRight ( $ table , $ on , $ columns = [ ] ) { $ prefixed_table = $ this -> prefixTableJoinCondition ( $ table ) ; $ this -> select -> join ( $ prefixed_table , $ on , $ columns , Select :: JOIN_RIGHT ) ; return $ this ; }

Add an right outer table join to the search

@param  string|array $table
@param  string $on
@param  string|array $columns by default won't retrieve any column from the joined table
@return TableSearch


public function getSql()
    {
        $adapterPlatform = $this->table->getTableManager()->getDbAdapter()->getPlatform();
        return $this->select->getSqlString($adapterPlatform);
    }

public function getSql ( ) { $ adapterPlatform = $ this -> table -> getTableManager ( ) -> getDbAdapter ( ) -> getPlatform ( ) ; return $ this -> select -> getSqlString ( $ adapterPlatform ) ; }


public function execute()
    {
        $rs = new ResultSet($this->select, $this->table, !$this->has_modified_columns);
        return $rs;
    }

public function execute ( ) { $ rs = new ResultSet ( $ this -> select , $ this -> table , ! $ this -> has_modified_columns ) ; return $ rs ; }

Return record as an array

@return ResultSet


protected function prefixTableJoinCondition($table)
    {
        $tm = $this->table->getTableManager();
        if (is_array($table)) {
            $alias = key($table);
            $prefixed_table = $tm->getPrefixedTable($table[$alias]);
            $table = [$alias => $prefixed_table];
        } elseif (is_string($table)) {
            $prefixed_table = $tm->getPrefixedTable($table);
            $table = $prefixed_table;
        }
        return $table;
    }

protected function prefixTableJoinCondition ( $ table ) { $ tm = $ this -> table -> getTableManager ( ) ; if ( is_array ( $ table ) ) { $ alias = key ( $ table ) ; $ prefixed_table = $ tm -> getPrefixedTable ( $ table [ $ alias ] ) ; $ table = [ $ alias => $ prefixed_table ] ; } elseif ( is_string ( $ table ) ) { $ prefixed_table = $ tm -> getPrefixedTable ( $ table ) ; $ table = $ prefixed_table ; } return $ table ; }

Prefix table join condition

@param string|array $table
@return array|string


public function get(string $key, $default = null) // : mixed
    {
        return $this->has($key)
            ? $this->collection[$key]
            : $default;
    }

public
function
get
(
string
$
key
,
$
default
=
)
// : mixed
{
return
$
this
->
has
(
$
key
)
$
this
->
collection
[
$
key
]
:
$
default
;
}

Get a single item from the collection.

@param string $key     The key to get
@param mixed  $default [optional] The default value

@return mixed


public function set(string $key, $value): self
    {
        $this->collection[$key] = $value;

        return $this;
    }

public function set ( string $ key , $ value ) : self { $ this -> collection [ $ key ] = $ value ; return $ this ; }

Set a new item into the collection.

@param string $key   The key
@param mixed  $value The value

@return self


public function remove(string $key): self
    {
        if (! $this->has($key)) {
            return $this;
        }

        unset($this->collection[$key]);

        return $this;
    }

public function remove ( string $ key ) : self { if ( ! $ this -> has ( $ key ) ) { return $ this ; } unset ( $ this -> collection [ $ key ] ) ; return $ this ; }

Remove an item from the collection.

@param string $key The key

@return self


public static function insert($table, array $set)
    {
        $sql = $values = $fields = $holders = [];
        $sql[] = 'INSERT INTO ' . static::e($table);

        foreach($set as $field => $value) {
            $fields[] = static::e($field);
            $holders[] = '?';
            $values[] = $value;
        }

        $sql[] = '(' . implode(', ', $fields) . ')';
        $sql[] = 'VALUES (' . implode(', ', $holders) . ')';

        $sql = implode("\n", $sql);
        return [$sql, $values];
    }

public
static
function
insert
(
$
table
,
array
$
set
)
{
$
sql
=
$
values
=
$
fields
=
$
holders
=
[
]
;
$
sql
[
]
=
'INSERT INTO '
.
static
::
e
(
$
table
)
;
foreach
(
$
set
as
$
field
=>
$
value
)
{
$
fields
[
]
=
static
::
e
(
$
field
)
;
$
holders
[
]
=
'?'
;
$
values
[
]
=
$
value
;
}
$
sql
[
]
=
'('
.
implode
(
', '
,
$
fields
)
.
')'
;
$
sql
[
]
=
'VALUES ('
.
implode
(
', '
,
$
holders
)
.
')'
;
$
sql
=
implode
(
"\n"
,
$
sql
)
;
return
[
$
sql
,
$
values
]
;
}

Compile INSERT INTO

@param string $table
@param array $set
@return array


function PEAR_ErrorStack($package, $msgCallback = false, $contextCallback = false,
                         $throwPEAR_Error = false)
    {
        $this->_package = $package;
        $this->setMessageCallback($msgCallback);
        $this->setContextCallback($contextCallback);
        $this->_compat = $throwPEAR_Error;
    }

function PEAR_ErrorStack ( $ package , $ msgCallback = false , $ contextCallback = false , $ throwPEAR_Error = false ) { $ this -> _package = $ package ; $ this -> setMessageCallback ( $ msgCallback ) ; $ this -> setContextCallback ( $ contextCallback ) ; $ this -> _compat = $ throwPEAR_Error ; }

Set up a new error stack

@param string   $package name of the package this error stack represents
@param callback $msgCallback callback used for error message generation
@param callback $contextCallback callback used for context generation,
defaults to {@link getFileLine()}
@param boolean  $throwPEAR_Error


function &singleton($package, $msgCallback = false, $contextCallback = false,
                         $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack')
    {
        if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
            return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package];
        }
        if (!class_exists($stackClass)) {
            if (function_exists('debug_backtrace')) {
                $trace = debug_backtrace();
            }
            PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS,
                'exception', array('stackclass' => $stackClass),
                'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)',
                false, $trace);
        }
        $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] =
            new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error);

        return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package];
    }

Return a single error stack for this package.

Note that all parameters are ignored if the stack for package $package
has already been instantiated
@param string   $package name of the package this error stack represents
@param callback $msgCallback callback used for error message generation
@param callback $contextCallback callback used for context generation,
defaults to {@link getFileLine()}
@param boolean  $throwPEAR_Error
@param string   $stackClass class to instantiate
@static
@return PEAR_ErrorStack

Return a single error stack for this package .


function _handleError($err)
    {
        if ($err['level'] == 'exception') {
            $message = $err['message'];
            if (isset($_SERVER['REQUEST_URI'])) {
                echo '<br />';
            } else {
                echo "\n";
            }
            var_dump($err['context']);
            die($message);
        }
    }

function
_handleError
(
$
err
)
{
if
(
$
err
[
'level'
]
==
'exception'
)
{
$
message
=
$
err
[
'message'
]
;
if
(
isset
(
$
_SERVER
[
'REQUEST_URI'
]
)
)
{
echo
'<br />'
;
}
else
{
echo
"\n"
;
}
var_dump
(
$
err
[
'context'
]
)
;
die
(
$
message
)
;
}
}

Internal error handler for PEAR_ErrorStack class

Dies if the error is an exception (and would have died anyway)
@access private


function setMessageCallback($msgCallback)
    {
        if (!$msgCallback) {
            $this->_msgCallback = array(&$this, 'getErrorMessage');
        } else {
            if (is_callable($msgCallback)) {
                $this->_msgCallback = $msgCallback;
            }
        }
    }

function setMessageCallback ( $ msgCallback ) { if ( ! $ msgCallback ) { $ this -> _msgCallback = array ( & $ this , 'getErrorMessage' ) ; } else { if ( is_callable ( $ msgCallback ) ) { $ this -> _msgCallback = $ msgCallback ; } } }

Set an error code => error message mapping callback

This method sets the callback that can be used to generate error
messages for any instance
@param array|string Callback function/method

Set an error code = > error message mapping callback


function setDefaultCallback($callback = false, $package = false)
    {
        if (!is_callable($callback)) {
            $callback = false;
        }
        $package = $package ? $package : '*';
        $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback;
    }

function setDefaultCallback ( $ callback = false , $ package = false ) { if ( ! is_callable ( $ callback ) ) { $ callback = false ; } $ package = $ package ? $ package : '*' ; $ GLOBALS [ '_PEAR_ERRORSTACK_DEFAULT_CALLBACK' ] [ $ package ] = $ callback ; }

Sets a default callback to be used by all error stacks

This method sets the callback that can be used to generate error
messages for a singleton
@param array|string Callback function/method
@param string Package name, or false for all packages
@static


function pop()
    {
        $err = @array_shift($this->_errors);
        if (!is_null($err)) {
            @array_pop($this->_errorsByLevel[$err['level']]);
            if (!count($this->_errorsByLevel[$err['level']])) {
                unset($this->_errorsByLevel[$err['level']]);
            }
        }
        return $err;
    }

function pop ( ) { $ err = @ array_shift ( $ this -> _errors ) ; if ( ! is_null ( $ err ) ) { @ array_pop ( $ this -> _errorsByLevel [ $ err [ 'level' ] ] ) ; if ( ! count ( $ this -> _errorsByLevel [ $ err [ 'level' ] ] ) ) { unset ( $ this -> _errorsByLevel [ $ err [ 'level' ] ] ) ; } } return $ err ; }

Pop an error off of the error stack

@return false|array
@since 0.4alpha it is no longer possible to specify a specific error
level to return - the last error pushed will be returned, instead


function staticPop($package)
    {
        if ($package) {
            if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
                return false;
            }
            return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->pop();
        }
    }

function staticPop ( $ package ) { if ( $ package ) { if ( ! isset ( $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] [ $ package ] ) ) { return false ; } return $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] [ $ package ] -> pop ( ) ; } }

Pop an error off of the error stack, static method

@param string package name
@return boolean
@since PEAR1.5.0a1

Pop an error off of the error stack static method


function hasErrors($level = false)
    {
        if ($level) {
            return isset($this->_errorsByLevel[$level]);
        }
        return count($this->_errors);
    }

function hasErrors ( $ level = false ) { if ( $ level ) { return isset ( $ this -> _errorsByLevel [ $ level ] ) ; } return count ( $ this -> _errors ) ; }

Determine whether there are any errors on the stack
@param string|array Level name.  Use to determine if any errors
of level (string), or levels (array) have been pushed
@return boolean


function getErrors($purge = false, $level = false)
    {
        if (!$purge) {
            if ($level) {
                if (!isset($this->_errorsByLevel[$level])) {
                    return array();
                } else {
                    return $this->_errorsByLevel[$level];
                }
            } else {
                return $this->_errors;
            }
        }
        if ($level) {
            $ret = $this->_errorsByLevel[$level];
            foreach ($this->_errorsByLevel[$level] as $i => $unused) {
                // entries are references to the $_errors array
                $this->_errorsByLevel[$level][$i] = false;
            }
            // array_filter removes all entries === false
            $this->_errors = array_filter($this->_errors);
            unset($this->_errorsByLevel[$level]);
            return $ret;
        }
        $ret = $this->_errors;
        $this->_errors = array();
        $this->_errorsByLevel = array();
        return $ret;
    }

Retrieve all errors since last purge

@param boolean set in order to empty the error stack
@param string level name, to return only errors of a particular severity
@return array


function staticHasErrors($package = false, $level = false)
    {
        if ($package) {
            if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) {
                return false;
            }
            return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level);
        }
        foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) {
            if ($obj->hasErrors($level)) {
                return true;
            }
        }
        return false;
    }

function staticHasErrors ( $ package = false , $ level = false ) { if ( $ package ) { if ( ! isset ( $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] [ $ package ] ) ) { return false ; } return $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] [ $ package ] -> hasErrors ( $ level ) ; } foreach ( $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] as $ package => $ obj ) { if ( $ obj -> hasErrors ( $ level ) ) { return true ; } } return false ; }

Determine whether there are any errors on a single error stack, or on any error stack

The optional parameter can be used to test the existence of any errors without the need of
singleton instantiation
@param string|false Package name to check for errors
@param string Level name to check for a particular severity
@return boolean
@static

Determine whether there are any errors on a single error stack or on any error stack


function staticGetErrors($purge = false, $level = false, $merge = false,
                             $sortfunc = array('PEAR_ErrorStack', '_sortErrors'))
    {
        $ret = array();
        if (!is_callable($sortfunc)) {
            $sortfunc = array('PEAR_ErrorStack', '_sortErrors');
        }
        foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) {
            $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level);
            if ($test) {
                if ($merge) {
                    $ret = array_merge($ret, $test);
                } else {
                    $ret[$package] = $test;
                }
            }
        }
        if ($merge) {
            usort($ret, $sortfunc);
        }
        return $ret;
    }

function staticGetErrors ( $ purge = false , $ level = false , $ merge = false , $ sortfunc = array ( 'PEAR_ErrorStack' , '_sortErrors' ) ) { $ ret = array ( ) ; if ( ! is_callable ( $ sortfunc ) ) { $ sortfunc = array ( 'PEAR_ErrorStack' , '_sortErrors' ) ; } foreach ( $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] as $ package => $ obj ) { $ test = $ GLOBALS [ '_PEAR_ERRORSTACK_SINGLETON' ] [ $ package ] -> getErrors ( $ purge , $ level ) ; if ( $ test ) { if ( $ merge ) { $ ret = array_merge ( $ ret , $ test ) ; } else { $ ret [ $ package ] = $ test ; } } } if ( $ merge ) { usort ( $ ret , $ sortfunc ) ; } return $ ret ; }

Get a list of all errors since last purge, organized by package
@since PEAR 1.4.0dev BC break! $level is now in the place $merge used to be
@param boolean $purge Set to purge the error stack of existing errors
@param string  $level Set to a level name in order to retrieve only errors of a particular level
@param boolean $merge Set to return a flat array, not organized by package
@param array   $sortfunc Function used to sort a merged array - default
sorts by time, and should be good for most cases
@static
@return array

Get a list of all errors since last purge organized by package


function getErrorMessage(&$stack, $err, $template = false)
    {
        if ($template) {
            $mainmsg = $template;
        } else {
            $mainmsg = $stack->getErrorMessageTemplate($err['code']);
        }
        $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg);
        if (is_array($err['params']) && count($err['params'])) {
            foreach ($err['params'] as $name => $val) {
                if (is_array($val)) {
                    // @ is needed in case $val is a multi-dimensional array
                    $val = @implode(', ', $val);
                }
                if (is_object($val)) {
                    if (method_exists($val, '__toString')) {
                        $val = $val->__toString();
                    } else {
                        PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING,
                            'warning', array('obj' => get_class($val)),
                            'object %obj% passed into getErrorMessage, but has no __toString() method');
                        $val = 'Object';
                    }
                }
                $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg);
            }
        }
        return $mainmsg;
    }

Standard error message generation callback

This method may also be called by a custom error message generator
to fill in template values from the params array, simply
set the third parameter to the error message template string to use

The special variable %__msg% is reserved: use it only to specify
where a message passed in by the user should be placed in the template,
like so:

Error message: %msg% - internal error

If the message passed like so:

<code>
$stack->push(ERROR_CODE, 'error', array(), 'server error 500');
</code>

The returned error message will be "Error message: server error 500 -
internal error"
@param PEAR_ErrorStack
@param array
@param string|false Pre-generated error message template
@static
@return string


public function registerConfiguration(array $configuration): void
    {
        foreach ($configuration as $identifier => $value) {
            $this->container->addEntry($identifier, new MixedEntry($value));
        }
    }

public function registerConfiguration ( array $ configuration ) : void { foreach ( $ configuration as $ identifier => $ value ) { $ this -> container -> addEntry ( $ identifier , new MixedEntry ( $ value ) ) ; } }

Registers an array with identifier value pairs to the container as mixed entries.
@param array $configuration The configuration array to register
@throws ContainerException If trying to register values that already exist

Registers an array with identifier value pairs to the container as mixed entries .


public function registerProvider(EntryProvider $provider): void
    {
        $class = \get_class($provider);

        $this->container->addEntry($class, new CallableEntry([\get_class($provider), 'initialize']));

        foreach ($provider->getMethods() as $identifier => $method) {
            $this->container->addEntry($identifier, new ProviderEntry([$provider, $method]));
        }
    }

public function registerProvider ( EntryProvider $ provider ) : void { $ class = \ get_class ( $ provider ) ; $ this -> container -> addEntry ( $ class , new CallableEntry ( [ \ get_class ( $ provider ) , 'initialize' ] ) ) ; foreach ( $ provider -> getMethods ( ) as $ identifier => $ method ) { $ this -> container -> addEntry ( $ identifier , new ProviderEntry ( [ $ provider , $ method ] ) ) ; } }

Registers the given provider as a callable and applicable methods as provider methods.
@param EntryProvider $provider The entry provider to register
@throws ContainerException If the provider tries to provide something that has already been registered

Registers the given provider as a callable and applicable methods as provider methods .


public function registerAutowiredClasses(array $classes, array $overrides = []): void
    {
        foreach ($classes as $class) {
            $reflection = new \ReflectionClass($class);
            $name = $reflection->getName();
            $parameters = $this->getWiredParameters($reflection, $overrides);

            $this->container->addEntry($name, new WiredEntry($name, $parameters));
        }
    }

public function registerAutowiredClasses ( array $ classes , array $ overrides = [ ] ) : void { foreach ( $ classes as $ class ) { $ reflection = new \ ReflectionClass ( $ class ) ; $ name = $ reflection -> getName ( ) ; $ parameters = $ this -> getWiredParameters ( $ reflection , $ overrides ) ; $ this -> container -> addEntry ( $ name , new WiredEntry ( $ name , $ parameters ) ) ; } }

Registers classes that can be wired automatically based on constructor arguments.
@param string[] $classes List of classes to register for autowiring
@param string[] $overrides Override identifiers for constructor parameters
@throws ContainerException If trying to register classes that have already been registered

Registers classes that can be wired automatically based on constructor arguments .


private function getWiredParameters(\ReflectionClass $reflection, array $overrides): array
    {
        $constructor = $reflection->getConstructor();

        if (!$constructor instanceof \ReflectionMethod) {
            return [];
        }

        $parameters = [];

        foreach ($constructor->getParameters() as $parameter) {
            $name = '$' . $parameter->getName();

            if (isset($overrides[$name])) {
                $parameters[] = $overrides[$name];
                continue;
            }

            $type = $parameter->getType();

            if (!$type instanceof \ReflectionType || $type->isBuiltin()) {
                throw new \InvalidArgumentException(
                    sprintf("Missing autowired parameter '%s' for '%s'", $name, $reflection->getName())
                );
            }

            $parameters[] = $type->getName();
        }

        return $parameters;
    }

Loads the parameter identifiers based on the constructor arguments and provided overrides.
@param \ReflectionClass $reflection The class reflection to inspect
@param string[] $overrides Override identifiers for constructor parameters
@return string[] Identifiers for constructor parameters

Loads the parameter identifiers based on the constructor arguments and provided overrides .


public function setTarget($target)
    {
        if (!file_exists(dirname($target))) {

            throw new Zend_Filter_Exception("The directory '$target' does not exist");
        }

        $target = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $target);
        $this->_options['target'] = (string) $target;
        return $this;
    }

Sets the targetpath to use

@param string $target
@return Zend_Filter_Compress_Tar


public function setMode($mode)
    {
        $mode = ucfirst(strtolower($mode));
        if (($mode != 'Bz2') && ($mode != 'Gz')) {

            throw new Zend_Filter_Exception("The mode '$mode' is unknown");
        }

        if (($mode == 'Bz2') && (!extension_loaded('bz2'))) {

            throw new Zend_Filter_Exception('This mode needs the bz2 extension');
        }

        if (($mode == 'Gz') && (!extension_loaded('zlib'))) {

            throw new Zend_Filter_Exception('This mode needs the zlib extension');
        }
    }

public
function
setMode
(
$
mode
)
{
$
mode
=
ucfirst
(
strtolower
(
$
mode
)
)
;
if
(
(
$
mode
!=
'Bz2'
)
&&
(
$
mode
!=
'Gz'
)
)
{
throw
new
Zend_Filter_Exception
(
"The mode '$mode' is unknown"
)
;
}
if
(
(
$
mode
==
'Bz2'
)
&&
(
!
extension_loaded
(
'bz2'
)
)
)
{
throw
new
Zend_Filter_Exception
(
'This mode needs the bz2 extension'
)
;
}
if
(
(
$
mode
==
'Gz'
)
&&
(
!
extension_loaded
(
'zlib'
)
)
)
{
throw
new
Zend_Filter_Exception
(
'This mode needs the zlib extension'
)
;
}
}

Compression mode to use
Eighter Gz or Bz2

@param string $mode


public function getRoutes(string ...$classes): array
    {
        $routes = $this->getClassRoutes($classes);
        /** @var \Valkyrja\Routing\Route[] $finalRoutes */
        $finalRoutes = [];

        // Iterate through all the routes
        foreach ($routes as $route) {
            // Set the route's properties
            $this->setRouteProperties($route);

            $classAnnotations = $this->classAnnotationsType(
                $this->routeAnnotationType,
                $route->getClass()
            );

            // If this route's class has annotations
            if ($classAnnotations) {
                /** @var Route $annotation */
                // Iterate through all the annotations
                foreach ($classAnnotations as $annotation) {
                    // And set a new route with the controller defined annotation additions
                    $finalRoutes[] =
                        $this->getRouteFromAnnotation(
                            $this->getControllerBuiltRoute($annotation, $route)
                        );
                }
            } else {
                // Validate the path before setting the route
                $route->setPath($this->validatePath($route->getPath()));

                // Otherwise just set the route in the final array
                $finalRoutes[] = $this->getRouteFromAnnotation($route);
            }
        }

        return $finalRoutes;
    }

Get routes.

@param string[] $classes The classes

@throws \InvalidArgumentException
@throws \ReflectionException
@throws \Valkyrja\Routing\Exceptions\InvalidRoutePath

@return \Valkyrja\Routing\Route[]


protected function setRouteProperties(Route $route): void
    {
        if (null === $route->getProperty()) {
            $methodReflection = $this->getMethodReflection(
                $route->getClass(),
                $route->getMethod() ?? '__construct'
            );

            // Set the dependencies
            $route->setDependencies(
                $this->getDependencies(...$methodReflection->getParameters())
            );
        }

        // Avoid having large arrays in cached routes file
        $route->setMatches();

        if (null === $route->getPath()) {
            throw new InvalidRoutePath(
                'Invalid route name for route : '
                . $route->getClass()
                . '@' . $route->getMethod()
            );
        }
    }

Set the route properties from arguments.

@param Route $route

@throws \ReflectionException
@throws \Valkyrja\Routing\Exceptions\InvalidRoutePath

@return void

Set the route properties from arguments .


protected function getClassRoutes(array $classes): array
    {
        /** @var \Valkyrja\Routing\Route[] $routes */
        $routes = [];

        // Iterate through all the classes
        foreach ($classes as $class) {
            $annotations = $this->classMembersAnnotationsType(
                $this->routeAnnotationType,
                $class
            );

            // Get all the routes for each class and iterate through them
            foreach ($annotations as $annotation) {
                // Set the annotation in the routes list
                $routes[] = $annotation;
            }
        }

        return $routes;
    }

Get all classes' routes.

@param array $classes The classes

@throws \ReflectionException

@return \Valkyrja\Routing\Route[]


protected function getControllerBuiltRoute(Route $controllerRoute, Route $route): Route
    {
        $newRoute = clone $route;

        // If there is a base path for this controller
        if (null !== $controllerRoute->getPath()) {
            // Get the route's path
            $path           = $this->validatePath($route->getPath());
            $controllerPath = $this->validatePath($controllerRoute->getPath());

            // Set the path to the base path and route path
            $newRoute->setPath($this->validatePath($controllerPath . $path));
        }

        // If there is a base name for this controller
        if (null !== $controllerRoute->getName()) {
            // Set the name to the base name and route name
            $newRoute->setName(
                $controllerRoute->getName() . '.' . $route->getName()
            );
        }

        // If the base is dynamic
        if (false !== $controllerRoute->isDynamic()) {
            // Set the route to dynamic
            $newRoute->setDynamic(true);
        }

        // If the base is secure
        if (false !== $controllerRoute->isSecure()) {
            // Set the route to dynamic
            $newRoute->setSecure(true);
        }

        // If there is a base middleware collection for this controller
        if (null !== $controllerRoute->getMiddleware()) {
            // Merge the route's middleware and the controller's middleware
            // keeping the controller's middleware first
            $middleware = array_merge(
                $controllerRoute->getMiddleware(),
                $route->getMiddleware() ?? []
            );

            // Set the middleware in the route
            $newRoute->setMiddleware($middleware);
        }

        return $newRoute;
    }

Get a new route with controller route additions.

@param Route $controllerRoute
@param Route $route

@return \Valkyrja\Routing\Annotations\Route

Get a new route with controller route additions .


protected function getRouteFromAnnotation(Route $route): RouterRoute
    {
        $routerRoute = new RouterRoute();

        $routerRoute
            ->setPath($route->getPath())
            ->setRegex($route->getRegex())
            ->setParams($route->getParams())
            ->setSegments($route->getSegments())
            ->setRequestMethods($route->getRequestMethods())
            ->setSecure($route->isSecure())
            ->setDynamic($route->isDynamic())
            ->setId($route->getId())
            ->setName($route->getName())
            ->setClass($route->getClass())
            ->setProperty($route->getProperty())
            ->setMethod($route->getMethod())
            ->setStatic($route->isStatic())
            ->setFunction($route->getFunction())
            ->setMatches($route->getMatches())
            ->setDependencies($route->getDependencies())
            ->setMiddleware($route->getMiddleware())
            ->setArguments($route->getArguments());

        return $routerRoute;
    }

protected function getRouteFromAnnotation ( Route $ route ) : RouterRoute { $ routerRoute = new RouterRoute ( ) ; $ routerRoute -> setPath ( $ route -> getPath ( ) ) -> setRegex ( $ route -> getRegex ( ) ) -> setParams ( $ route -> getParams ( ) ) -> setSegments ( $ route -> getSegments ( ) ) -> setRequestMethods ( $ route -> getRequestMethods ( ) ) -> setSecure ( $ route -> isSecure ( ) ) -> setDynamic ( $ route -> isDynamic ( ) ) -> setId ( $ route -> getId ( ) ) -> setName ( $ route -> getName ( ) ) -> setClass ( $ route -> getClass ( ) ) -> setProperty ( $ route -> getProperty ( ) ) -> setMethod ( $ route -> getMethod ( ) ) -> setStatic ( $ route -> isStatic ( ) ) -> setFunction ( $ route -> getFunction ( ) ) -> setMatches ( $ route -> getMatches ( ) ) -> setDependencies ( $ route -> getDependencies ( ) ) -> setMiddleware ( $ route -> getMiddleware ( ) ) -> setArguments ( $ route -> getArguments ( ) ) ; return $ routerRoute ; }

Get a route from a route annotation.

@param Route $route The route annotation

@throws \InvalidArgumentException

@return \Valkyrja\Routing\Route


public static function publish(Application $app): void
    {
        $app->container()->singleton(
            RouteAnnotations::class,
            new static(
                $app->container()->getSingleton(AnnotationsParser::class)
            )
        );
    }

public static function publish ( Application $ app ) : void { $ app -> container ( ) -> singleton ( RouteAnnotations :: class , new static ( $ app -> container ( ) -> getSingleton ( AnnotationsParser :: class ) ) ) ; }

Bind the route annotations.

@param Application $app The application

@return void


protected function formatJson($response)
    {
        $bodyRaw = $response->getRawBody();
        if ($bodyRaw !== null) {
            $options = $this->encodeOptions;
            if ($this->prettyPrint) {
                $options |= JSON_PRETTY_PRINT;
            }
            return $response->app instanceof Reaction\RequestApplicationInterface
                ? $response->app->helpers->json->encode($bodyRaw, $options)
                : Json::encode($bodyRaw, $options);
        }
        return '';
    }

protected function formatJson ( $ response ) { $ bodyRaw = $ response -> getRawBody ( ) ; if ( $ bodyRaw !== null ) { $ options = $ this -> encodeOptions ; if ( $ this -> prettyPrint ) { $ options |= JSON_PRETTY_PRINT ; } return $ response -> app instanceof Reaction \ RequestApplicationInterface ? $ response -> app -> helpers -> json -> encode ( $ bodyRaw , $ options ) : Json :: encode ( $ bodyRaw , $ options ) ; } return '' ; }

Formats response data in JSON format.
@param ResponseBuilderInterface $response
@return string


protected function formatJsonp($response)
    {
        $bodyRaw = $response->getRawBody();
        if (is_array($bodyRaw)
            && isset($bodyRaw['data'], $bodyRaw['callback'])
        ) {
            $data = $response->app instanceof Reaction\RequestApplicationInterface
                ? $response->app->helpers->json->htmlEncode($bodyRaw['data'])
                : Json::htmlEncode($bodyRaw['data']);
            return sprintf('%s(%s);', $bodyRaw['callback'], $data);
        } elseif ($bodyRaw !== null) {
            Reaction::warning(
                "The 'jsonp' response requires that the data be an array consisting of both 'data' and 'callback' elements."
            );
        }
        return '';
    }

Formats response data in JSONP format.
@param ResponseBuilderInterface $response
@return string


public function getHostPort(): string
    {
        $host = $this->getHost();

        if ($host && $port = $this->getPort()) {
            $host .= ':' . $port;
        }

        return $host;
    }

public function getHostPort ( ) : string { $ host = $ this -> getHost ( ) ; if ( $ host && $ port = $ this -> getPort ( ) ) { $ host .= ':' . $ port ; } return $ host ; }

Retrieve the host and port component of the URI.

If a port is present, and it is non-standard for the current scheme,
this method MUST return it, along with the host component, as
a string in a fashion akin to the following <host:port>.

If the port is the standard port used with the current scheme, this
method SHOULD return only the host component.

If no port is present, and no scheme is present, this method MUST return
only the host component.

If no port is present, no host is present, and no scheme is present,
this method MUST return an empty string.

If no port is resent, no host is present, and a scheme is present,
this method MUST return an empty string.

if no port is present, a host is present, and a scheme is present,
this method MUST return only the host component.

@return string

Retrieve the host and port component of the URI .


public function getSchemeHostPort(): string
    {
        $hostPort = $this->getHostPort();
        $scheme   = $this->getScheme();

        return $hostPort && $scheme ? $scheme . '://' . $hostPort : $hostPort;
    }

public function getSchemeHostPort ( ) : string { $ hostPort = $ this -> getHostPort ( ) ; $ scheme = $ this -> getScheme ( ) ; return $ hostPort && $ scheme ? $ scheme . '://' . $ hostPort : $ hostPort ; }

Retrieve the scheme, host, and port components of the URI.

If a scheme is present, a host is present, and a port is present,
and the port is non-standard for the current scheme, this method
MUST return the scheme, followed by the host, followed by the
port in a fashion akin to the following <scheme://host:port>.

If a scheme is present, a host is present, and a port is present,
and the port is standard for the current scheme, this method
MUST return only the scheme followed by the host, in a
fashion akin to the following <scheme://host>.

If a scheme is present, a host is present, and a port is not
present, this method MUST return only the scheme followed by
the host, in a fashion akin to the following <scheme://host>.

If a scheme is not present, a host is present, and a port is
present, this method MUST return only the host, followed by
the port, in a fashion akin to the following <host:port>.

If a scheme is not present, a host is present, and a port is
not present, this method MUST return only the host.

If a scheme is not present, a host is not present, and a port
is not present, this method MUST return an empty string.

If a scheme is present, a host is not present, and a port
is either present or not, this method MUST return an
empty string.

@return string

Retrieve the scheme host and port components of the URI .


public function withHost(string $host): Uri
    {
        if ($host === $this->host) {
            return clone $this;
        }

        $new = clone $this;

        $new->host = $host;

        return $new;
    }

public function withHost ( string $ host ) : Uri { if ( $ host === $ this -> host ) { return clone $ this ; } $ new = clone $ this ; $ new -> host = $ host ; return $ new ; }

Return an instance with the specified host.

This method MUST retain the state of the current instance, and return
an instance that contains the specified host.

An empty host value is equivalent to removing the host.

@param string $host The hostname to use with the new instance.

@throws \InvalidArgumentException for invalid hostnames.

@return static A new instance with the specified host.

Return an instance with the specified host .


public function withPort(int $port = null): Uri
    {
        if ($port === $this->port) {
            return clone $this;
        }

        $this->validatePort($port);

        $new = clone $this;

        $new->port = $port;

        return $new;
    }

public function withPort ( int $ port = null ) : Uri { if ( $ port === $ this -> port ) { return clone $ this ; } $ this -> validatePort ( $ port ) ; $ new = clone $ this ; $ new -> port = $ port ; return $ new ; }

Return an instance with the specified port.

This method MUST retain the state of the current instance, and return
an instance that contains the specified port.

Implementations MUST raise an exception for ports outside the
established TCP and UDP port ranges.

A null value provided for the port is equivalent to removing the port
information.

@param null|int $port The port to use with the new instance; a null value
removes the port information.

@throws \Valkyrja\HttpMessage\Exceptions\InvalidPort for invalid ports.

@return static A new instance with the specified port.

Return an instance with the specified port .


public function withPath(string $path): Uri
    {
        if ($path === $this->path) {
            return clone $this;
        }

        $path = $this->validatePath($path);

        $new = clone $this;

        $new->path = $path;

        return $new;
    }

public function withPath ( string $ path ) : Uri { if ( $ path === $ this -> path ) { return clone $ this ; } $ path = $ this -> validatePath ( $ path ) ; $ new = clone $ this ; $ new -> path = $ path ; return $ new ; }

Return an instance with the specified path.

This method MUST retain the state of the current instance, and return
an instance that contains the specified path.

The path can either be empty or absolute (starting with a slash) or
rootless (not starting with a slash). Implementations MUST support all
three syntaxes.

If the path is intended to be domain-relative rather than path relative
then it must begin with a slash ("/"). Paths not starting with a slash
("/") are assumed to be relative to some base path known to the
application or consumer.

Users can provide both encoded and decoded path characters.
Implementations ensure the correct encoding as outlined in getPath().

@param string $path The path to use with the new instance.

@throws \Valkyrja\HttpMessage\Exceptions\InvalidPath for invalid paths.

@return static A new instance with the specified path.

Return an instance with the specified path .


public function withQuery(string $query): Uri
    {
        if ($query === $this->query) {
            return clone $this;
        }

        $query = $this->validateQuery($query);

        $new = clone $this;

        $new->query = $query;

        return $new;
    }

public function withQuery ( string $ query ) : Uri { if ( $ query === $ this -> query ) { return clone $ this ; } $ query = $ this -> validateQuery ( $ query ) ; $ new = clone $ this ; $ new -> query = $ query ; return $ new ; }

Return an instance with the specified query string.

This method MUST retain the state of the current instance, and return
an instance that contains the specified query string.

Users can provide both encoded and decoded query characters.
Implementations ensure the correct encoding as outlined in getQuery().

An empty query string value is equivalent to removing the query string.

@param string $query The query string to use with the new instance.

@throws \Valkyrja\HttpMessage\Exceptions\InvalidQuery for invalid query
strings.

@return static A new instance with the specified query string.

Return an instance with the specified query string .


public function withFragment(string $fragment): Uri
    {
        if ($fragment === $this->fragment) {
            return clone $this;
        }

        $fragment = $this->validateFragment($fragment);

        $new = clone $this;

        $new->fragment = $fragment;

        return $new;
    }

public function withFragment ( string $ fragment ) : Uri { if ( $ fragment === $ this -> fragment ) { return clone $ this ; } $ fragment = $ this -> validateFragment ( $ fragment ) ; $ new = clone $ this ; $ new -> fragment = $ fragment ; return $ new ; }

Return an instance with the specified URI fragment.

This method MUST retain the state of the current instance, and return
an instance that contains the specified URI fragment.

Users can provide both encoded and decoded fragment characters.
Implementations ensure the correct encoding as outlined in getFragment().

An empty fragment value is equivalent to removing the fragment.

@param string $fragment The fragment to use with the new instance.

@return static A new instance with the specified fragment.

Return an instance with the specified URI fragment .


protected function isStandardPort(): bool
    {
        if (! $this->scheme) {
            return $this->host && ! $this->port;
        }

        if (! $this->host || ! $this->port) {
            return true;
        }

        return (static::HTTP_SCHEME === $this->scheme && $this->port === static::HTTP_PORT)
            || (static::HTTPS_SCHEME === $this->scheme && $this->port === static::HTTPS_PORT);
    }

protected function isStandardPort ( ) : bool { if ( ! $ this -> scheme ) { return $ this -> host && ! $ this -> port ; } if ( ! $ this -> host || ! $ this -> port ) { return true ; } return ( static :: HTTP_SCHEME === $ this -> scheme && $ this -> port === static :: HTTP_PORT ) || ( static :: HTTPS_SCHEME === $ this -> scheme && $ this -> port === static :: HTTPS_PORT ) ; }

Determine whether this uri is on a standard port for the scheme.

@return bool

Determine whether this uri is on a standard port for the scheme .


protected function validateScheme(string $scheme): string
    {
        $scheme = strtolower($scheme);
        $scheme = (string) preg_replace('#:(//)?$#', '', $scheme);

        if (! $scheme) {
            return '';
        }

        if (static::HTTP_SCHEME !== $scheme || $scheme !== static::HTTPS_SCHEME) {
            throw new InvalidScheme(
                sprintf(
                    'Invalid scheme "%s" specified; must be either "http" or "https"',
                    $scheme
                )
            );
        }

        return $scheme;
    }

Validate a scheme.

@param string $scheme The scheme

@throws \Valkyrja\HttpMessage\Exceptions\InvalidScheme

@return string


protected function validatePort(int $port = null): void
    {
        if ($port !== null && ($port < 1 || $port > 65535)) {
            throw new InvalidPort(
                sprintf(
                    'Invalid port "%d" specified; must be a valid TCP/UDP port',
                    $port
                )
            );
        }
    }

Validate a port.

@param int $port The port

@throws \Valkyrja\HttpMessage\Exceptions\InvalidPort

@return void


function validatePackage($pkg, &$dl, $params = array())
    {
        if (is_array($pkg) && isset($pkg['info'])) {
            $deps = $this->_dependencydb->getDependentPackageDependencies($pkg['info']);
        } else {
            $deps = $this->_dependencydb->getDependentPackageDependencies($pkg);
        }

        $fail = false;
        if ($deps) {
            if (!class_exists('PEAR_Downloader_Package')) {
                require_once 'PEAR/Downloader/Package.php';
            }

            $dp = &new PEAR_Downloader_Package($dl);
            if (is_object($pkg)) {
                $dp->setPackageFile($pkg);
            } else {
                $dp->setDownloadURL($pkg);
            }

            PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
            foreach ($deps as $channel => $info) {
                foreach ($info as $package => $ds) {
                    foreach ($params as $packd) {
                        if (strtolower($packd->getPackage()) == strtolower($package) &&
                              $packd->getChannel() == $channel) {
                            $dl->log(3, 'skipping installed package check of "' .
                                        $this->_registry->parsedPackageNameToString(
                                            array('channel' => $channel, 'package' => $package),
                                            true) .
                                        '", version "' . $packd->getVersion() . '" will be ' .
                                        'downloaded and installed');
                            continue 2; // jump to next package
                        }
                    }

                    foreach ($ds as $d) {
                        $checker = &new PEAR_Dependency2($this->_config, $this->_options,
                            array('channel' => $channel, 'package' => $package), $this->_state);
                        $dep = $d['dep'];
                        $required = $d['type'] == 'required';
                        $ret = $checker->_validatePackageDownload($dep, $required, array(&$dp));
                        if (is_array($ret)) {
                            $dl->log(0, $ret[0]);
                        } elseif (PEAR::isError($ret)) {
                            $dl->log(0, $ret->getMessage());
                            $fail = true;
                        }
                    }
                }
            }
            PEAR::popErrorHandling();
        }

        if ($fail) {
            return $this->raiseError(
                '%s cannot be installed, conflicts with installed packages');
        }

        return true;
    }

validate a downloaded package against installed packages

As of PEAR 1.4.3, this will only validate

@param array|PEAR_Downloader_Package|PEAR_PackageFile_v1|PEAR_PackageFile_v2
$pkg package identifier (either
array('package' => blah, 'channel' => blah) or an array with
index 'info' referencing an object)
@param PEAR_Downloader $dl
@param array $params full list of packages to install
@return true|PEAR_Error


function validateDependency1($dep, $params = array())
    {
        if (!isset($dep['optional'])) {
            $dep['optional'] = 'no';
        }

        list($newdep, $type) = $this->normalizeDep($dep);
        if (!$newdep) {
            return $this->raiseError("Invalid Dependency");
        }

        if (method_exists($this, "validate{$type}Dependency")) {
            return $this->{"validate{$type}Dependency"}($newdep, $dep['optional'] == 'no',
                $params, true);
        }
    }

function
validateDependency1
(
$
dep
,
$
params
=
array
(
)
)
{
if
(
!
isset
(
$
dep
[
'optional'
]
)
)
{
$
dep
[
'optional'
]
=
'no'
;
}
list
(
$
newdep
,
$
type
)
=
$
this
->
normalizeDep
(
$
dep
)
;
if
(
!
$
newdep
)
{
return
$
this
->
raiseError
(
"Invalid Dependency"
)
;
}
if
(
method_exists
(
$
this
,
"validate{$type}Dependency"
)
)
{
return
$
this
->
{
"validate{$type}Dependency"
}
(
$
newdep
,
$
dep
[
'optional'
]
==
'no'
,
$
params
,
true
)
;
}
}

validate a package . xml 1 . 0 dependency