protected function calculateRequestLength(&$headers)
    {
        $this->requestBody = $this->request->getBody();

        if (is_string($this->requestBody)) {
            $this->contentLength = strlen($this->requestBody);
        } elseif (is_resource($this->requestBody)) {
            $stat = fstat($this->requestBody);
            $this->contentLength = $stat['size'];
            rewind($this->requestBody);
        } else {
            $this->contentLength = $this->requestBody->getLength();
            $headers['content-type'] = 'multipart/form-data; boundary=' .
                                       $this->requestBody->getBoundary();
            $this->requestBody->rewind();
        }

        if (in_array($this->request->getMethod(), self::$bodyDisallowed)
            || 0 == $this->contentLength
        ) {
            // No body: send a Content-Length header nonetheless (request #12900),
            // but do that only for methods that require a body (bug #14740)
            if (in_array($this->request->getMethod(), self::$bodyRequired)) {
                $headers['content-length'] = 0;
            } else {
                unset($headers['content-length']);
                // if the method doesn't require a body and doesn't have a
                // body, don't send a Content-Type header. (request #16799)
                unset($headers['content-type']);
            }
        } else {
            if (empty($headers['content-type'])) {
                $headers['content-type'] = 'application/x-www-form-urlencoded';
            }
            // Content-Length should not be sent for chunked Transfer-Encoding (bug #20125)
            if (!isset($headers['transfer-encoding'])) {
                $headers['content-length'] = $this->contentLength;
            }
        }
    }

Calculates length of the request body, adds proper headers

@param array &$headers associative array of request headers, this method
will add proper 'Content-Length' and 'Content-Type'
headers to this array (or remove them if not needed)

Calculates length of the request body adds proper headers


public function executeCommand($command, array $input, $decorators = [])
    {
        $command = $this->mapInputToCommand($command, $input);

        $bus = $this->getCommandBus();

        // If any decorators are passed, we'll
        // filter through and register them
        // with the CommandBus, so that they
        // are executed first.
        foreach ($decorators as $decorator) {
            $bus->decorate($decorator);
        }

        return $bus->execute($command);
    }

public
function
executeCommand
(
$
command
,
array
$
input
,
$
decorators
=
[
]
)
{
$
command
=
$
this
->
mapInputToCommand
(
$
command
,
$
input
)
;
$
bus
=
$
this
->
getCommandBus
(
)
;
// If any decorators are passed, we'll
// filter through and register them
// with the CommandBus, so that they
// are executed first.
foreach
(
$
decorators
as
$
decorator
)
{
$
bus
->
decorate
(
$
decorator
)
;
}
return
$
bus
->
execute
(
$
command
)
;
}

Execute the command

@param  string $command
@param  array  $input
@param  array  $decorators

@return mixed


function _serializeValue($value, $tagName = null, $attributes = array())
    {
        if (is_array($value)) {
            $xml = $this->_serializeArray($value, $tagName, $attributes);
        } elseif (is_object($value)) {
            $xml = $this->_serializeObject($value, $tagName);
        } else {
            $tag = array(
                          'qname'      => $tagName,
                          'attributes' => $attributes,
                          'content'    => $value
                        );
            $xml = $this->_createXMLTag($tag);
        }
        return $xml;
    }

function _serializeValue ( $ value , $ tagName = null , $ attributes = array ( ) ) { if ( is_array ( $ value ) ) { $ xml = $ this -> _serializeArray ( $ value , $ tagName , $ attributes ) ; } elseif ( is_object ( $ value ) ) { $ xml = $ this -> _serializeObject ( $ value , $ tagName ) ; } else { $ tag = array ( 'qname' => $ tagName , 'attributes' => $ attributes , 'content' => $ value ) ; $ xml = $ this -> _createXMLTag ( $ tag ) ; } return $ xml ; }

serialize any value

This method checks for the type of the value and calls the appropriate method

@access private
@param  mixed     $value
@param  string    $tagName
@param  array     $attributes
@return string


protected function unpublishOthers($entity) {
        if(!$entity->isHead()) {
            $head = $entity->getHead();
            if($head->isPublished()) {
                $head->unpublish();
                $this->persist($head, false);
            }
        }

        foreach($entity->getVersions() as $version) {
            if($version !== $entity && $version->isPublished()) {
                $version->unpublish();
                $this->persist($version, false);
            }
        }
    }

protected function unpublishOthers ( $ entity ) { if ( ! $ entity -> isHead ( ) ) { $ head = $ entity -> getHead ( ) ; if ( $ head -> isPublished ( ) ) { $ head -> unpublish ( ) ; $ this -> persist ( $ head , false ) ; } } foreach ( $ entity -> getVersions ( ) as $ version ) { if ( $ version !== $ entity && $ version -> isPublished ( ) ) { $ version -> unpublish ( ) ; $ this -> persist ( $ version , false ) ; } } }

Ensures that only one entity can be published at a time.

@param object $entity
@return void

Ensures that only one entity can be published at a time .


public function setClassName($className)
    {
        $className = (string) $className;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($className)) {
            throw new Exception\InvalidArgumentException('Class Name must be a non-empty string.');
        }

        $this->className = $className;

        return $this;
    }

Sets the ClassName value.

@param string $className

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setIdColumn($idColumn)
    {
        $idColumn = (string) $idColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($idColumn)) {
            throw new Exception\InvalidArgumentException('ID column must be a non-empty string.');
        }

        $this->idColumn = $idColumn;

        return $this;
    }

Sets the IdColumn value.

@param string $idColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setNameColumn($nameColumn)
    {
        $nameColumn = (string) $nameColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($nameColumn)) {
            throw new Exception\InvalidArgumentException('Name column must be a non-empty string.');
        }

        $this->nameColumn = $nameColumn;

        return $this;
    }

Sets the NameColumn value.

@param string $nameColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setDataColumn($dataColumn)
    {
        $dataColumn = (string) $dataColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($dataColumn)) {
            throw new Exception\InvalidArgumentException('Data column must be a non-empty string.');
        }

        $this->dataColumn = $dataColumn;

        return $this;
    }

Sets the DataColumn value.

@param string $dataColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setLifetimeColumn($lifetimeColumn)
    {
        $lifetimeColumn = (string) $lifetimeColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($lifetimeColumn)) {
            throw new Exception\InvalidArgumentException('Lifetime column must be a non-empty string.');
        }

        $this->lifetimeColumn = $lifetimeColumn;

        return $this;
    }

Sets the LifetimeColumn value.

@param string $lifetimeColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setModifiedColumn($modifiedColumn)
    {
        $modifiedColumn = (string) $modifiedColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($modifiedColumn)) {
            throw new Exception\InvalidArgumentException('Modified column must be a non-empty string.');
        }

        $this->modifiedColumn = $modifiedColumn;

        return $this;
    }

Sets the ModifiedColumn value.

@param string $modifiedColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public function setCreatedColumn($createdColumn)
    {
        $createdColumn = (string) $createdColumn;

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($createdColumn)) {
            throw new Exception\InvalidArgumentException('Created column must be a non-empty string.');
        }

        $this->createdColumn = $createdColumn;

        return $this;
    }

Sets the CreatedColumn value.

@param string $createdColumn

@return $this
@throws \Xloit\Bridge\Zend\Session\Exception\InvalidArgumentException


public static function providers()
    {
        return collect(Settings::first()->fillable)->filter(function ($value) {
            return strpos($value, '_client_id') !== false;
        })->map(function ($value) {
            return str_replace('_client_id', '', $value);
        })->toArray();
    }

public static function providers ( ) { return collect ( Settings :: first ( ) -> fillable ) -> filter ( function ( $ value ) { return strpos ( $ value , '_client_id' ) !== false ; } ) -> map ( function ( $ value ) { return str_replace ( '_client_id' , '' , $ value ) ; } ) -> toArray ( ) ; }

Return all the providers supported.

@return array


public static function availableProviders()
    {
        $settings = Settings::first();

        return collect(static::providers())->filter(function ($value) use ($settings) {
            $ci = $value.'_client_id';
            $cs = $value.'_client_secret';

            return $settings->$ci && $settings->$cs;
        })->toArray();
    }

public static function availableProviders ( ) { $ settings = Settings :: first ( ) ; return collect ( static :: providers ( ) ) -> filter ( function ( $ value ) use ( $ settings ) { $ ci = $ value . '_client_id' ; $ cs = $ value . '_client_secret' ; return $ settings -> $ ci && $ settings -> $ cs ; } ) -> toArray ( ) ; }

Returns all the available providers.

@return array


public function boot(Application $app)
    {
        $app->before(array($this, "setRequestFormat"), Application::EARLY_EVENT);
        $app->before(array($this, "validateRequestContentType"), Application::EARLY_EVENT);
    }

public function boot ( Application $ app ) { $ app -> before ( array ( $ this , "setRequestFormat" ) , Application :: EARLY_EVENT ) ; $ app -> before ( array ( $ this , "validateRequestContentType" ) , Application :: EARLY_EVENT ) ; }

Add filters to check that the request and repsonse formats are supported
by the application.

@param Application $app

Add filters to check that the request and repsonse formats are supported by the application .


public function register(Container $app)
    {
        $app["conneg.responseFormats"] = array("html");
        $app["conneg.requestFormats"] = array("form");
        $app["conneg.defaultFormat"] = "html";

        $app["conneg"] = function (Container $app) {
            if ($app->offsetExists("serializer")) {
                if ($app["serializer"] instanceof JMS\Serializer) {
                    if (!$app->offsetExists("conneg.serializationContext")) {
                        $app["conneg.serializationContext"] = null;
                    }
                    if (!$app->offsetExists("conneg.deserializationContext")) {
                        $app["conneg.deserializationContext"] = null;
                    }

                    return new JmsSerializerContentNegotiation($app);
                } elseif ($app["serializer"] instanceof SymfonySerializer\Serializer) {
                    if (!$app->offsetExists("conneg.serializationContext")) {
                        $app["conneg.serializationContext"] = array();
                    }
                    if (!$app->offsetExists("conneg.deserializationContext")) {
                        $app["conneg.deserializationContext"] = array();
                    }

                    return new SymfonySerializerContentNegotiation($app);
                }
            }

            throw new ServiceUnavailableHttpException(null, "No supported serializer found");
        };
    }

public
function
register
(
Container
$
app
)
{
$
app
[
"conneg.responseFormats"
]
=
array
(
"html"
)
;
$
app
[
"conneg.requestFormats"
]
=
array
(
"form"
)
;
$
app
[
"conneg.defaultFormat"
]
=
"html"
;
$
app
[
"conneg"
]
=
function
(
Container
$
app
)
{
if
(
$
app
->
offsetExists
(
"serializer"
)
)
{
if
(
$
app
[
"serializer"
]
instanceof
JMS
\
Serializer
)
{
if
(
!
$
app
->
offsetExists
(
"conneg.serializationContext"
)
)
{
$
app
[
"conneg.serializationContext"
]
=
;
}
if
(
!
$
app
->
offsetExists
(
"conneg.deserializationContext"
)
)
{
$
app
[
"conneg.deserializationContext"
]
=
;
}
return
new
JmsSerializerContentNegotiation
(
$
app
)
;
}
elseif
(
$
app
[
"serializer"
]
instanceof
SymfonySerializer
\
Serializer
)
{
if
(
!
$
app
->
offsetExists
(
"conneg.serializationContext"
)
)
{
$
app
[
"conneg.serializationContext"
]
=
array
(
)
;
}
if
(
!
$
app
->
offsetExists
(
"conneg.deserializationContext"
)
)
{
$
app
[
"conneg.deserializationContext"
]
=
array
(
)
;
}
return
new
SymfonySerializerContentNegotiation
(
$
app
)
;
}
}
throw
new
ServiceUnavailableHttpException
(
,
"No supported serializer found"
)
;
}
;
}

Set defaults and build the conneg service.

@param Container $app
@throws ServiceUnavailableHttpException

Set defaults and build the conneg service .


public function setRequestFormat(Request $request, Application $app)
    {
        // If there is no Accept header, do nothing
        if (!$request->headers->get("Accept")) {
            return;
        }

        // Check the Accept header for acceptable formats
        foreach ($request->getAcceptableContentTypes() as $contentType) {
            // If any format is acceptable, do nothing
            if ($contentType === "*/*") {
                return;
            }

            $format = $request->getFormat($contentType);
            if (in_array($format, $app["conneg.responseFormats"])) {
                // An acceptable format was found.  Set it as the requestFormat
                // where it can be referenced later.
                $request->setRequestFormat($format);
                return;
            }
        }

        // No acceptable formats were found
        throw new NotAcceptableHttpException();
    }

This before middleware validates whether the application will be able to
respond in a format that the client understands.

@param Request $request
@throws NotAcceptableHttpException

This before middleware validates whether the application will be able to respond in a format that the client understands .


public function validateRequestContentType(Request $request, Application $app)
    {
        // Define the "form" format so we can use it for validation
        $request->setFormat("form", array("application/x-www-form-urlencoded", "multipart/form-data"));

        $format = $request->getContentType();
        if (strlen($request->getContent()) > 0 && !in_array($format, $app["conneg.requestFormats"])) {
            // The request has a body but it is not a supported media type
            throw new UnsupportedMediaTypeHttpException();
        }
    }

This before middleware validates that the request body is in a format
that the application understands.

@param Request $request
@throws UnsupportedMediaTypeHttpException

This before middleware validates that the request body is in a format that the application understands .


public function execute(array $args, FunctionProphecy $function)
    {
        $value = array_shift($this->returnValues);

        if (!count($this->returnValues)) {
            $this->returnValues[] = $value;
        }

        return $value;
    }

public function execute ( array $ args , FunctionProphecy $ function ) { $ value = array_shift ( $ this -> returnValues ) ; if ( ! count ( $ this -> returnValues ) ) { $ this -> returnValues [ ] = $ value ; } return $ value ; }

Returns saved values one by one until last one, then continuously returns last value.

@param array          $args
@param FunctionProphecy $function

@return mixed

Returns saved values one by one until last one then continuously returns last value .


function discover($channel)
    {
        $this->log(1, 'Attempting to discover channel "' . $channel . '"...');
        PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
        $callback = $this->ui ? array(&$this, '_downloadCallback') : null;
        if (!class_exists('System')) {
            require_once 'System.php';
        }

        $tmpdir = $this->config->get('temp_dir');
        $tmp = System::mktemp('-d -t "' . $tmpdir . '"');
        $a   = $this->downloadHttp('http://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
        PEAR::popErrorHandling();
        if (PEAR::isError($a)) {
            // Attempt to fallback to https automatically.
            PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
            $this->log(1, 'Attempting fallback to https instead of http on channel "' . $channel . '"...');
            $a = $this->downloadHttp('https://' . $channel . '/channel.xml', $this->ui, $tmp, $callback, false);
            PEAR::popErrorHandling();
            if (PEAR::isError($a)) {
                return false;
            }
        }

        list($a, $lastmodified) = $a;
        if (!class_exists('PEAR_ChannelFile')) {
            require_once 'PEAR/ChannelFile.php';
        }

        $b = new PEAR_ChannelFile;
        if ($b->fromXmlFile($a)) {
            unlink($a);
            if ($this->config->get('auto_discover')) {
                $this->_registry->addChannel($b, $lastmodified);
                $alias = $b->getName();
                if ($b->getName() == $this->_registry->channelName($b->getAlias())) {
                    $alias = $b->getAlias();
                }

                $this->log(1, 'Auto-discovered channel "' . $channel .
                    '", alias "' . $alias . '", adding to registry');
            }

            return true;
        }

        unlink($a);
        return false;
    }

Attempt to discover a channel's remote capabilities from
its server name
@param string
@return boolean

Attempt to discover a channel s remote capabilities from its server name


function &getDependency2Object(&$c, $i, $p, $s)
    {
        if (!class_exists('PEAR_Dependency2')) {
            require_once 'PEAR/Dependency2.php';
        }
        $z = &new PEAR_Dependency2($c, $i, $p, $s);
        return $z;
    }

function & getDependency2Object ( & $ c , $ i , $ p , $ s ) { if ( ! class_exists ( 'PEAR_Dependency2' ) ) { require_once 'PEAR/Dependency2.php' ; } $ z = & new PEAR_Dependency2 ( $ c , $ i , $ p , $ s ) ; return $ z ; }

For simpler unit-testing
@param PEAR_Config
@param array
@param array
@param int


function getDownloadDir()
    {
        if (isset($this->_downloadDir)) {
            return $this->_downloadDir;
        }

        $downloaddir = $this->config->get('download_dir');
        if (empty($downloaddir) || (is_dir($downloaddir) && !is_writable($downloaddir))) {
            if  (is_dir($downloaddir) && !is_writable($downloaddir)) {
                $this->log(0, 'WARNING: configuration download directory "' . $downloaddir .
                    '" is not writeable.  Change download_dir config variable to ' .
                    'a writeable dir to avoid this warning');
            }

            if (!class_exists('System')) {
                require_once 'System.php';
            }

            if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
                return $downloaddir;
            }
            $this->log(3, '+ tmp dir created at ' . $downloaddir);
        }

        if (!is_writable($downloaddir)) {
            if (PEAR::isError(System::mkdir(array('-p', $downloaddir))) ||
                  !is_writable($downloaddir)) {
                return PEAR::raiseError('download directory "' . $downloaddir .
                    '" is not writeable.  Change download_dir config variable to ' .
                    'a writeable dir');
            }
        }

        return $this->_downloadDir = $downloaddir;
    }

Retrieve the directory that downloads will happen in
@access private
@return string


function _detectDepCycle(&$deplinks)
    {
        do {
            $keepgoing = false;
            foreach ($deplinks as $dep => $parents) {
                foreach ($parents as $parent => $unused) {
                    // reset the parent cycle detector
                    $this->_testCycle(null, null, null);
                    if ($this->_testCycle($dep, $deplinks, $parent)) {
                        $keepgoing = true;
                        unset($deplinks[$dep][$parent]);
                        if (count($deplinks[$dep]) == 0) {
                            unset($deplinks[$dep]);
                        }

                        continue 3;
                    }
                }
            }
        } while ($keepgoing);
    }

function
_detectDepCycle
(
&
$
deplinks
)
{
do
{
$
keepgoing
=
false
;
foreach
(
$
deplinks
as
$
dep
=>
$
parents
)
{
foreach
(
$
parents
as
$
parent
=>
$
unused
)
{
// reset the parent cycle detector
$
this
->
_testCycle
(
,
,
)
;
if
(
$
this
->
_testCycle
(
$
dep
,
$
deplinks
,
$
parent
)
)
{
$
keepgoing
=
true
;
unset
(
$
deplinks
[
$
dep
]
[
$
parent
]
)
;
if
(
count
(
$
deplinks
[
$
dep
]
)
==
0
)
{
unset
(
$
deplinks
[
$
dep
]
)
;
}
continue
3
;
}
}
}
}
while
(
$
keepgoing
)
;
}

Detect recursive links between dependencies and break the cycles

@param array
@access private


function _setupGraph($t, $reg, &$deplinks, &$nodes, $package)
    {
        foreach ($t as $dep) {
            $depchannel = !isset($dep['channel']) ? '__uri': $dep['channel'];
            $dname = $reg->parsedPackageNameToString(
                  array(
                      'channel' => $depchannel,
                      'package' => strtolower($dep['name']),
                  ));

            if (isset($nodes[$dname])) {
                if (!isset($deplinks[$dname])) {
                    $deplinks[$dname] = array();
                }
                $deplinks[$dname][$package] = 1;
            }
        }
    }

function _setupGraph ( $ t , $ reg , & $ deplinks , & $ nodes , $ package ) { foreach ( $ t as $ dep ) { $ depchannel = ! isset ( $ dep [ 'channel' ] ) ? '__uri' : $ dep [ 'channel' ] ; $ dname = $ reg -> parsedPackageNameToString ( array ( 'channel' => $ depchannel , 'package' => strtolower ( $ dep [ 'name' ] ) , ) ) ; if ( isset ( $ nodes [ $ dname ] ) ) { if ( ! isset ( $ deplinks [ $ dname ] ) ) { $ deplinks [ $ dname ] = array ( ) ; } $ deplinks [ $ dname ] [ $ package ] = 1 ; } } }

Set up the dependency for installation parsing

@param array $t dependency information
@param PEAR_Registry $reg
@param array $deplinks list of dependency links already established
@param array $nodes all existing package nodes
@param string $package parent package name
@access private


public function getUrlArg($param = null, $default = false)
    {
        $routes = CarteBlanche::getContainer()->get('router')->getRouteParsed();
        if (!empty($routes)) {
            if ($param=='args') {
                if (isset($routes['args']))
                    return $routes['args'];
            } else {
                if (isset($routes[$param]))
                    return $routes[$param];
                if (isset($routes['args'][$param]))
                    return $routes['args'][$param];
            }
        }
        return $default;
    }

public function getUrlArg ( $ param = null , $ default = false ) { $ routes = CarteBlanche :: getContainer ( ) -> get ( 'router' ) -> getRouteParsed ( ) ; if ( ! empty ( $ routes ) ) { if ( $ param == 'args' ) { if ( isset ( $ routes [ 'args' ] ) ) return $ routes [ 'args' ] ; } else { if ( isset ( $ routes [ $ param ] ) ) return $ routes [ $ param ] ; if ( isset ( $ routes [ 'args' ] [ $ param ] ) ) return $ routes [ 'args' ] [ $ param ] ; } } return $ default ; }

Get the value of a specific argument value from current parsed URL

@param   string  $param      The parameter name if so, or 'args' to get all parameters values
@param   mixed   $default    The default value sent if the argument is not setted
@return  string  The value retrieved, $default otherwise


public function outputLine($string = '', $translate = true)
    {
        if ($translate) {
            \cli\line($this->getLang()->__($string));
        } else {
            \cli\line($string);
        }
    }

public function outputLine ( $ string = '' , $ translate = true ) { if ( $ translate ) { \ cli \ line ( $ this -> getLang ( ) -> __ ( $ string ) ) ; } else { \ cli \ line ( $ string ) ; } }

Outputs a new line

@param string $string The output we want to display to the console out
@param bool $translate Whether the string should be sent through the mithra62\Language object
@return void


public function getArgs($strict = false, $force = false)
    {
        if (is_null($this->args) || $force) {
            $this->args = new \cli\Arguments($strict);
            $this->args->addFlag(array(
                'verbose',
                'v'
            ), 'Turn on verbose output');
            $this->args->addFlag('version', 'Display the version');
            $this->args->addFlag(array(
                'help',
                'h'
            ), 'Show this help screen');
        }

        return $this->args;
    }

public
function
getArgs
(
$
strict
=
false
,
$
force
=
false
)
{
if
(
is_null
(
$
this
->
args
)
||
$
force
)
{
$
this
->
args
=
new
\
cli
\
Arguments
(
$
strict
)
;
$
this
->
args
->
addFlag
(
array
(
'verbose'
,
'v'
)
,
'Turn on verbose output'
)
;
$
this
->
args
->
addFlag
(
'version'
,
'Display the version'
)
;
$
this
->
args
->
addFlag
(
array
(
'help'
,
'h'
)
,
'Show this help screen'
)
;
}
return
$
this
->
args
;
}

Returns the available commands the Console provides
@see \cli\Arguments
@param string $strict
@param string $force
@return \cli\Arguments


private function registerNoCaptcha()
    {
        $this->singleton(Contracts\NoCaptcha::class, function($app) {
            /** @var  \Illuminate\Config\Repository  $config */
            $config = $app['config'];

            return new NoCaptcha(
                $config->get('no-captcha.secret'),
                $config->get('no-captcha.sitekey'),
                $config->get('no-captcha.lang'),
                $config->get('no-captcha.attributes', [])
            );
        });

        $this->singleton('arcanedev.no-captcha', Contracts\NoCaptcha::class);
    }


private function registerValidatorRules($app)
    {
        $app['validator']->extend('captcha', function($attribute, $value) use ($app) {
            unset($attribute);
            $ip = $app['request']->getClientIp();

            return $app[Contracts\NoCaptcha::class]->verify($value, $ip);
        });
    }

private function registerValidatorRules ( $ app ) { $ app [ 'validator' ] -> extend ( 'captcha' , function ( $ attribute , $ value ) use ( $ app ) { unset ( $ attribute ) ; $ ip = $ app [ 'request' ] -> getClientIp ( ) ; return $ app [ Contracts \ NoCaptcha :: class ] -> verify ( $ value , $ ip ) ; } ) ; }

Register Validator rules.

@param  \Illuminate\Foundation\Application  $app


private function registerFormMacros($app)
    {
        if ($app->bound('form')) {
            $app['form']->macro('captcha', function($name = null, array $attributes = []) use ($app) {
                return $app[Contracts\NoCaptcha::class]->display($name, $attributes);
            });
        }
    }

private function registerFormMacros ( $ app ) { if ( $ app -> bound ( 'form' ) ) { $ app [ 'form' ] -> macro ( 'captcha' , function ( $ name = null , array $ attributes = [ ] ) use ( $ app ) { return $ app [ Contracts \ NoCaptcha :: class ] -> display ( $ name , $ attributes ) ; } ) ; } }

Register Form Macros.

@param  \Illuminate\Foundation\Application  $app


function fromXmlFile($descfile)
    {
        if (!file_exists($descfile) || !is_file($descfile) || !is_readable($descfile) ||
             (!$fp = fopen($descfile, 'r'))) {
            require_once 'PEAR.php';
            return PEAR::raiseError("Unable to open $descfile");
        }

        // read the whole thing so we only get one cdata callback
        // for each block of cdata
        fclose($fp);
        $data = file_get_contents($descfile);
        return $this->fromXmlString($data);
    }

Parse a channel.xml file.  Expects the name of
a channel xml file as input.

@param string  $descfile  name of channel xml file
@return bool success of parsing

Parse a channel . xml file . Expects the name of a channel xml file as input .


function fromAny($info)
    {
        if (is_string($info) && file_exists($info) && strlen($info) < 255) {
            $tmp = substr($info, -4);
            if ($tmp == '.xml') {
                $info = $this->fromXmlFile($info);
            } else {
                $fp = fopen($info, "r");
                $test = fread($fp, 5);
                fclose($fp);
                if ($test == "<?xml") {
                    $info = $this->fromXmlFile($info);
                }
            }
            if (PEAR::isError($info)) {
                require_once 'PEAR.php';
                return PEAR::raiseError($info);
            }
        }
        if (is_string($info)) {
            $info = $this->fromXmlString($info);
        }
        return $info;
    }

function fromAny ( $ info ) { if ( is_string ( $ info ) && file_exists ( $ info ) && strlen ( $ info ) < 255 ) { $ tmp = substr ( $ info , - 4 ) ; if ( $ tmp == '.xml' ) { $ info = $ this -> fromXmlFile ( $ info ) ; } else { $ fp = fopen ( $ info , "r" ) ; $ test = fread ( $ fp , 5 ) ; fclose ( $ fp ) ; if ( $ test == "<?xml" ) { $ info = $ this -> fromXmlFile ( $ info ) ; } } if ( PEAR :: isError ( $ info ) ) { require_once 'PEAR.php' ; return PEAR :: raiseError ( $ info ) ; } } if ( is_string ( $ info ) ) { $ info = $ this -> fromXmlString ( $ info ) ; } return $ info ; }

Parse channel information from different sources

This method is able to extract information about a channel
from an .xml file or a string

@access public
@param  string Filename of the source or the source itself
@return bool


function toXml()
    {
        if (!$this->_isValid && !$this->validate()) {
            $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID);
            return false;
        }
        if (!isset($this->_channelInfo['attribs']['version'])) {
            $this->_channelInfo['attribs']['version'] = '1.0';
        }
        $channelInfo = $this->_channelInfo;
        $ret = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
        $ret .= "<channel version=\"" .
            $channelInfo['attribs']['version'] . "\" xmlns=\"http://pear.php.net/channel-1.0\"
  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
  xsi:schemaLocation=\"http://pear.php.net/dtd/channel-"
            . $channelInfo['attribs']['version'] . " http://pear.php.net/dtd/channel-" .
            $channelInfo['attribs']['version'] . ".xsd\">
 <name>$channelInfo[name]</name>
 <summary>" . htmlspecialchars($channelInfo['summary'])."</summary>
";
        if (isset($channelInfo['suggestedalias'])) {
            $ret .= ' <suggestedalias>' . $channelInfo['suggestedalias'] . "</suggestedalias>\n";
        }
        if (isset($channelInfo['validatepackage'])) {
            $ret .= ' <validatepackage version="' .
                $channelInfo['validatepackage']['attribs']['version']. '">' .
                htmlspecialchars($channelInfo['validatepackage']['_content']) .
                "</validatepackage>\n";
        }
        $ret .= " <servers>\n";
        $ret .= '  <primary';
        if (isset($channelInfo['servers']['primary']['attribs']['ssl'])) {
            $ret .= ' ssl="' . $channelInfo['servers']['primary']['attribs']['ssl'] . '"';
        }
        if (isset($channelInfo['servers']['primary']['attribs']['port'])) {
            $ret .= ' port="' . $channelInfo['servers']['primary']['attribs']['port'] . '"';
        }
        $ret .= ">\n";
        if (isset($channelInfo['servers']['primary']['rest'])) {
            $ret .= $this->_makeRestXml($channelInfo['servers']['primary']['rest'], '   ');
        }
        $ret .= "  </primary>\n";
        if (isset($channelInfo['servers']['mirror'])) {
            $ret .= $this->_makeMirrorsXml($channelInfo);
        }
        $ret .= " </servers>\n";
        $ret .= "</channel>";
        return str_replace("\r", "\n", str_replace("\r\n", "\n", $ret));
    }

Return an XML document based on previous parsing and modifications

@return string XML data

@access public


function _validateError($code, $params = array())
    {
        $this->_stack->push($code, 'error', $params);
        $this->_isValid = false;
    }

function _validateError ( $ code , $ params = array ( ) ) { $ this -> _stack -> push ( $ code , 'error' , $ params ) ; $ this -> _isValid = false ; }

Validation error.  Also marks the object contents as invalid
@param error code
@param array error information
@access private

Validation error . Also marks the object contents as invalid


function getBaseURL($resourceType, $mirror = false)
    {
        if ($mirror == $this->_channelInfo['name']) {
            $mirror = false;
        }

        if ($mirror) {
            $mir = $this->getMirror($mirror);
            if (!$mir) {
                return false;
            }

            $rest = $mir['rest'];
        } else {
            $rest = $this->_channelInfo['servers']['primary']['rest'];
        }

        if (!isset($rest['baseurl'][0])) {
            $rest['baseurl'] = array($rest['baseurl']);
        }

        foreach ($rest['baseurl'] as $baseurl) {
            if (strtolower($baseurl['attribs']['type']) == strtolower($resourceType)) {
                return $baseurl['_content'];
            }
        }

        return false;
    }

function getBaseURL ( $ resourceType , $ mirror = false ) { if ( $ mirror == $ this -> _channelInfo [ 'name' ] ) { $ mirror = false ; } if ( $ mirror ) { $ mir = $ this -> getMirror ( $ mirror ) ; if ( ! $ mir ) { return false ; } $ rest = $ mir [ 'rest' ] ; } else { $ rest = $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ 'rest' ] ; } if ( ! isset ( $ rest [ 'baseurl' ] [ 0 ] ) ) { $ rest [ 'baseurl' ] = array ( $ rest [ 'baseurl' ] ) ; } foreach ( $ rest [ 'baseurl' ] as $ baseurl ) { if ( strtolower ( $ baseurl [ 'attribs' ] [ 'type' ] ) == strtolower ( $ resourceType ) ) { return $ baseurl [ '_content' ] ; } } return false ; }

Get the URL to access a base resource.

Hyperlinks in the returned xml will be used to retrieve the proper information
needed.  This allows extreme extensibility and flexibility in implementation
@param string Resource Type to retrieve


function resetFunctions($type, $mirror = false)
    {
        if ($mirror) {
            if (isset($this->_channelInfo['servers']['mirror'])) {
                $mirrors = $this->_channelInfo['servers']['mirror'];
                if (!isset($mirrors[0])) {
                    $mirrors = array($mirrors);
                }

                foreach ($mirrors as $i => $mir) {
                    if ($mir['attribs']['host'] == $mirror) {
                        if (isset($this->_channelInfo['servers']['mirror'][$i][$type])) {
                            unset($this->_channelInfo['servers']['mirror'][$i][$type]);
                        }

                        return true;
                    }
                }

                return false;
            }

            return false;
        }

        if (isset($this->_channelInfo['servers']['primary'][$type])) {
            unset($this->_channelInfo['servers']['primary'][$type]);
        }

        return true;
    }

function resetFunctions ( $ type , $ mirror = false ) { if ( $ mirror ) { if ( isset ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] ) ) { $ mirrors = $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] ; if ( ! isset ( $ mirrors [ 0 ] ) ) { $ mirrors = array ( $ mirrors ) ; } foreach ( $ mirrors as $ i => $ mir ) { if ( $ mir [ 'attribs' ] [ 'host' ] == $ mirror ) { if ( isset ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] [ $ i ] [ $ type ] ) ) { unset ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] [ $ i ] [ $ type ] ) ; } return true ; } } return false ; } return false ; } if ( isset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] ) ) { unset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] ) ; } return true ; }

Empty all protocol definitions
@param string protocol type
@param string|false mirror name, if any


function setDefaultPEARProtocols($version = '1.0', $mirror = false)
    {
        switch ($version) {
            case '1.0' :
                $this->resetREST($mirror);

                if (!isset($this->_channelInfo['servers'])) {
                    $this->_channelInfo['servers'] = array('primary' =>
                        array('rest' => array()));
                } elseif (!isset($this->_channelInfo['servers']['primary'])) {
                    $this->_channelInfo['servers']['primary'] = array('rest' => array());
                }

                return true;
            break;
            default :
                return false;
            break;
        }
    }

function setDefaultPEARProtocols ( $ version = '1.0' , $ mirror = false ) { switch ( $ version ) { case '1.0' : $ this -> resetREST ( $ mirror ) ; if ( ! isset ( $ this -> _channelInfo [ 'servers' ] ) ) { $ this -> _channelInfo [ 'servers' ] = array ( 'primary' => array ( 'rest' => array ( ) ) ) ; } elseif ( ! isset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] ) ) { $ this -> _channelInfo [ 'servers' ] [ 'primary' ] = array ( 'rest' => array ( ) ) ; } return true ; break ; default : return false ; break ; } }

Set a channel's protocols to the protocols supported by pearweb

Set a channel s protocols to the protocols supported by pearweb


function getMirror($server)
    {
        foreach ($this->getMirrors() as $mirror) {
            if ($mirror['attribs']['host'] == $server) {
                return $mirror;
            }
        }

        return false;
    }

function getMirror ( $ server ) { foreach ( $ this -> getMirrors ( ) as $ mirror ) { if ( $ mirror [ 'attribs' ] [ 'host' ] == $ server ) { return $ mirror ; } } return false ; }

Get the unserialized XML representing a mirror
@return array|false


function setValidationPackage($validateclass, $version)
    {
        if (empty($validateclass)) {
            unset($this->_channelInfo['validatepackage']);
        }
        $this->_channelInfo['validatepackage'] = array('_content' => $validateclass);
        $this->_channelInfo['validatepackage']['attribs'] = array('version' => $version);
    }

function setValidationPackage ( $ validateclass , $ version ) { if ( empty ( $ validateclass ) ) { unset ( $ this -> _channelInfo [ 'validatepackage' ] ) ; } $ this -> _channelInfo [ 'validatepackage' ] = array ( '_content' => $ validateclass ) ; $ this -> _channelInfo [ 'validatepackage' ] [ 'attribs' ] = array ( 'version' => $ version ) ; }

Set the package validation object if it differs from PEAR's default
The class must be includeable via changing _ in the classname to path separator,
but no checking of this is made.
@param string|false pass in false to reset to the default packagename regex
@return boolean success

Set the package validation object if it differs from PEAR s default The class must be includeable via changing _ in the classname to path separator but no checking of this is made .


function addFunction($type, $version, $name = '', $mirror = false)
    {
        if ($mirror) {
            return $this->addMirrorFunction($mirror, $type, $version, $name);
        }

        $set = array('attribs' => array('version' => $version), '_content' => $name);
        if (!isset($this->_channelInfo['servers']['primary'][$type]['function'])) {
            if (!isset($this->_channelInfo['servers'])) {
                $this->_channelInfo['servers'] = array('primary' =>
                    array($type => array()));
            } elseif (!isset($this->_channelInfo['servers']['primary'])) {
                $this->_channelInfo['servers']['primary'] = array($type => array());
            }

            $this->_channelInfo['servers']['primary'][$type]['function'] = $set;
            $this->_isValid = false;
            return true;
        } elseif (!isset($this->_channelInfo['servers']['primary'][$type]['function'][0])) {
            $this->_channelInfo['servers']['primary'][$type]['function'] = array(
                $this->_channelInfo['servers']['primary'][$type]['function']);
        }

        $this->_channelInfo['servers']['primary'][$type]['function'][] = $set;
        return true;
    }

function addFunction ( $ type , $ version , $ name = '' , $ mirror = false ) { if ( $ mirror ) { return $ this -> addMirrorFunction ( $ mirror , $ type , $ version , $ name ) ; } $ set = array ( 'attribs' => array ( 'version' => $ version ) , '_content' => $ name ) ; if ( ! isset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] ) ) { if ( ! isset ( $ this -> _channelInfo [ 'servers' ] ) ) { $ this -> _channelInfo [ 'servers' ] = array ( 'primary' => array ( $ type => array ( ) ) ) ; } elseif ( ! isset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] ) ) { $ this -> _channelInfo [ 'servers' ] [ 'primary' ] = array ( $ type => array ( ) ) ; } $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] = $ set ; $ this -> _isValid = false ; return true ; } elseif ( ! isset ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] [ 0 ] ) ) { $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] = array ( $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] ) ; } $ this -> _channelInfo [ 'servers' ] [ 'primary' ] [ $ type ] [ 'function' ] [ ] = $ set ; return true ; }

Add a protocol to the provides section
@param string protocol type
@param string protocol version
@param string protocol name, if any
@param string mirror name, if this is a mirror's protocol
@return bool


function addMirrorFunction($mirror, $type, $version, $name = '')
    {
        if (!isset($this->_channelInfo['servers']['mirror'])) {
            $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
                array('mirror' => $mirror));
            return false;
        }

        $setmirror = false;
        if (isset($this->_channelInfo['servers']['mirror'][0])) {
            foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
                if ($mirror == $mir['attribs']['host']) {
                    $setmirror = &$this->_channelInfo['servers']['mirror'][$i];
                    break;
                }
            }
        } else {
            if ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
                $setmirror = &$this->_channelInfo['servers']['mirror'];
            }
        }

        if (!$setmirror) {
            $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
                array('mirror' => $mirror));
            return false;
        }

        $set = array('attribs' => array('version' => $version), '_content' => $name);
        if (!isset($setmirror[$type]['function'])) {
            $setmirror[$type]['function'] = $set;
            $this->_isValid = false;
            return true;
        } elseif (!isset($setmirror[$type]['function'][0])) {
            $setmirror[$type]['function'] = array($setmirror[$type]['function']);
        }

        $setmirror[$type]['function'][] = $set;
        $this->_isValid = false;
        return true;
    }

function addMirrorFunction ( $ mirror , $ type , $ version , $ name = '' ) { if ( ! isset ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] ) ) { $ this -> _validateError ( PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND , array ( 'mirror' => $ mirror ) ) ; return false ; } $ setmirror = false ; if ( isset ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] [ 0 ] ) ) { foreach ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] as $ i => $ mir ) { if ( $ mirror == $ mir [ 'attribs' ] [ 'host' ] ) { $ setmirror = & $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] [ $ i ] ; break ; } } } else { if ( $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] [ 'attribs' ] [ 'host' ] == $ mirror ) { $ setmirror = & $ this -> _channelInfo [ 'servers' ] [ 'mirror' ] ; } } if ( ! $ setmirror ) { $ this -> _validateError ( PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND , array ( 'mirror' => $ mirror ) ) ; return false ; } $ set = array ( 'attribs' => array ( 'version' => $ version ) , '_content' => $ name ) ; if ( ! isset ( $ setmirror [ $ type ] [ 'function' ] ) ) { $ setmirror [ $ type ] [ 'function' ] = $ set ; $ this -> _isValid = false ; return true ; } elseif ( ! isset ( $ setmirror [ $ type ] [ 'function' ] [ 0 ] ) ) { $ setmirror [ $ type ] [ 'function' ] = array ( $ setmirror [ $ type ] [ 'function' ] ) ; } $ setmirror [ $ type ] [ 'function' ] [ ] = $ set ; $ this -> _isValid = false ; return true ; }

Add a protocol to a mirror's provides section
@param string mirror name (server)
@param string protocol type
@param string protocol version
@param string protocol name, if any

Add a protocol to a mirror s provides section


function getValidationPackage()
    {
        if (!$this->_isValid && !$this->validate()) {
            return false;
        }

        if (!isset($this->_channelInfo['validatepackage'])) {
            return array('attribs' => array('version' => 'default'),
                '_content' => 'PEAR_Validate');
        }

        return $this->_channelInfo['validatepackage'];
    }

function getValidationPackage ( ) { if ( ! $ this -> _isValid && ! $ this -> validate ( ) ) { return false ; } if ( ! isset ( $ this -> _channelInfo [ 'validatepackage' ] ) ) { return array ( 'attribs' => array ( 'version' => 'default' ) , '_content' => 'PEAR_Validate' ) ; } return $ this -> _channelInfo [ 'validatepackage' ] ; }

Retrieve the name of the validation package for this channel
@return string|false


function &getValidationObject($package = false)
    {
        if (!class_exists('PEAR_Validate')) {
            require_once 'PEAR/Validate.php';
        }

        if (!$this->_isValid) {
            if (!$this->validate()) {
                $a = false;
                return $a;
            }
        }

        if (isset($this->_channelInfo['validatepackage'])) {
            if ($package == $this->_channelInfo['validatepackage']) {
                // channel validation packages are always validated by PEAR_Validate
                $val = &new PEAR_Validate;
                return $val;
            }

            if (!class_exists(str_replace('.', '_',
                  $this->_channelInfo['validatepackage']['_content']))) {
                if ($this->isIncludeable(str_replace('_', '/',
                      $this->_channelInfo['validatepackage']['_content']) . '.php')) {
                    include_once str_replace('_', '/',
                        $this->_channelInfo['validatepackage']['_content']) . '.php';
                    $vclass = str_replace('.', '_',
                        $this->_channelInfo['validatepackage']['_content']);
                    $val = &new $vclass;
                } else {
                    $a = false;
                    return $a;
                }
            } else {
                $vclass = str_replace('.', '_',
                    $this->_channelInfo['validatepackage']['_content']);
                $val = &new $vclass;
            }
        } else {
            $val = &new PEAR_Validate;
        }

        return $val;
    }

Retrieve the object that can be used for custom validation
@param string|false the name of the package to validate.  If the package is
the channel validation package, PEAR_Validate is returned
@return PEAR_Validate|false false is returned if the validation package
cannot be located


public function canGetProperty($name, $checkVars = true)
    {
        $getter = static::_GETTER_PREFIX . $name;
        return method_exists($this, $getter) || $checkVars && property_exists($this, $name);
    }

public function canGetProperty ( $ name , $ checkVars = true ) { $ getter = static :: _GETTER_PREFIX . $ name ; return method_exists ( $ this , $ getter ) || $ checkVars && property_exists ( $ this , $ name ) ; }

Returns a value indicating whether a property can be read.

A property is readable if:

- the class has a getter method associated with the specified name
(in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when `$checkVars` is true);

@param string $name the property name
@param bool $checkVars whether to treat member variables as properties
@return bool whether the property can be read
@see canSetProperty()

Returns a value indicating whether a property can be read .


public function canSetProperty($name, $checkVars = true)
    {
        $setter = static::_GETTER_PREFIX . $name;
        return method_exists($this, $setter) || $checkVars && property_exists($this, $name);
    }

public function canSetProperty ( $ name , $ checkVars = true ) { $ setter = static :: _GETTER_PREFIX . $ name ; return method_exists ( $ this , $ setter ) || $ checkVars && property_exists ( $ this , $ name ) ; }

Returns a value indicating whether a property can be set.

A property is writable if:

- the class has a setter method associated with the specified name
(in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when `$checkVars` is true);

@param string $name the property name
@param bool $checkVars whether to treat member variables as properties
@return bool whether the property can be written
@see canGetProperty()

Returns a value indicating whether a property can be set .


public function getCacheFile(callable $encoder = null): string
    {
        if (\is_null($encoder)) {
            $encoder = function ($value): string {
                return var_export($value, true);
            };
        }

        $this->loadCacheParameters();
        ksort($this->entries);
        $encoded = $encoder($this->entries);

        return <<<TEMPLATE
<?php return new class extends \Simply\Container\Container {
    protected \$entries = $encoded;
};
TEMPLATE;
    }

Returns PHP code for a cached container that can be loaded quickly on runtime.
@param callable $encoder Encoder to turn the cached entry data into PHP code or null for default
@return string The PHP code for the cached container
@throws ContainerException If the container contains entries that cannot be cached

Returns PHP code for a cached container that can be loaded quickly on runtime .


private function loadCacheParameters(): void
    {
        foreach ($this->entryCache as $id => $entry) {
            $parameters = $entry->getCacheParameters();

            if (!$this->isConstantValue($parameters)) {
                throw new ContainerException("Unable to cache entry '$id', the cache parameters are not static");
            }

            $this->entries[$id] = [\get_class($entry), $parameters];
        }
    }

Loads the cache parameters for all entries.
@throws ContainerException If the container contains entries that cannot be cached

Loads the cache parameters for all entries .


public function addEntry(string $id, EntryInterface $type): void
    {
        if (isset($this[$id])) {
            throw new ContainerException("Entry for identifier '$id' already exists");
        }

        $this->entryCache[$id] = $type;
    }

Adds an entry to the container.
@param string $id The identifier for the container entry
@param EntryInterface $type The container entry to add
@throws ContainerException If trying to add an entry to an identifier that already exists


public function get($id)
    {
        if (array_key_exists($id, $this->valueCache)) {
            return $this->valueCache[$id];
        }

        $entry = $this->getEntry($id);
        $value = $entry->getValue($this->delegate);

        if ($entry->isFactory()) {
            $this->entryCache[$id] = $entry;
        } else {
            $this->valueCache[$id] = $value;
        }

        return $value;
    }

public function get ( $ id ) { if ( array_key_exists ( $ id , $ this -> valueCache ) ) { return $ this -> valueCache [ $ id ] ; } $ entry = $ this -> getEntry ( $ id ) ; $ value = $ entry -> getValue ( $ this -> delegate ) ; if ( $ entry -> isFactory ( ) ) { $ this -> entryCache [ $ id ] = $ entry ; } else { $ this -> valueCache [ $ id ] = $ value ; } return $ value ; }

Returns value for the container entry with the given identifier.
@param string $id The entry identifier to look for
@return mixed The value for the entry
@throws NotFoundExceptionInterface If the entry cannot be found
@throws ContainerExceptionInterface If there are errors trying to load dependencies

Returns value for the container entry with the given identifier .


private function getEntry(string $id): EntryInterface
    {
        if (isset($this->entryCache[$id])) {
            return $this->entryCache[$id];
        }

        if (!isset($this->entries[$id])) {
            throw new NotFoundException("No entry was found for the identifier '$id'");
        }

        /** @var EntryInterface $class */
        [$class, $parameters] = $this->entries[$id];
        return $class::createFromCacheParameters($parameters);
    }

Returns container entry for the given identifier.
@param string $id The entry identifier to look for
@return EntryInterface The container entry for the given identifier
@throws NotFoundExceptionInterface If the entry cannot be found
@throws ContainerException If the cached type is not a valid entry type

Returns container entry for the given identifier .


public function has($id): bool
    {
        return isset($this->entries[$id]) || isset($this->entryCache[$id]);
    }

public function has ( $ id ) : bool { return isset ( $ this -> entries [ $ id ] ) || isset ( $ this -> entryCache [ $ id ] ) ; }

Tells if the entry with the given identifier exists in the container.
@param string $id The entry identifier to look for
@return bool True if an entry with the given identifier exists, false otherwise

Tells if the entry with the given identifier exists in the container .


public function offsetUnset($offset): void
    {
        unset(
            $this->entries[$offset],
            $this->entryCache[$offset],
            $this->valueCache[$offset]
        );
    }

public function offsetUnset ( $ offset ) : void { unset ( $ this -> entries [ $ offset ] , $ this -> entryCache [ $ offset ] , $ this -> valueCache [ $ offset ] ) ; }

Removes an entry from the container.
@param string $offset The identifier of the container entry to remove


protected function applySiteConditions()
    {
        if ($this->siteId !== null) {
            $this->andWhere(Db::parseParam('siteId', $this->siteId));
        } else {
            $this->andWhere(Db::parseParam('siteId', Craft::$app->getSites()->currentSite->id));
        }
    }

protected function applySiteConditions ( ) { if ( $ this -> siteId !== null ) { $ this -> andWhere ( Db :: parseParam ( 'siteId' , $ this -> siteId ) ) ; } else { $ this -> andWhere ( Db :: parseParam ( 'siteId' , Craft :: $ app -> getSites ( ) -> currentSite -> id ) ) ; } }


function assign(array $keys, $value)
    {
        foreach ($keys as $key) {
            $arr = &$this->array[$key];
        }

        $arr = $value;

        return $this->array;
    }

function assign ( array $ keys , $ value ) { foreach ( $ keys as $ key ) { $ arr = & $ this -> array [ $ key ] ; } $ arr = $ value ; return $ this -> array ; }

Creates an multidimensional array out of an array with keynames

@param array $keys
The array holding the keys to use as values
@param mixed $value
The value to assign to the last key


function _extractErrors($err = null)
    {
        static $errors = array();
        if ($err === null) {
            $e = $errors;
            $errors = array();
            return $e;
        }
        $errors[] = $err->getMessage();
    }

function _extractErrors ( $ err = null ) { static $ errors = array ( ) ; if ( $ err === null ) { $ e = $ errors ; $ errors = array ( ) ; return $ e ; } $ errors [ ] = $ err -> getMessage ( ) ; }

helper callback for extracting Archive_Tar errors

@param PEAR_Error|null $err
@return array
@access private


public function getModelsConfigFile()
    {
        $o = $this->params;
        $file = $o['path'] . DIRECTORY_SEPARATOR . 'normalist_zeroconf_cache_' . $o['alias'] . '_' . $o['version'] . '.php';
        return $file;
    }

public function getModelsConfigFile ( ) { $ o = $ this -> params ; $ file = $ o [ 'path' ] . DIRECTORY_SEPARATOR . 'normalist_zeroconf_cache_' . $ o [ 'alias' ] . '_' . $ o [ 'version' ] . '.php' ; return $ file ; }

Return models configuration file
@return string


public function getModelsDefinition()
    {
        $file = $this->getModelsConfigFile();
        if (!file_exists($file) || !is_readable($file)) {
            throw new Exception\ModelFileNotFoundException(__METHOD__ . " Model configuration file '$file' does not exists or not readable");
        }

        if (defined('HHVM_VERSION')) {
            // As an 'evil' workaround, waiting for hhvm to comply
            // see https://github.com/facebook/hhvm/issues/1447
            $definition = false;
            $file_content = file_get_contents($file);
            $file_content = trim(str_replace('<?php', '', $file_content));
            $file_content = trim(str_replace('return array(', '$definition = array(', $file_content));
            eval($file_content);
        } else {
            $definition = include $file;
        }

        if (!$definition) {
            throw new Exception\ModelFileCorruptedException(__METHOD__ . " Model configuration file '$file' cannot be included");
        }
        if (!is_array($definition)) {
            throw new Exception\ModelFileCorruptedException(__METHOD__ . " Model configuration file '$file' was included but is not a valid array");
        }

        return $definition;
    }

Get models definition according to options

@throws Exception\ModelFileNotFoundException
@throws Exception\ModelFileCorruptedException
@return array


protected function saveModelsDefinition(array $models_definition)
    {
        $file = $this->getModelsConfigFile();
        if (file_exists($file) && !is_writable($file)) {
            throw new Exception\ModelFileNotWritableException(__METHOD__ . "Model configuration file '$file' cannot be overwritten, not writable.");
        }

        //$config = new Config($models_defintion, true);
        $writer = new Writer\PhpArray();
        $models_definition['normalist'] = ['model_version' => Metadata\NormalistModels::VERSION];
        $writer->toFile($file, $models_definition, $exclusiveLock = true);
        $perms = $this->params['permissions'];
        if ($perms != '') {
            if (decoct(octdec($perms)) == $perms) {
                $perms = octdec($perms);
            }
            chmod($file, $perms);
        }
        return $this;
    }

Save model definition

@throws Exception\ModelFileNotWritableException
@param array $models_definition
@return DriverInterface


public function getMetadata()
    {
        $cache_key = md5(serialize($this->params));
        if (!array_key_exists($cache_key, self::$metadataCache)) {
            if ($this->metadata === null) {
                self::$metadataCache[$cache_key] = $this->getDefaultMetadata();
            } else {
                self::$metadataCache[$cache_key] = $this->metadata;
            }
        }
        return self::$metadataCache[$cache_key];
    }

public function getMetadata ( ) { $ cache_key = md5 ( serialize ( $ this -> params ) ) ; if ( ! array_key_exists ( $ cache_key , self :: $ metadataCache ) ) { if ( $ this -> metadata === null ) { self :: $ metadataCache [ $ cache_key ] = $ this -> getDefaultMetadata ( ) ; } else { self :: $ metadataCache [ $ cache_key ] = $ this -> metadata ; } } return self :: $ metadataCache [ $ cache_key ] ; }

Get internal metadata reader

@return Source\AbstractSchemaSource


public function setName($name)
    {
        $name = (string) $name;

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

        $this->name = $name;

        return $this;
    }

public function setName ( $ name ) { $ name = ( string ) $ name ; if ( $ this -> exists ( ) && $ this -> name !== $ name ) { $ this -> updated [ 'name' ] = true ; } $ this -> name = $ name ; return $ this ; }

Set value for field "bank_name"

@param  string $name
@return $this


public function setColor($color)
    {
        $color = (string) $color;

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

        $this->color = $color;

        return $this;
    }

public function setColor ( $ color ) { $ color = ( string ) $ color ; if ( $ this -> exists ( ) && $ this -> color !== $ color ) { $ this -> updated [ 'color' ] = true ; } $ this -> color = $ color ; return $ this ; }

Set value for field "bank_color"

@param  string $color
@return $this


public function setParser($parser)
    {
        $parser = (string) $parser;

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

        $this->parser = $parser;

        return $this;
    }

public function setParser ( $ parser ) { $ parser = ( string ) $ parser ; if ( $ this -> exists ( ) && $ this -> parser !== $ parser ) { $ this -> updated [ 'parser' ] = true ; } $ this -> parser = $ parser ; return $ this ; }

Set value for field "bank_parser"

@param  string $parser
@return $this


public function aggregate($collection)
    {
        // Ensure the collection is materialized.
        $collection = $this->mirror->materializeCollection($collection);

        // Create aggregate collection to accumulate style sheets.
        $aggregate = new StyleAggregate();
        foreach ($collection as $resource) {
            if ($resource instanceof MaterializedResource) {
                $internalResource = $resource->getResource();
                $mediaType = 'all';
                if ($internalResource instanceof CssResource) {
                    $mediaType = $internalResource->getMediaType();
                }
                $aggregate->addStyle($resource, $mediaType);
            }
        }

        // Create resource with the aggregate style sheet.
        $data = $aggregate->getAggregateStyle();
        $hash = sha1($data);
        $file = $this->prefix.$hash.'.css';
        $resource = new LocalResource($file, $data);
        return $resource;
    }

Aggregates a collection of CSS resources.

@param Collection $collection
@return LocalResource

Aggregates a collection of CSS resources .


public static function curl($url)
    {
        $req = curl_init();

        $opt = [
            CURLOPT_AUTOREFERER    => true,
            CURLOPT_COOKIEJAR      => tempnam(sys_get_temp_dir(), 'curl'),
            CURLOPT_FAILONERROR    => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HEADER         => true,
            CURLOPT_HTTPHEADER     => ['DNT: 1', 'Accept-Language: en-us,en;q=0.5'],
            CURLOPT_MAXREDIRS      => 5,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_URL            => $url,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0',
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT        => 10,
        ];

        curl_setopt_array($req, $opt);

        if (! $res = curl_exec($req)) return false;

        curl_close($req);

        // mb_convert_encoding is used to avoid encoding issues related to DOMDocument::loadHTML
        // see https://secure.php.net/manual/en/domdocument.loadhtml.php#52251
        return mb_convert_encoding($res, 'HTML-ENTITIES', 'UTF-8');
    }

Download and return a resource.

@param string $url URL of the target page

@return string|bool false on error


public static function imageProxy($url, $filename, $directory, $overwrite = null)
    {
        $allowedmimetype = [ 'image/gif', 'image/jpeg', 'image/png', 'image/x-icon' ];

        $localpath = $directory . '/noapi_' . $filename;

        if (! $overwrite && file_exists($localpath)) return $localpath;

        $image = file_get_contents($url);
        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mimetype = $finfo->buffer($image);

        if (! in_array($mimetype, $allowedmimetype)) return false;

        if (file_put_contents($localpath, $image) === false) return false;

        return $localpath;
    }

public static function imageProxy ( $ url , $ filename , $ directory , $ overwrite = null ) { $ allowedmimetype = [ 'image/gif' , 'image/jpeg' , 'image/png' , 'image/x-icon' ] ; $ localpath = $ directory . '/noapi_' . $ filename ; if ( ! $ overwrite && file_exists ( $ localpath ) ) return $ localpath ; $ image = file_get_contents ( $ url ) ; $ finfo = new \ finfo ( FILEINFO_MIME_TYPE ) ; $ mimetype = $ finfo -> buffer ( $ image ) ; if ( ! in_array ( $ mimetype , $ allowedmimetype ) ) return false ; if ( file_put_contents ( $ localpath , $ image ) === false ) return false ; return $ localpath ; }

Create local copy of remote images.

Hotlinking third party content raises privacy and security concerns. This
method allows for easy copying of remote images.

Copying remote content raises other kind of security concerns, we
mitigate the risks by : checking the mime type against a predefined set ;
ignoring the original file name, extension and metadata ; enforcing part
of the path (prepending "noapi_" to the file name).

@param string $url       URL of the remote image
@param string $filename  name of the target image
@param string $directory target directory without a ending slash
@param bool   $overwrite true to overwrite existing image

@return string|bool false on error


public static function createValidator($type, $model, $attributes, $params = [])
    {
        $params['attributes'] = $attributes;

        if ($type instanceof \Closure || ($model->hasMethod($type) && !isset(static::$builtInValidators[$type]))) {
            // method-based validator
            $params['class'] = __NAMESPACE__ . '\InlineValidator';
            $params['method'] = $type;
        } else {
            if (isset(static::$builtInValidators[$type])) {
                $type = static::$builtInValidators[$type];
            }
            if (is_array($type)) {
                $params = array_merge($type, $params);
            } else {
                $params['class'] = $type;
            }
        }

        return Reaction::create($params);
    }

public
static
function
createValidator
(
$
type
,
$
model
,
$
attributes
,
$
params
=
[
]
)
{
$
params
[
'attributes'
]
=
$
attributes
;
if
(
$
type
instanceof
\
Closure
||
(
$
model
->
hasMethod
(
$
type
)
&&
!
isset
(
static
::
$
builtInValidators
[
$
type
]
)
)
)
{
// method-based validator
$
params
[
'class'
]
=
__NAMESPACE__
.
'\InlineValidator'
;
$
params
[
'method'
]
=
$
type
;
}
else
{
if
(
isset
(
static
::
$
builtInValidators
[
$
type
]
)
)
{
$
type
=
static
::
$
builtInValidators
[
$
type
]
;
}
if
(
is_array
(
$
type
)
)
{
$
params
=
array_merge
(
$
type
,
$
params
)
;
}
else
{
$
params
[
'class'
]
=
$
type
;
}
}
return
Reaction
::
create
(
$
params
)
;
}

Creates a validator object.
@param string|\Closure $type the validator type. This can be either:
* a built-in validator name listed in [[builtInValidators]];
* a method name of the model class;
* an anonymous function;
* a validator class name.
@param \Reaction\Base\Model $model the data model to be validated.
@param array|string $attributes list of attributes to be validated. This can be either an array of
the attribute names or a string of comma-separated attribute names.
@param array $params initial values to be applied to the validator properties.
@return Validator the validator


public function validateAttribute($model, $attribute)
    {
        $result = $this->validateValue($model->$attribute);
        if ($result instanceof ExtendedPromiseInterface) {
            return $result->then(function($_result) use ($model, $attribute) {
                if (!empty($_result)) {
                    $this->addError($model, $attribute, $_result[0], $_result[1]);
                }
            });
        }
        if (!empty($result)) {
            $this->addError($model, $attribute, $result[0], $result[1]);
        }
        return null;
    }

public function validateAttribute ( $ model , $ attribute ) { $ result = $ this -> validateValue ( $ model -> $ attribute ) ; if ( $ result instanceof ExtendedPromiseInterface ) { return $ result -> then ( function ( $ _result ) use ( $ model , $ attribute ) { if ( ! empty ( $ _result ) ) { $ this -> addError ( $ model , $ attribute , $ _result [ 0 ] , $ _result [ 1 ] ) ; } } ) ; } if ( ! empty ( $ result ) ) { $ this -> addError ( $ model , $ attribute , $ result [ 0 ] , $ result [ 1 ] ) ; } return null ; }

Validates a single attribute.
Child classes must implement this method to provide the actual validation logic.
@param \Reaction\Base\Model $model the data model to be validated
@param string               $attribute the name of the attribute to be validated.
@return ExtendedPromiseInterface|null Some validators may return a promise if DB or other async components used

Validates a single attribute . Child classes must implement this method to provide the actual validation logic .


public function validate($value, &$error = null)
    {
        $result = $this->validateValue($value);
        if (empty($result)) {
            return true;
        }

        list($message, $params) = $result;
        $params['attribute'] = Reaction::t('rct', 'the input value');
        if (is_array($value)) {
            $params['value'] = 'array()';
        } elseif (is_object($value)) {
            $params['value'] = 'object';
        } else {
            $params['value'] = $value;
        }
        $error = $this->formatMessage($message, $params);

        return false;
    }

public
function
validate
(
$
value
,
&
$
error
=
)
{
$
result
=
$
this
->
validateValue
(
$
value
)
;
if
(
empty
(
$
result
)
)
{
return
true
;
}
list
(
$
message
,
$
params
)
=
$
result
;
$
params
[
'attribute'
]
=
Reaction
::
t
(
'rct'
,
'the input value'
)
;
if
(
is_array
(
$
value
)
)
{
$
params
[
'value'
]
=
'array()'
;
}
elseif
(
is_object
(
$
value
)
)
{
$
params
[
'value'
]
=
'object'
;
}
else
{
$
params
[
'value'
]
=
$
value
;
}
$
error
=
$
this
->
formatMessage
(
$
message
,
$
params
)
;
return
false
;
}

Validates a given value.
You may use this method to validate a value out of the context of a data model.
@param mixed $value the data value to be validated.
@param string $error the error message to be returned, if the validation fails.
@return bool whether the data is valid.

Validates a given value . You may use this method to validate a value out of the context of a data model .


public function run($namespace)
    {
        $this->namespace = $namespace;
        $this->_initRegister();

        date_default_timezone_set($this->config['timezone']);

        if (false === IS_CLI) {
            $this->route = Route::instance()->init();
            $this->controller = Controller::create($this->route);
        }
    }

public function run ( $ namespace ) { $ this -> namespace = $ namespace ; $ this -> _initRegister ( ) ; date_default_timezone_set ( $ this -> config [ 'timezone' ] ) ; if ( false === IS_CLI ) { $ this -> route = Route :: instance ( ) -> init ( ) ; $ this -> controller = Controller :: create ( $ this -> route ) ; } }


public static function shutdown()
    {
        $error = error_get_last();

        if ($error !== null) {
            if (App::app()->config['debug'] == false) {
                Log::log()->fatal('Fatal Error:  ' .$error['message'] . ' in '. $error['file']. ' on '.$error['line']);
            }
        }
    }

public
static
function
shutdown
(
)
{
$
error
=
error_get_last
(
)
;
if
(
$
error
!==
)
{
if
(
App
::
app
(
)
->
config
[
'debug'
]
==
false
)
{
Log
::
log
(
)
->
fatal
(
'Fatal Error:  '
.
$
error
[
'message'
]
.
' in '
.
$
error
[
'file'
]
.
' on '
.
$
error
[
'line'
]
)
;
}
}
}


public function url($controller, $action, $param)
    {
        $path = url();
        if (empty($param)) {
            // return PATH_APP_REL.'/'.$controller.'/'.$action;
            return $path . '/' . $controller.'/'.$action;
        } else {
            // return PATH_APP_REL.'/'.$controller.'/'.$action.'?'.http_build_query($param);
            return $path . '/' . $controller.'/'.$action.'?'.http_build_query($param);
        }
    }

build url with controller action and url param

@param $controller string the controller name
@param $action string the action name
@param $param array the url param

@return string the url


public function canonical()
    {
        $routePath = $this->getCurrentPath(true);
        if ($routePath === null) {
            return null;
        }
        $params = $this->app->getRoute()->getRouteParams();
        $params[0] = $routePath;

        return $this->getUrlManager()->createAbsoluteUrl($params);
    }

public function canonical ( ) { $ routePath = $ this -> getCurrentPath ( true ) ; if ( $ routePath === null ) { return null ; } $ params = $ this -> app -> getRoute ( ) -> getRouteParams ( ) ; $ params [ 0 ] = $ routePath ; return $ this -> getUrlManager ( ) -> createAbsoluteUrl ( $ params ) ; }

Returns the canonical URL of the currently requested page.

The canonical URL is constructed using the current controller's [[\yii\web\Controller::route]] and
[[\yii\web\Controller::actionParams]]. You may use the following code in the layout view to add a link tag
about canonical URL:

```php
$this->registerLinkTag(['rel' => 'canonical', 'href' => Url::canonical()]);
```

@return string the canonical URL of the currently requested page
@see \Reaction\Helpers\Url::canonical()

Returns the canonical URL of the currently requested page .


protected function normalizeRoutePath($routePath)
    {
        $routePath = Reaction::$app->getAlias((string) $routePath);
        if (strncmp($routePath, '/', 1) === 0) {
            // absolute route
            return $routePath;
        }

        $route = $this->app->getRoute();

        // relative route
        if ($route === null || $route->controller === null) {
            throw new InvalidArgumentException("Unable to resolve the relative route: $routePath. No active controller is available.");
        }

        return $routePath === '' ? $route->getRoutePath(true) : $route->controller->group() . '/' . $routePath;
    }

Normalizes route and makes it suitable for UrlManager. Absolute routes are staying as is
while relative routes are converted to absolute ones.

A relative route is a route without a leading slash, such as "view", "post/view".

- If the route is an empty string, the current [[\yii\web\Controller::route|route]] will be used;
- If the route contains no slashes at all, it is considered to be an action ID
of the current controller and will be prepended with [[\yii\web\Controller::uniqueId]];
- If the route has no leading slash, it is considered to be a route relative
to the current module and will be prepended with the module's uniqueId.

A route can also be specified as an alias. In this case, the alias
will be converted into the actual route first before conducting the above transformation steps.

@param string              $routePath the route. This can be either an absolute route or a relative route.
@return string normalized  route suitable for UrlManager

Normalizes route and makes it suitable for UrlManager . Absolute routes are staying as is while relative routes are converted to absolute ones .


public function isWorking()
    {
        if (null != $this->exception) {
            return false;
        }

        foreach ($this->getTests() as $test) {
            if ($test->hasFailed()) {
                $this->exception = new \Exception('Tests failed');
                return false;
            }
        }

        return true;
    }

public
function
isWorking
(
)
{
if
(
!=
$
this
->
exception
)
{
return
false
;
}
foreach
(
$
this
->
getTests
(
)
as
$
test
)
{
if
(
$
test
->
hasFailed
(
)
)
{
$
this
->
exception
=
new
\
Exception
(
'Tests failed'
)
;
return
false
;
}
}
return
true
;
}

Application is working if all tests are OK & no down exception is set

@return boolean


public function getViewNames($schema = '', $refresh = false)
    {
        if (!isset($this->_viewNames[$schema]) || $refresh) {
            return $this->findViewNames($schema)->then(
                function($names) use($schema) {
                    $this->_viewNames[$schema] = $names;
                    return $names;
                }
            );
        }

        return resolve($this->_viewNames[$schema]);
    }

public function getViewNames ( $ schema = '' , $ refresh = false ) { if ( ! isset ( $ this -> _viewNames [ $ schema ] ) || $ refresh ) { return $ this -> findViewNames ( $ schema ) -> then ( function ( $ names ) use ( $ schema ) { $ this -> _viewNames [ $ schema ] = $ names ; return $ names ; } ) ; } return resolve ( $ this -> _viewNames [ $ schema ] ) ; }

Returns all view names in the database.
@param string $schema the schema of the views. Defaults to empty string, meaning the current or default schema name.
If not empty, the returned view names will be prefixed with the schema name.
@param bool $refresh whether to fetch the latest available view names. If this is false,
view names fetched previously (if available) will be returned.
@return ExtendedPromiseInterface with string[] all view names in the database.

Returns all view names in the database .


public function get(string $key, $default = null)
    {
        $value = static::$handler->get($this->normalized($key));
        // If we could not find the cache value, we will get
        // the default value for this cache value. This default could be a callback
        // so we will execute the value function which will resolve it if needed.
        if (is_null($value)) {
            $value = is_callable($default) ? $default() : $default;
        }

        if (static::hasMacro()) {
            $value = $this->runMacro('getAfter', [$value, $key, false]);
        }

        return $value;
    }

Retrieve an item from the cache by key.

@param string $key     键
@param mixed  $default 默认值

@return mixed

Retrieve an item from the cache by key .


public function set(string $key, $value, int $ttl = null)
    {
        $keyNormalized = $this->normalized($key);

        $result = static::$handler->set($keyNormalized, $value, $ttl ?? $this->ttl);

        if ($result) {
            if ($this->assistant) {
                $this->assistant->add($keyNormalized);
                $this->assistant->save();
            }
        }

        return $result;
    }

public function set ( string $ key , $ value , int $ ttl = null ) { $ keyNormalized = $ this -> normalized ( $ key ) ; $ result = static :: $ handler -> set ( $ keyNormalized , $ value , $ ttl ?? $ this -> ttl ) ; if ( $ result ) { if ( $ this -> assistant ) { $ this -> assistant -> add ( $ keyNormalized ) ; $ this -> assistant -> save ( ) ; } } return $ result ; }

Store an item in the cache.

@param string                               $key   键
@param mixed                                $value 值
@param \DateTimeInterface|\DateInterval|int $ttl   生命值，秒

@return bool


public function setMultiple(array $values, int $ttl = null)
    {
        $valuesNormalized = [];

        foreach ($values as $key => $value) {
            $valuesNormalized[$this->normalized($key)] = $value;
        }

        $result = static::$handler->setMultiple(
            $valuesNormalized,
            $ttl ?? $this->ttl
        );

        if ($result) {
            if ($this->assistant) {
                foreach (array_keys($valuesNormalized) as $key) {
                    $this->assistant->add($key);
                }
                $this->assistant->save();
            }
        }

        return $result;
    }

public function setMultiple ( array $ values , int $ ttl = null ) { $ valuesNormalized = [ ] ; foreach ( $ values as $ key => $ value ) { $ valuesNormalized [ $ this -> normalized ( $ key ) ] = $ value ; } $ result = static :: $ handler -> setMultiple ( $ valuesNormalized , $ ttl ?? $ this -> ttl ) ; if ( $ result ) { if ( $ this -> assistant ) { foreach ( array_keys ( $ valuesNormalized ) as $ key ) { $ this -> assistant -> add ( $ key ) ; } $ this -> assistant -> save ( ) ; } } return $ result ; }

Store multiple items in the cache for a given number of minutes.

@param array                                $values key、value表
@param \DateTimeInterface|\DateInterval|int $ttl    生命值，秒

Store multiple items in the cache for a given number of minutes .


public function pull(string $key, $default = null)
    {
        $result = $this->get($key, $default);

        $this->delete($key);

        return $result;
    }

public function pull ( string $ key , $ default = null ) { $ result = $ this -> get ( $ key , $ default ) ; $ this -> delete ( $ key ) ; return $ result ; }

Retrieve an item from the cache and delete it.

@param string $key     键
@param mixed  $default 默认值

@return mixed|null

Retrieve an item from the cache and delete it .


public function add(string $key, $value, int $ttl = null)
    {
        // If the store has an "add" method we will call the method on the store so it
        // has a chance to override this logic. Some drivers better support the way
        // this operation should work with a total "atomic" implementation of it.
        if (method_exists(static::$handler, 'add')) {
            return static::$handler->add(
                $this->normalized($key),
                $value,
                $ttl ?? $this->ttl
            );
        }

        // If the value did not exist in the cache, we will put the value in the cache
        // so it exists for subsequent requests. Then, we will return true so it is
        // easy to know if the value gets added. Otherwise, we will return false.
        if (is_null($this->get($key))) {
            return $this->set($key, $value, $ttl ?? $this->ttl);
        }

        return false;
    }

Store an item in the cache if the key does not exist.

@param string                               $key   键
@param mixed                                $value 值
@param \DateTimeInterface|\DateInterval|int $ttl   生命值，秒

@return bool

Store an item in the cache if the key does not exist .


public function remember(string $key, \Closure $callback, $ttl = null)
    {
        $value = $this->get($key);
        // If the item exists in the cache we will just return this immediately and if
        // not we will execute the given Closure and cache the result of that for a
        // given number of seconds so it's available for all subsequent requests.
        if (!is_null($value)) {
            return $value;
        }

        $this->set($key, $value = $callback(), $ttl ?? $this->ttl);

        return $value;
    }

Get an item from the cache, or store the default value.

@param string                               $key      键
@param \Closure                             $callback 获取不到时的取值
@param \DateTimeInterface|\DateInterval|int $ttl      生命值

@return mixed

Get an item from the cache or store the default value .


public function delete(string $key)
    {
        $keyNormalized = $this->normalized($key);

        $result = static::$handler->delete($keyNormalized);

        if ($result) {
            if ($this->assistant) {
                $this->assistant->remove($keyNormalized);
                $this->assistant->save();
            }
        }

        return $result;
    }

public function delete ( string $ key ) { $ keyNormalized = $ this -> normalized ( $ key ) ; $ result = static :: $ handler -> delete ( $ keyNormalized ) ; if ( $ result ) { if ( $ this -> assistant ) { $ this -> assistant -> remove ( $ keyNormalized ) ; $ this -> assistant -> save ( ) ; } } return $ result ; }

Remove an item from the cache.

@param string $key 缓存键

@return bool


public function filter($str)
    {
        $str = preg_replace("|[\D+]|", "", $str);

        if (strlen($str) == 11 && in_array(substr($str, 0, 1), array("7", "8"))) {
            $str = substr($str, 1);
        }

        $len2 = strlen($str);

        return $len2 == 10 ? $str : "";
    }

public function filter ( $ str ) { $ str = preg_replace ( "|[\D+]|" , "" , $ str ) ; if ( strlen ( $ str ) == 11 && in_array ( substr ( $ str , 0 , 1 ) , array ( "7" , "8" ) ) ) { $ str = substr ( $ str , 1 ) ; } $ len2 = strlen ( $ str ) ; return $ len2 == 10 ? $ str : "" ; }

Returns only digits from source string. If string is
11 chars length and first char is 7 then that char is stripped
@param  string $str Source string
@return string Filtered string

Returns only digits from source string . If string is 11 chars length and first char is 7 then that char is stripped


protected function configDefaultOptions(Command $command)
    {
        $defaultConfPath = getcwd() . '/' . $this->confDir;
        $command->addArgument('working-directory', InputOption::VALUE_REQUIRED, 'Working directory', getcwd());
        $command
            ->addOption('app-type', null, InputOption::VALUE_REQUIRED, 'Application type', StaticApplicationInterface::APP_TYPE_WEB)
            ->addOption('app-host', null, InputOption::VALUE_REQUIRED, 'Host to run', '127.0.0.1')
            ->addOption('app-port', null, InputOption::VALUE_REQUIRED, 'Port to run', 4000)
            ->addOption('app-debug', null, InputOption::VALUE_REQUIRED, 'Enable debug', true)
            ->addOption('app-config', null, InputOption::VALUE_REQUIRED, 'Configs dir path', $defaultConfPath);
    }

protected
function
configDefaultOptions
(
Command
$
command
)
{
$
defaultConfPath
=
getcwd
(
)
.
'/'
.
$
this
->
confDir
;
$
command
->
addArgument
(
'working-directory'
,
InputOption
::
VALUE_REQUIRED
,
'Working directory'
,
getcwd
(
)
)
;
$
command
->
addOption
(
'app-type'
,
,
InputOption
::
VALUE_REQUIRED
,
'Application type'
,
StaticApplicationInterface
::
APP_TYPE_WEB
)
->
addOption
(
'app-host'
,
,
InputOption
::
VALUE_REQUIRED
,
'Host to run'
,
'127.0.0.1'
)
->
addOption
(
'app-port'
,
,
InputOption
::
VALUE_REQUIRED
,
'Port to run'
,
4000
)
->
addOption
(
'app-debug'
,
,
InputOption
::
VALUE_REQUIRED
,
'Enable debug'
,
true
)
->
addOption
(
'app-config'
,
,
InputOption
::
VALUE_REQUIRED
,
'Configs dir path'
,
$
defaultConfPath
)
;
}

Config application's wide options
@param Command $command


protected function optionOrConfigValue(InputInterface $input, $config, $optionName, $configName = null)
    {
        $optionNameRaw = $this->normalizeConfigArrayPath($optionName);
        if ($input->hasParameterOption('--' . $optionNameRaw)) {
            return $this->getOptionWithTypeCast($input, $optionName);
        }
        if (!isset($configName)) {
            $configName = $optionNameRaw;
        }

        $configValue = ArrayHelper::getValue($config, $configName, null);

        return isset($configValue) ? $configValue : $input->getOption($optionName);
    }

protected function optionOrConfigValue ( InputInterface $ input , $ config , $ optionName , $ configName = null ) { $ optionNameRaw = $ this -> normalizeConfigArrayPath ( $ optionName ) ; if ( $ input -> hasParameterOption ( '--' . $ optionNameRaw ) ) { return $ this -> getOptionWithTypeCast ( $ input , $ optionName ) ; } if ( ! isset ( $ configName ) ) { $ configName = $ optionNameRaw ; } $ configValue = ArrayHelper :: getValue ( $ config , $ configName , null ) ; return isset ( $ configValue ) ? $ configValue : $ input -> getOption ( $ optionName ) ; }

Get option from input or config array
@param InputInterface $input
@param array          $config
@param string         $optionName
@param string         $configName
@return mixed


protected function getOptionWithTypeCast(InputInterface $input, $optionName)
    {
        $optionNameExp = explode(':', $optionName);
        if (count($optionNameExp) > 1) {
            $optionName = $optionNameExp[0];
            $optionType = $optionNameExp[1];
        }
        $optionValue = $input->getOption($optionName);
        if (isset($optionType) && function_exists($optionType . 'val')) {
            $typeCastFunc = $optionType . 'val';
            $optionValue = $typeCastFunc($optionValue);
        }
        return $optionValue;
    }

protected function getOptionWithTypeCast ( InputInterface $ input , $ optionName ) { $ optionNameExp = explode ( ':' , $ optionName ) ; if ( count ( $ optionNameExp ) > 1 ) { $ optionName = $ optionNameExp [ 0 ] ; $ optionType = $ optionNameExp [ 1 ] ; } $ optionValue = $ input -> getOption ( $ optionName ) ; if ( isset ( $ optionType ) && function_exists ( $ optionType . 'val' ) ) { $ typeCastFunc = $ optionType . 'val' ; $ optionValue = $ typeCastFunc ( $ optionValue ) ; } return $ optionValue ; }

Get option with typecast
@param InputInterface $input
@param string         $optionName
@return mixed


protected function loadConfigFromFile($path, $appType = StaticApplicationInterface::APP_TYPE_WEB)
    {
        if (!isset($this->_reader)) {
            $reader = new ConfigReader([
                'path' => $path,
                'appType' => $appType,
            ]);
            $this->_reader = $reader;
        }
        return $this->_reader->data;
    }

protected function loadConfigFromFile ( $ path , $ appType = StaticApplicationInterface :: APP_TYPE_WEB ) { if ( ! isset ( $ this -> _reader ) ) { $ reader = new ConfigReader ( [ 'path' => $ path , 'appType' => $ appType , ] ) ; $ this -> _reader = $ reader ; } return $ this -> _reader -> data ; }

Load config data from file
@param string $path
@param string $appType
@return array


protected function loadConfig(InputInterface $input, OutputInterface $output, $saveConfig = true)
    {
        $configsPath = $this->getConfigPath($input);
        $appType = $input->getOption('app-type');
        $config = $this->loadConfigFromFile($configsPath, $appType);
        /**
         * Array format
         * [ 'OPTION_NAME:TYPE' => 'CONFIG_ARRAY_PATH', ]
         */
        $configOptions = [
            'app-host' => 'appStatic.hostname',
            'app-port:int' => 'appStatic.port',
            'app-debug:bool' => 'appStatic.debug',
        ];

        foreach ($configOptions as $optionName => $configName) {
            $value = $this->optionOrConfigValue($input, $config, $optionName, $configName);
            ArrayHelper::setValue($config, $configName, $value);
        }

        if ($saveConfig) {
            $this->_reader->data = $config;
            \Reaction::$config = $this->_reader;
        }

        return $config;
    }

Load config data
@param InputInterface  $input
@param OutputInterface $output
@param bool            $saveConfig
@return array|mixed
@throws \Exception


protected function renderConfig(OutputInterface $output, array $config)
    {
        $table = new Table($output);
        $rows = $this->renderConfigRows($config);
        $table->addRows($rows);
        $table->render();
    }

protected function renderConfig ( OutputInterface $ output , array $ config ) { $ table = new Table ( $ output ) ; $ rows = $ this -> renderConfigRows ( $ config ) ; $ table -> addRows ( $ rows ) ; $ table -> render ( ) ; }

Render config as table in console
@param OutputInterface $output
@param array           $config


private function renderValue($value)
    {
        $type = gettype($value);
        $valueStr = null;
        switch ($type) {
            case 'object':
                $valueStr = 'object(' . get_class($value) . ')';
                break;
            case 'array':
                $valueStr = 'array(' . count($value) . ')';
                break;
            case 'boolean':
                $valueStr = $value ? 'TRUE' : 'FALSE';
                break;
            case 'string':
                $valueStr = '"' . $value . '"';
                break;
            default: $valueStr = $value;
        }
        return $valueStr;
    }

private function renderValue ( $ value ) { $ type = gettype ( $ value ) ; $ valueStr = null ; switch ( $ type ) { case 'object' : $ valueStr = 'object(' . get_class ( $ value ) . ')' ; break ; case 'array' : $ valueStr = 'array(' . count ( $ value ) . ')' ; break ; case 'boolean' : $ valueStr = $ value ? 'TRUE' : 'FALSE' ; break ; case 'string' : $ valueStr = '"' . $ value . '"' ; break ; default : $ valueStr = $ value ; } return $ valueStr ; }

Get string representation of value
@param mixed $value
@return string


private function normalizeConfigArrayPath($configPath)
    {
        if (!strpos($configPath, ':')) {
            return $configPath;
        }
        $configPathExp = explode(':', $configPath);
        return reset($configPathExp);
    }

private function normalizeConfigArrayPath ( $ configPath ) { if ( ! strpos ( $ configPath , ':' ) ) { return $ configPath ; } $ configPathExp = explode ( ':' , $ configPath ) ; return reset ( $ configPathExp ) ; }

Normalize config array key path
@param string $configPath
@return string


function _setPackageVersion2_1()
    {
        $info = array(
                                 'version' => '2.1',
                                 'xmlns' => 'http://pear.php.net/dtd/package-2.1',
                                 'xmlns:tasks' => 'http://pear.php.net/dtd/tasks-1.0',
                                 'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
                                 'xsi:schemaLocation' => 'http://pear.php.net/dtd/tasks-1.0
    http://pear.php.net/dtd/tasks-1.0.xsd
    http://pear.php.net/dtd/package-2.1
    http://pear.php.net/dtd/package-2.1.xsd',
                             );
        if (!isset($this->_packageInfo['attribs'])) {
            $this->_packageInfo = array_merge(array('attribs' => $info), $this->_packageInfo);
        } else {
            $this->_packageInfo['attribs'] = $info;
        }
    }

set this as a package.xml version 2.1
@access private

set this as a package . xml version 2 . 1


function clearContents($baseinstall = false)
    {
        $this->_filesValid = false;
        $this->_isValid = 0;
        if (!isset($this->_packageInfo['contents'])) {
            $this->_packageInfo = $this->_insertBefore($this->_packageInfo,
                array('compatible',
                    'dependencies', 'providesextension', 'usesrole', 'usestask',
                    'srcpackage', 'srcuri', 'phprelease', 'extsrcrelease',
                    'extbinrelease', 'zendextsrcrelease', 'zendextbinrelease',
                    'bundle', 'changelog'), array(), 'contents');
        }
        if ($this->getPackageType() != 'bundle') {
            $this->_packageInfo['contents'] =
                array('dir' => array('attribs' => array('name' => '/')));
            if ($baseinstall) {
                $this->_packageInfo['contents']['dir']['attribs']['baseinstalldir'] = $baseinstall;
            }
        } else {
            $this->_packageInfo['contents'] = array('bundledpackage' => array());
        }
    }

function clearContents ( $ baseinstall = false ) { $ this -> _filesValid = false ; $ this -> _isValid = 0 ; if ( ! isset ( $ this -> _packageInfo [ 'contents' ] ) ) { $ this -> _packageInfo = $ this -> _insertBefore ( $ this -> _packageInfo , array ( 'compatible' , 'dependencies' , 'providesextension' , 'usesrole' , 'usestask' , 'srcpackage' , 'srcuri' , 'phprelease' , 'extsrcrelease' , 'extbinrelease' , 'zendextsrcrelease' , 'zendextbinrelease' , 'bundle' , 'changelog' ) , array ( ) , 'contents' ) ; } if ( $ this -> getPackageType ( ) != 'bundle' ) { $ this -> _packageInfo [ 'contents' ] = array ( 'dir' => array ( 'attribs' => array ( 'name' => '/' ) ) ) ; if ( $ baseinstall ) { $ this -> _packageInfo [ 'contents' ] [ 'dir' ] [ 'attribs' ] [ 'baseinstalldir' ] = $ baseinstall ; } } else { $ this -> _packageInfo [ 'contents' ] = array ( 'bundledpackage' => array ( ) ) ; } }

Reset the listing of package contents
@param string base installation dir for the whole package, if any


function clearDeps()
    {
        if (!isset($this->_packageInfo['dependencies'])) {
            $this->_packageInfo = $this->_mergeTag($this->_packageInfo, array(),
                array(
                    'dependencies' => array('providesextension', 'usesrole', 'usestask',
                        'srcpackage', 'srcuri', 'phprelease', 'extsrcrelease', 'extbinrelease',
                        'zendextsrcrelease', 'zendextbinrelease', 'bundle', 'changelog')));
        }
        $this->_packageInfo['dependencies'] = array();
    }

function clearDeps ( ) { if ( ! isset ( $ this -> _packageInfo [ 'dependencies' ] ) ) { $ this -> _packageInfo = $ this -> _mergeTag ( $ this -> _packageInfo , array ( ) , array ( 'dependencies' => array ( 'providesextension' , 'usesrole' , 'usestask' , 'srcpackage' , 'srcuri' , 'phprelease' , 'extsrcrelease' , 'extbinrelease' , 'zendextsrcrelease' , 'zendextbinrelease' , 'bundle' , 'changelog' ) ) ) ; } $ this -> _packageInfo [ 'dependencies' ] = array ( ) ; }

Reset dependencies prior to adding new ones


function setPackageType($type)
    {
        $this->_isValid = 0;
        if (!in_array($type, array('php', 'extbin', 'extsrc', 'zendextsrc',
                                   'zendextbin', 'bundle'))) {
            return false;
        }

        if (in_array($type, array('zendextsrc', 'zendextbin'))) {
            $this->_setPackageVersion2_1();
        }

        if ($type != 'bundle') {
            $type .= 'release';
        }

        foreach (array('phprelease', 'extbinrelease', 'extsrcrelease',
                       'zendextsrcrelease', 'zendextbinrelease', 'bundle') as $test) {
            unset($this->_packageInfo[$test]);
        }

        if (!isset($this->_packageInfo[$type])) {
            // ensure that the release tag is set up
            $this->_packageInfo = $this->_insertBefore($this->_packageInfo, array('changelog'),
                array(), $type);
        }

        $this->_packageInfo[$type] = array();
        return true;
    }

Set the kind of package, and erase all release tags

- a php package is a PEAR-style package
- an extbin package is a PECL-style extension binary
- an extsrc package is a PECL-style source for a binary
- an zendextbin package is a PECL-style zend extension binary
- an zendextsrc package is a PECL-style source for a zend extension binary
- a bundle package is a collection of other pre-packaged packages
@param php|extbin|extsrc|zendextsrc|zendextbin|bundle
@return bool success

Set the kind of package and erase all release tags