private function checking() : void
    {
        $cleared = ! ($this->cIdleCount() + $this->cBusyCount());

        if ($this->exiting) {
            if ($this->pool && ($closed = $this->pool->closed())->pended() && $cleared) {
                $closed->resolve();
            }
            return;
        }

        $cleared && $this->resizing(
            max(
                1,
                $this->options->initial,
                min($this->getWaitQ->count(), $this->options->maxIdle)
            ),
            'minimum-scaling'
        );
    }

private function checking ( ) : void { $ cleared = ! ( $ this -> cIdleCount ( ) + $ this -> cBusyCount ( ) ) ; if ( $ this -> exiting ) { if ( $ this -> pool && ( $ closed = $ this -> pool -> closed ( ) ) -> pended ( ) && $ cleared ) { $ closed -> resolve ( ) ; } return ; } $ cleared && $ this -> resizing ( max ( 1 , $ this -> options -> initial , min ( $ this -> getWaitQ -> count ( ) , $ this -> options -> maxIdle ) ) , 'minimum-scaling' ) ; }


public function getHeaders(): array
    {
        $headers        = [];
        $specialHeaders = self::SPECIAL_HEADERS;

        foreach ($this->collection as $key => $value) {
            if (
                \in_array($key, $specialHeaders, true)
                || 0 === strpos($key, 'HTTP_')
            ) {
                $headers[$this->getHeaderName($key)] = $value;
            }
        }

        return $headers;
    }

public function getHeaders ( ) : array { $ headers = [ ] ; $ specialHeaders = self :: SPECIAL_HEADERS ; foreach ( $ this -> collection as $ key => $ value ) { if ( \ in_array ( $ key , $ specialHeaders , true ) || 0 === strpos ( $ key , 'HTTP_' ) ) { $ headers [ $ this -> getHeaderName ( $ key ) ] = $ value ; } } return $ headers ; }

Get all headers from server.

@return array


protected function getHeaderName($header): string
    {
        if (0 === strpos($header, 'HTTP_')) {
            $header = substr($header, 5);
        }

        $header =
            str_replace(
                ' ',
                '-',
                ucwords(str_replace('_', ' ', strtolower($header)))
            );

        return $header;
    }

protected
function
getHeaderName
(
$
header
)
:
string
{
if
(
0
===
strpos
(
$
header
,
'HTTP_'
)
)
{
$
header
=
substr
(
$
header
,
5
)
;
}
$
header
=
str_replace
(
' '
,
'-'
,
ucwords
(
str_replace
(
'_'
,
' '
,
strtolower
(
$
header
)
)
)
)
;
return
$
header
;
}

Get the correct HTTP header name.

@param string $header

@return string


public function write(array $messages, bool $newLine = null, OutputStyle $outputStyle = null): void
    {
        foreach ($messages as $message) {
            $this->writeMessage($message, $newLine, $outputStyle);
        }
    }

public function write ( array $ messages , bool $ newLine = null , OutputStyle $ outputStyle = null ) : void { foreach ( $ messages as $ message ) { $ this -> writeMessage ( $ message , $ newLine , $ outputStyle ) ; } }

Write messages to the console.

@param array       $messages    The messages
@param bool        $newLine     [optional] Whether to use new lines
between each message
@param OutputStyle $outputStyle [optional] The output style to use

@throws \InvalidArgumentException

@return void


public function writeMessage(string $message, bool $newLine = null, OutputStyle $outputStyle = null): void
    {
        $newLine         = $newLine ?? false;
        $outputStyleType =
            $outputStyle ? $outputStyle->getValue() : OutputStyle::NORMAL;

        switch ($outputStyleType) {
            case OutputStyle::NORMAL:
                $message = $this->formatter->format($message);
                break;
            case OutputStyle::RAW:
                break;
            case OutputStyle::PLAIN:
                $message = strip_tags($this->formatter->format($message));
                break;
        }

        $this->writeOut($message, $newLine);
    }

public function writeMessage ( string $ message , bool $ newLine = null , OutputStyle $ outputStyle = null ) : void { $ newLine = $ newLine ?? false ; $ outputStyleType = $ outputStyle ? $ outputStyle -> getValue ( ) : OutputStyle :: NORMAL ; switch ( $ outputStyleType ) { case OutputStyle :: NORMAL : $ message = $ this -> formatter -> format ( $ message ) ; break ; case OutputStyle :: RAW : break ; case OutputStyle :: PLAIN : $ message = strip_tags ( $ this -> formatter -> format ( $ message ) ) ; break ; } $ this -> writeOut ( $ message , $ newLine ) ; }

Write a message to the console.

@param string      $message     The message
@param bool        $newLine     [optional] Whether to use new lines
between each message
@param OutputStyle $outputStyle [optional] The output style to use

@throws \InvalidArgumentException

@return void


public function setType($type = null)
    {
        if (is_array($type)) {
            $detected = 0;
            foreach($type as $value) {
                if (is_int($value)) {
                    $detected += $value;
                } else if (in_array($value, $this->_constants)) {
                    $detected += array_search($value, $this->_constants);
                }
            }

            $type = $detected;
        } else if (is_string($type)) {
            if (in_array($type, $this->_constants)) {
                $type = array_search($type, $this->_constants);
            }
        }

        if (!is_int($type) || ($type < 0) || ($type > self::ALL)) {

            throw new Zend_Filter_Exception('Unknown type');
        }

        $this->_type = $type;
        return $this;
    }

public
function
setType
(
$
type
=
)
{
if
(
is_array
(
$
type
)
)
{
$
detected
=
0
;
foreach
(
$
type
as
$
value
)
{
if
(
is_int
(
$
value
)
)
{
$
detected
+=
$
value
;
}
else
if
(
in_array
(
$
value
,
$
this
->
_constants
)
)
{
$
detected
+=
array_search
(
$
value
,
$
this
->
_constants
)
;
}
}
$
type
=
$
detected
;
}
else
if
(
is_string
(
$
type
)
)
{
if
(
in_array
(
$
type
,
$
this
->
_constants
)
)
{
$
type
=
array_search
(
$
type
,
$
this
->
_constants
)
;
}
}
if
(
!
is_int
(
$
type
)
||
(
$
type
<
0
)
||
(
$
type
>
self
::
ALL
)
)
{
throw
new
Zend_Filter_Exception
(
'Unknown type'
)
;
}
$
this
->
_type
=
$
type
;
return
$
this
;
}

Set the null types

@param  integer|array $type
@throws Zend_Filter_Exception
@return Zend_Filter_Null


protected function findInPaths($name, array $paths)
    {
        foreach ($paths as $path) {
            foreach ($this->getPossibleFiles($name) as $file) {

                if ($this->fs->exists($viewPath = $path.'/'.$file)) {
                    return $viewPath;
                }

            }
        }

        throw new InvalidArgumentException("Resource '$name' not found.");
    }

protected
function
findInPaths
(
$
name
,
array
$
paths
)
{
foreach
(
$
paths
as
$
path
)
{
foreach
(
$
this
->
getPossibleFiles
(
$
name
)
as
$
file
)
{
if
(
$
this
->
fs
->
exists
(
$
viewPath
=
$
path
.
'/'
.
$
file
)
)
{
return
$
viewPath
;
}
}
}
throw
new
InvalidArgumentException
(
"Resource '$name' not found."
)
;
}

Find the file in the possible paths

@param  string $name
@param  array  $paths
@throws InvalidArgumentException
@return string Path the the view


protected function getPossibleFiles($name)
    {
        return array_map(function($extension) use ($name) {
            return str_replace('.', '/', $name).'.'.$extension;
        }, $this->extensions);
    }

protected function getPossibleFiles ( $ name ) { return array_map ( function ( $ extension ) use ( $ name ) { return str_replace ( '.' , '/' , $ name ) . '.' . $ extension ; } , $ this -> extensions ) ; }

Get an array of possible files.

@param string $name
@return array


public function start(): void
    {
        // If the session is already active
        if ($this->isActive() || headers_sent()) {
            // No need to reactivate
            return;
        }

        // If the session failed to start
        if (! session_start()) {
            // Throw a new exception
            throw new SessionStartFailure('The session failed to start!');
        }

        // Set the data
        $this->data = &$_SESSION;
    }

public
function
start
(
)
:
void
{
// If the session is already active
if
(
$
this
->
isActive
(
)
||
headers_sent
(
)
)
{
// No need to reactivate
return
;
}
// If the session failed to start
if
(
!
session_start
(
)
)
{
// Throw a new exception
throw
new
SessionStartFailure
(
'The session failed to start!'
)
;
}
// Set the data
$
this
->
data
=
&
$
_SESSION
;
}

Start the session.

@throws \Valkyrja\Session\Exceptions\SessionStartFailure

@return void


public function get(string $id)
    {
        return $this->has($id) ? $this->data[$id] : null;
    }

public function get ( string $ id ) { return $ this -> has ( $ id ) ? $ this -> data [ $ id ] : null ; }

Get an item from the session.

@param string $id The item id

@return mixed


public function set(string $id, string $value): void
    {
        $this->data[$id] = $value;
    }

public function set ( string $ id , string $ value ) : void { $ this -> data [ $ id ] = $ value ; }

Set an item into the session.

@param string $id    The id
@param string $value The value

@return void


public function remove(string $id): bool
    {
        if (! $this->has($id)) {
            return false;
        }

        unset($this->data[$id]);

        return true;
    }

public function remove ( string $ id ) : bool { if ( ! $ this -> has ( $ id ) ) { return false ; } unset ( $ this -> data [ $ id ] ) ; return true ; }

Remove a session item.

@param string $id The item id

@return bool


public function csrf(string $id): string
    {
        $token = bin2hex(random_bytes(64));

        $this->set($id, $token);

        return $token;
    }

public function csrf ( string $ id ) : string { $ token = bin2hex ( random_bytes ( 64 ) ) ; $ this -> set ( $ id , $ token ) ; return $ token ; }

Get a csrf token for a unique token id.

@param string $id The csrf unique token id

@throws \Exception

@return string

Get a csrf token for a unique token id .


public function validateCsrf(string $id, string $token): bool
    {
        if (! $this->has($id)) {
            return false;
        }

        $sessionToken = $this->get($id);

        if (! \is_string($sessionToken)) {
            return false;
        }

        $this->remove($id);

        return hash_equals($token, $sessionToken);
    }

public function validateCsrf ( string $ id , string $ token ) : bool { if ( ! $ this -> has ( $ id ) ) { return false ; } $ sessionToken = $ this -> get ( $ id ) ; if ( ! \ is_string ( $ sessionToken ) ) { return false ; } $ this -> remove ( $ id ) ; return hash_equals ( $ token , $ sessionToken ) ; }

Validate a csrf token.

@param string $id    The csrf unique token id
@param string $token The token to validate

@return bool


public static function humanize($name)
    {
        if (empty($name)) {
            return '';
        }
        $word = static::tableize(static::classify($name), ' ');
        $word = strtoupper($word[0]) . substr($word, 1);
        return $word;
    }

public
static
function
humanize
(
$
name
)
{
if
(
empty
(
$
name
)
)
{
return
''
;
}
$
word
=
static
::
tableize
(
static
::
classify
(
$
name
)
,
' '
)
;
$
word
=
strtoupper
(
$
word
[
0
]
)
.
substr
(
$
word
,
1
)
;
return
$
word
;
}

Convert word in to the human format.
@param  [type] $name [description]
@return [type]       [description]


public function delete($clean_only = false): bool
    {
        $path = $this->replaceDirectorySeperator($this->filename);

        if (!file_exists($path)) {
            return true;
        }

        if (!is_dir($path)) {
            return unlink($path);
        }

        $files = scandir($path);

        foreach ($files as $item) {

            $file = $path . DIRECTORY_SEPARATOR . $item;

            if (is_dir($file)) {
                $this->delete($file);
            }
            else {
                unlink($file);
            }
        }

        return $clean_only == false ? rmdir($path) : true;
    }

public function delete ( $ clean_only = false ) : bool { $ path = $ this -> replaceDirectorySeperator ( $ this -> filename ) ; if ( ! file_exists ( $ path ) ) { return true ; } if ( ! is_dir ( $ path ) ) { return unlink ( $ path ) ; } $ files = scandir ( $ path ) ; foreach ( $ files as $ item ) { $ file = $ path . DIRECTORY_SEPARATOR . $ item ; if ( is_dir ( $ file ) ) { $ this -> delete ( $ file ) ; } else { unlink ( $ file ) ; } } return $ clean_only == false ? rmdir ( $ path ) : true ; }

Deletes a file or a complete directory tree

@param boolean $clean_only
Flag to delete only files while a directorystructure stays intact

@return bool


public function move($destination)
    {
        if (copy($this->filename, $destination)) {
            unlink($this->filename);

            $this->filename = $destination;

            return $destination;
        }
        else {
            return false;
        }
    }

public function move ( $ destination ) { if ( copy ( $ this -> filename , $ destination ) ) { unlink ( $ this -> filename ) ; $ this -> filename = $ destination ; return $ destination ; } else { return false ; } }

Moves the source to the destination.
Both parameter have to be a full paths.On success the return value will be the destination path.
Otherwise it will be boolean false.

@param string $source
Path to source file
@param string $destination
Path to destination file

@return string boolean

Moves the source to the destination . Both parameter have to be a full paths . On success the return value will be the destination path . Otherwise it will be boolean false .


public function clean($delimiter = '-')
    {
        // The fileextension should not be normalized.
        if (strrpos($this->filename, '.') !== false) {
            list ($name, $extension) = explode('.', $this->filename);
        }

        $normalize = new Normalize($name);

        $name = $normalize->normalize();
        $name = preg_replace('/[^[:alnum:]\-]+/', $delimiter, $name);
        $name = preg_replace('/' . $delimiter . '+/', $delimiter, $name);
        $name = rtrim($name, $delimiter);

        $cleaned = isset($extension) ? $name . '.' . $extension : $name;

        return $cleaned;
    }

Cleans up a filename string from all characters which can make trouble on filesystems.

@param string $name
The string to cleanup
@param string $delimiter

@return string

Cleans up a filename string from all characters which can make trouble on filesystems .


final public function dispatch($name, EventInterface $event)
    {
        if ($this->hasDispatcher()) {
            $this->getDispatcher()->dispatch($name, $event);
            return true;
        }
        return false;
    }

final public function dispatch ( $ name , EventInterface $ event ) { if ( $ this -> hasDispatcher ( ) ) { $ this -> getDispatcher ( ) -> dispatch ( $ name , $ event ) ; return true ; } return false ; }

Dispatch an event if the dispatcher is loaded
@param string $name event name to dispatch
@param EventInterface $event
@return boolean


public function handle($level, $message, $file, $line, $context)
    {
        if ( $this->level === 0 ) return true;

        if ( $level & (E_USER_DEPRECATED | E_DEPRECATED) ) {
            if (self::$logger !== null) {
                if ( version_compare(PHP_VERSION, '5.4', '<') ) {
                    $stack = array_slice(debug_backtrace(false), 0, 10);
                } else {
                    $stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 10);
                }

                self::$logger->warning($message, array(
                    'type' => self::TYPE_DEPRECATION,
                    'stack' => $stack
                ));
            }

            return true;
        }

        if ( error_reporting() & $level && $this->level & $level ) {
            $this->generateErrorException($level, $message, $file, $line, false);
        }

        return true;
    }

public function handle ( $ level , $ message , $ file , $ line , $ context ) { if ( $ this -> level === 0 ) return true ; if ( $ level & ( E_USER_DEPRECATED | E_DEPRECATED ) ) { if ( self :: $ logger !== null ) { if ( version_compare ( PHP_VERSION , '5.4' , '<' ) ) { $ stack = array_slice ( debug_backtrace ( false ) , 0 , 10 ) ; } else { $ stack = debug_backtrace ( DEBUG_BACKTRACE_IGNORE_ARGS , 10 ) ; } self :: $ logger -> warning ( $ message , array ( 'type' => self :: TYPE_DEPRECATION , 'stack' => $ stack ) ) ; } return true ; } if ( error_reporting ( ) & $ level && $ this -> level & $ level ) { $ this -> generateErrorException ( $ level , $ message , $ file , $ line , false ) ; } return true ; }

This method will be used by set_error_handler

@throws \ErrorException When error_reporting returns error


public function handleFatal()
    {
        $error = $this->getLastError();
        if ($error === null) return;

        unset($this->reservedMemory);
        $type = $error['type'];
        if ( $this->level === 0 || !in_array($type, array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) {
            return;
        }

        // get current exception handler
        $exceptionHandler = set_exception_handler(function() {});
        restore_exception_handler();

        if (
            is_array($exceptionHandler) &&
            $exceptionHandler[0] instanceof Error
        ) {
            $this->generateErrorException($type, $error['message'], $error['file'], $error['line']);
        }
    }

public
function
handleFatal
(
)
{
$
error
=
$
this
->
getLastError
(
)
;
if
(
$
error
===
)
return
;
unset
(
$
this
->
reservedMemory
)
;
$
type
=
$
error
[
'type'
]
;
if
(
$
this
->
level
===
0
||
!
in_array
(
$
type
,
array
(
E_ERROR
,
E_CORE_ERROR
,
E_COMPILE_ERROR
,
E_PARSE
)
)
)
{
return
;
}
// get current exception handler
$
exceptionHandler
=
set_exception_handler
(
function
(
)
{
}
)
;
restore_exception_handler
(
)
;
if
(
is_array
(
$
exceptionHandler
)
&&
$
exceptionHandler
[
0
]
instanceof
Error
)
{
$
this
->
generateErrorException
(
$
type
,
$
error
[
'message'
]
,
$
error
[
'file'
]
,
$
error
[
'line'
]
)
;
}
}

This method will be used by register_shutdown_function


public function save() {
        if ($this->validate() == false) {
            return false;
        }

        if ($isNewItem = ($this->item === null)) {
            $this->item = $this->createItem($this->name);
        } else {
            $oldName = $this->item->name;
        }

        $this->item->name = $this->name;
        $this->item->description = $this->description;

        if (!empty($this->rule)) {
            $rule = \Yii::createObject($this->rule);
            if (null === $this->manager->getRule($rule->name)) {
                $this->manager->add($rule);
            }
            $this->item->ruleName = $rule->name;
        } else {
            $this->item->ruleName = null;
        }

        if ($isNewItem) {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been created'));
            $this->manager->add($this->item);
        } else {
            \Yii::$app->session->setFlash('success', \Yii::t('rbac', 'Item has been updated'));
            $this->manager->update($oldName, $this->item);
        }

        $this->updateChildren();

        return true;
    }

public
function
save
(
)
{
if
(
$
this
->
validate
(
)
==
false
)
{
return
false
;
}
if
(
$
isNewItem
=
(
$
this
->
item
===
)
)
{
$
this
->
item
=
$
this
->
createItem
(
$
this
->
name
)
;
}
else
{
$
oldName
=
$
this
->
item
->
name
;
}
$
this
->
item
->
name
=
$
this
->
name
;
$
this
->
item
->
description
=
$
this
->
description
;
if
(
!
empty
(
$
this
->
rule
)
)
{
$
rule
=
\
Yii
::
createObject
(
$
this
->
rule
)
;
if
(
===
$
this
->
manager
->
getRule
(
$
rule
->
name
)
)
{
$
this
->
manager
->
add
(
$
rule
)
;
}
$
this
->
item
->
ruleName
=
$
rule
->
name
;
}
else
{
$
this
->
item
->
ruleName
=
;
}
if
(
$
isNewItem
)
{
\
Yii
::
$
app
->
session
->
setFlash
(
'success'
,
\
Yii
::
t
(
'rbac'
,
'Item has been created'
)
)
;
$
this
->
manager
->
add
(
$
this
->
item
)
;
}
else
{
\
Yii
::
$
app
->
session
->
setFlash
(
'success'
,
\
Yii
::
t
(
'rbac'
,
'Item has been updated'
)
)
;
$
this
->
manager
->
update
(
$
oldName
,
$
this
->
item
)
;
}
$
this
->
updateChildren
(
)
;
return
true
;
}


public function toString(/*boolean*/ $includeFile = false) {
    $format = true === $includeFile
      ? '%s #%d (%s): %s in %s(%d)'
      : '%s #%d (%s): %s';
    return sprintf(
      $format,
      $this->getType(),
      $this->getCode(),
      $this->getMagic(),
      $this->getMessage(),
      $this->getFile(),
      $this->getLine()
    );
  }

public
function
toString
(
/*boolean*/
$
includeFile
=
false
)
{
$
format
=
true
===
$
includeFile
'%s #%d (%s): %s in %s(%d)'
:
'%s #%d (%s): %s'
;
return
sprintf
(
$
format
,
$
this
->
getType
(
)
,
$
this
->
getCode
(
)
,
$
this
->
getMagic
(
)
,
$
this
->
getMessage
(
)
,
$
this
->
getFile
(
)
,
$
this
->
getLine
(
)
)
;
}

Returns the error as a string with all necessary details.

@param boolean $includeFile whether to include source file name and line
@return string

Returns the error as a string with all necessary details .


public static function xml($original) {
    $array = self::convert($original);
    $xml_data = new \SimpleXMLElement('<?xml version="1.0"?><data></data>');
    self::arrayToXml($array, $xml_data);
    return $xml_data->asXML();
  }

public
static
function
xml
(
$
original
)
{
$
array
=
self
::
convert
(
$
original
)
;
$
xml_data
=
new
\
SimpleXMLElement
(
'<?xml version="1.0"?><data></data>'
)
;
self
::
arrayToXml
(
$
array
,
$
xml_data
)
;
return
$
xml_data
->
asXML
(
)
;
}

Return XML object.

@param string $original
The text, in tagged corpus format.

@return object
An XML object.


protected static function convert($original = '') {
    $array = [];
    // Only search for tags within header section, if demarcated.
    $header_split = preg_split('/<End Header>/', $original);
    preg_match_all("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", $header_split[0], $matches, PREG_SET_ORDER);
    if (isset($matches[0])) {
      // Store <TAGNAME: VALUE> strings.
      foreach ($matches as $key => $values) {
        $values[2] = trim($values[2]);
        $multiple_terms = preg_grep('/;/', explode("\n", $values[2]));
        if (!empty($multiple_terms)) {
          $terms = preg_split('/;/', $values[2]);
          foreach ($terms as $i => &$term) {
            if (empty($term)) {
              unset($terms[$i]);
            }
            $term = (string) trim($term);
          }
        }
        else {
          $terms = (string) trim($values[2]);
        }
        $array[trim($values[1])] = $terms;
      }
    }

    // Remove tags and parse each line into an array element.
    if (isset($header_split[1])) {
      $untagged = $header_split[1];
    }
    else {
      $untagged = preg_replace("/<([a-zA-Z0-9_ -]*):([a-zA-Z0-9_&;, -]*)>/", "", $original);
      $untagged = str_replace('<End Header>', '', $untagged);
    }
    $clean = '';
    $lines = preg_split('/((\r?\n)|(\n?\r))/', htmlspecialchars($untagged, ENT_NOQUOTES));
    $end = end($lines);
    foreach ($lines as $key => $line) {
      if ($line != '') {
        $clean .= $line;
        if ($key != $end) {
          $clean .= PHP_EOL;
        }
      }
    }
    // Add a new array element, 'text', to the array. If nothing else, the
    // $array array will now contain the 'text' element with an empty string.
    $array['text'] = $clean;
    return $array;
  }

Convert tag format into PHP array.

@param string $original
The text, in tagged corpus format.


public function load($filename, $merge_globals = true, $stack_name = null, $handler = null)
    {
        $file = new \SplFileInfo($filename);
        if ($file->isFile()) {
            if (empty($handler)) {
                $handler = $file->getExtension();
            }
            $factory = \Library\Factory::create()
                ->factoryName(__CLASS__)
                ->mustImplement(Kernel::CONFIG_FILETYPE_INTERFACE)
                ->defaultNamespace(Kernel::CONFIG_FILETYPE_DEFAULT_NAMESPACE)
                ->classNameMask(array('%s', '%s'.Kernel::CONFIG_FILETYPE_SUFFIX))
                ;
            $config = $factory->build($handler);
            $values = $config->parse($file);
            if (!empty($values)) {
                $this->set($values, $merge_globals, $stack_name);
                $this->_registerConfigFile($filename, count($values));
            } else {
                $this->_registerConfigFile($filename, 'empty content');
            }
        } else {
            throw new ErrorException(
                sprintf('Configuration file "%s" not found!', $filename)
            );
        }
        return $this;
    }

public
function
load
(
$
filename
,
$
merge_globals
=
true
,
$
stack_name
=
,
$
handler
=
)
{
$
file
=
new
\
SplFileInfo
(
$
filename
)
;
if
(
$
file
->
isFile
(
)
)
{
if
(
empty
(
$
handler
)
)
{
$
handler
=
$
file
->
getExtension
(
)
;
}
$
factory
=
\
Library
\
Factory
::
create
(
)
->
factoryName
(
__CLASS__
)
->
mustImplement
(
Kernel
::
CONFIG_FILETYPE_INTERFACE
)
->
defaultNamespace
(
Kernel
::
CONFIG_FILETYPE_DEFAULT_NAMESPACE
)
->
classNameMask
(
array
(
'%s'
,
'%s'
.
Kernel
::
CONFIG_FILETYPE_SUFFIX
)
)
;
$
config
=
$
factory
->
build
(
$
handler
)
;
$
values
=
$
config
->
parse
(
$
file
)
;
if
(
!
empty
(
$
values
)
)
{
$
this
->
set
(
$
values
,
$
merge_globals
,
$
stack_name
)
;
$
this
->
_registerConfigFile
(
$
filename
,
count
(
$
values
)
)
;
}
else
{
$
this
->
_registerConfigFile
(
$
filename
,
'empty content'
)
;
}
}
else
{
throw
new
ErrorException
(
sprintf
(
'Configuration file "%s" not found!'
,
$
filename
)
)
;
}
return
$
this
;
}

Load and parse a configuration file

@param   string      $filename
@param   bool        $merge_globals
@param   null|string $stack_name
@param   null|string $handler    A classname to parse concerned config content
@return  self
@throws  \CarteBlanche\Exception\ErrorException if the file is not found


public function set(array $config, $merge_globals = true, $stack_name = null)
    {
        if (!empty($config)) {
            $config = $this->_buildConfigStack($config);
            if (!empty($stack_name)) {
                $this->getRegistry()->loadStack($stack_name);
            }
            foreach ($config as $index=>$val) {
                $this->getRegistry()->setEntry($index, $val);
            }
            if (!empty($stack_name)) {
                $this->getRegistry()->saveStack($stack_name);
            }
        }

        if (!$merge_globals) {
            return $config;
        } else {
            $this->getRegistry()->loadStack(self::$global_config_id);
            $globals = array_replace_recursive(
                $this->getRegistry()->dump(), $config
            );
            foreach ($globals as $index=>$val) {
                $this->getRegistry()->setEntry($index, $val);
            }
            $this->getRegistry()->saveStack(self::$global_config_id);
            return $this;
        }
    }

public function set ( array $ config , $ merge_globals = true , $ stack_name = null ) { if ( ! empty ( $ config ) ) { $ config = $ this -> _buildConfigStack ( $ config ) ; if ( ! empty ( $ stack_name ) ) { $ this -> getRegistry ( ) -> loadStack ( $ stack_name ) ; } foreach ( $ config as $ index => $ val ) { $ this -> getRegistry ( ) -> setEntry ( $ index , $ val ) ; } if ( ! empty ( $ stack_name ) ) { $ this -> getRegistry ( ) -> saveStack ( $ stack_name ) ; } } if ( ! $ merge_globals ) { return $ config ; } else { $ this -> getRegistry ( ) -> loadStack ( self :: $ global_config_id ) ; $ globals = array_replace_recursive ( $ this -> getRegistry ( ) -> dump ( ) , $ config ) ; foreach ( $ globals as $ index => $ val ) { $ this -> getRegistry ( ) -> setEntry ( $ index , $ val ) ; } $ this -> getRegistry ( ) -> saveStack ( self :: $ global_config_id ) ; return $ this ; } }

Parse and set a configuration array

@param   array       $config
@param   bool        $merge_globals
@param   null/string $stack_name
@return  self/array  Returns the parsed array if `$merge_globals` is false, the config object otherwise


public function get($index, $flag = self::NOT_FOUND_GRACEFULLY, $default = null, $stack_name = 'global')
    {
        $value = null;
        if ($stack_name==='global') {
            $config = $this->getRegistry()->dumpStack(self::$global_config_id);
        } else {
            if ($this->getRegistry()->isStack($stack_name)) {
                $config = $this->getRegistry()->dumpStack($stack_name);
            } else {
                if ($flag & self::NOT_FOUND_ERROR) {
                    throw new InvalidArgumentException(
                        sprintf('Unknown configuration stack "%s"!', $stack_name)
                    );
                } else {
                    return $default;
                }
            }
        }

        if (strpos($index, self::$depth_separator_char)!==false) {
            $depth_index = explode(self::$depth_separator_char, $index);
            $tmp_conf =& $config;
            foreach ($depth_index as $count=>$_i) {
                if (array_key_exists($_i, $tmp_conf)) {
                    $tmp_conf =& $tmp_conf[$_i];
                } else {
                    if ($count===0) {
                        $stack_name = array_shift($depth_index);
                        return $this->get(
                            implode(self::$depth_separator_char, $depth_index),
                            $flag, $default, $stack_name
                        );
                    }
                    $tmp_conf = array();
                }
            }
            if (!empty($tmp_conf)) {
                $value = $this->_parseConfig($tmp_conf, $stack_name);
            }
        } else {
            if (array_key_exists($index, $config)) {
                $value = $this->_parseConfig($config[$index], $stack_name);
            }
        }

        if (!$value) {
            if ($flag & self::NOT_FOUND_GRACEFULLY) {
                return $default;
            } else {
                throw new InvalidArgumentException(
                    sprintf('Unknown configuration entry "%s"!', $index)
                );
            }
        } else {
            return $value;
        }
    }

public
function
get
(
$
index
,
$
flag
=
self
::
NOT_FOUND_GRACEFULLY
,
$
default
=
,
$
stack_name
=
'global'
)
{
$
value
=
;
if
(
$
stack_name
===
'global'
)
{
$
config
=
$
this
->
getRegistry
(
)
->
dumpStack
(
self
::
$
global_config_id
)
;
}
else
{
if
(
$
this
->
getRegistry
(
)
->
isStack
(
$
stack_name
)
)
{
$
config
=
$
this
->
getRegistry
(
)
->
dumpStack
(
$
stack_name
)
;
}
else
{
if
(
$
flag
&
self
::
NOT_FOUND_ERROR
)
{
throw
new
InvalidArgumentException
(
sprintf
(
'Unknown configuration stack "%s"!'
,
$
stack_name
)
)
;
}
else
{
return
$
default
;
}
}
}
if
(
strpos
(
$
index
,
self
::
$
depth_separator_char
)
!==
false
)
{
$
depth_index
=
explode
(
self
::
$
depth_separator_char
,
$
index
)
;
$
tmp_conf
=
&
$
config
;
foreach
(
$
depth_index
as
$
count
=>
$
_i
)
{
if
(
array_key_exists
(
$
_i
,
$
tmp_conf
)
)
{
$
tmp_conf
=
&
$
tmp_conf
[
$
_i
]
;
}
else
{
if
(
$
count
===
0
)
{
$
stack_name
=
array_shift
(
$
depth_index
)
;
return
$
this
->
get
(
implode
(
self
::
$
depth_separator_char
,
$
depth_index
)
,
$
flag
,
$
default
,
$
stack_name
)
;
}
$
tmp_conf
=
array
(
)
;
}
}
if
(
!
empty
(
$
tmp_conf
)
)
{
$
value
=
$
this
->
_parseConfig
(
$
tmp_conf
,
$
stack_name
)
;
}
}
else
{
if
(
array_key_exists
(
$
index
,
$
config
)
)
{
$
value
=
$
this
->
_parseConfig
(
$
config
[
$
index
]
,
$
stack_name
)
;
}
}
if
(
!
$
value
)
{
if
(
$
flag
&
self
::
NOT_FOUND_GRACEFULLY
)
{
return
$
default
;
}
else
{
throw
new
InvalidArgumentException
(
sprintf
(
'Unknown configuration entry "%s"!'
,
$
index
)
)
;
}
}
else
{
return
$
value
;
}
}

Get a configuration stack or entry

@param   string      $index
@param   int         $flag
@param   null/mixed   $default
@param   string      $stack_name
@return  mixed
@throws  \CarteBlanche\Exception\InvalidArgumentException if the index doesn't exist and `$flag` is NOT_FOUND_ERROR


protected function _buildConfigStack(array $config_array)
    {
        $config = array();
        foreach ($config_array as $index=>$val) {
            $index = $this->_slugify($index);
            $val = $this->_treatValue($val);

            if (strpos($index, self::$depth_separator_char)!==false) {
                $depth_index = explode(self::$depth_separator_char, $index);
                $tmp_conf =& $config;
                foreach ($depth_index as $count=>$_i) {
                    if (!array_key_exists($_i, $tmp_conf)) {
                        $tmp_conf[$_i] = array();
                    }
                    $tmp_conf =& $tmp_conf[$_i];
                    if ($count===count($depth_index)-1) {
                        $tmp_conf = $val;
                    }
                }
                unset($config[$index]);
            } else {
                if (is_array($val)) {
                    foreach ($val as $val_index=>$val_val) {
                        if (strpos($val_index, self::$depth_separator_char)!==false) {
                            $val = $this->_buildConfigStack($val);
                        }
                    }
                }
                $config[$index] = $val;
            }
        }
        return $config;
    }

protected function _buildConfigStack ( array $ config_array ) { $ config = array ( ) ; foreach ( $ config_array as $ index => $ val ) { $ index = $ this -> _slugify ( $ index ) ; $ val = $ this -> _treatValue ( $ val ) ; if ( strpos ( $ index , self :: $ depth_separator_char ) !== false ) { $ depth_index = explode ( self :: $ depth_separator_char , $ index ) ; $ tmp_conf = & $ config ; foreach ( $ depth_index as $ count => $ _i ) { if ( ! array_key_exists ( $ _i , $ tmp_conf ) ) { $ tmp_conf [ $ _i ] = array ( ) ; } $ tmp_conf = & $ tmp_conf [ $ _i ] ; if ( $ count === count ( $ depth_index ) - 1 ) { $ tmp_conf = $ val ; } } unset ( $ config [ $ index ] ) ; } else { if ( is_array ( $ val ) ) { foreach ( $ val as $ val_index => $ val_val ) { if ( strpos ( $ val_index , self :: $ depth_separator_char ) !== false ) { $ val = $ this -> _buildConfigStack ( $ val ) ; } } } $ config [ $ index ] = $ val ; } } return $ config ; }

Rebuild a configuration array

This will slugify all indexes and dispatch values following the dotted indexes.

@param   array   $config_array
@return  array


protected function _parseConfig($conf, $stack_name = 'global')
    {
        if (is_string($conf)) {
            $this->_parseConfigRecursive($conf, null, $stack_name);
        } elseif (is_array($conf)) {
            array_walk_recursive($conf, array($this, '_parseConfigRecursive'), $stack_name);
            $conf = array_filter($conf);
        }
        return $conf;
    }

protected function _parseConfig ( $ conf , $ stack_name = 'global' ) { if ( is_string ( $ conf ) ) { $ this -> _parseConfigRecursive ( $ conf , null , $ stack_name ) ; } elseif ( is_array ( $ conf ) ) { array_walk_recursive ( $ conf , array ( $ this , '_parseConfigRecursive' ) , $ stack_name ) ; $ conf = array_filter ( $ conf ) ; } return $ conf ; }

Parse a configuration stack or entry

This function will complete a configuration entry replacing references to other entries written like :
'name' => '%entry%'
where "entry" is the name of another defined configuration entry.

@param   mixed   $conf
@param   string  $stack_name
@return  mixed


protected function _parseConfigRecursive(&$value, $key = null, $stack_name = 'global')
    {
        if (!is_string($value)) return;

        // escape any '\%'
        $hash = 'XH'.uniqid();
        $value = str_replace('\%', $hash, $value);

        // configuration value notation : %name%
        while (is_string($value) && 0!=preg_match('/^(.*)\%(.*)\%(.*)$/i', $value, $matches) && count($matches)>1) {
            $_cf = $matches[2];
            if ($_cfg_val = $this->get($_cf, self::NOT_FOUND_GRACEFULLY, null, $stack_name)) {
                if (is_array($_cfg_val)) {
                    $value = $_cfg_val;
                } else {
                    $value = $matches[1].$_cfg_val.$matches[3];
                }
            }
            $matches = array();
        }

        // un-escape any '\%'
        if (is_string($value)) {
            $value = str_replace($hash, '%', $value);
        }

        // configuration stack notation : {name}
        if (is_string($value) && 0!=preg_match('/^\{(.*)\}$/i', $value, $matches)) {
            $_cf = $matches[1];
            if (substr(trim($_cf), 0, strlen('function'))!=='function') {
                $_cf = 'function(){ '.$_cf.'; }';
            }
            @eval("\$_cfg_closure = $_cf;");
            if ($_cfg_closure && is_callable($_cfg_closure)) {
                $value = call_user_func($_cfg_closure);
            }
        }
    }

Parse a configuration stack array recursively

@param   mixed       $value
@param   null/string $key
@param   string      $stack_name
@return  void        As the value is set by reference, nothing is returned but the original array is modified


protected function compileJoinConstraint(array $clause) {
		$firstColumn = $this->wrap($clause['firstColumn']);

		if ($clause['where']) {
			if ($clause['operator'] === 'in' || $clause['operator'] === 'not in') {
				$secondColumn = '('.implode(', ', array_fill(0, $clause['secondColumn'], '?')).')';
			} else {
				$secondColumn = '?';
			}
		} else {
			$secondColumn = $this->wrap($clause['secondColumn']);
		}

		return "{$clause['boolean']} $firstColumn {$clause['operator']} $secondColumn";
	}

Create a join clause constraint segment.

@param  array   $clause
@return string

Create a join clause constraint segment .


protected function whereNull(Builder $query, $where) {
		$null = $where['not'] ? 'not null' : 'null';

		return $this->wrap($where['column']).' is '.$null;
	}

protected
function
whereNull
(
Builder
$
query
,
$
where
)
{
$
=
$
where
[
'not'
]
'not null'
:
'null'
;
return
$
this
->
wrap
(
$
where
[
'column'
]
)
.
' is '
.
$
;
}

Compile a "where null" clause.

@param  Builder $query
@param  array  $where
@return string


public function compileInsert(Builder $query) {
		$table = $this->wrap($query->from[0]);

		$columns = $this->columnize(array_keys(reset($query->inserts)));

		// We need to build a list of parameter place-holders of values that are bound
		// to the query. Each insert should have the exact same amount of parameter
		// bindings so we can just go off the first list of values in this array.
		$parameters = $this->parameterize(reset($query->inserts));

		$value = array_fill(0, count($query->inserts), "($parameters)");

		$parameters = implode(', ', $value);

		return "insert into $table ($columns) values $parameters";
	}

Compile an insert statement into SQL.

@param  Builder $query
@param  array  $values
@return string


public function compileUpdate(Builder $query) {
		$table = $this->wrap($query->from[0]);

		// Each one of the columns in the update statements needs to be wrapped in the
		// keyword identifiers, also a place-holder needs to be created for each of
		// the values in the list of bindings so we can make the sets statements.
		$columns = array();

		foreach ($query->updates as $key => $value) {
			$columns[] = $this->wrap($key).' = ?';
		}

		$columns = implode(', ', $columns);

		$joins = isset($query->joins) ? ' '.$this->compileJoins($query, $query->joins) : '';

		// Of course, update queries may also be constrained by where clauses so we'll
		// need to compile the where clauses and attach it to the query so only the
		// intended records are updated by the SQL statements we generate to run.
		$where = $this->compileWheres($query);

		$sql = trim("update {$table}{$joins} set {$columns} {$where}");

		if (isset($query->orders)) {
			$sql .= ' '.$this->compileOrders($query, $query->orders);
		}
		if (isset($query->limit)) {
			$sql .= ' '.$this->compileLimit($query, $query->limit);
		}

		return trim($sql);
	}

Compile an update statement into SQL.

@param  Builder $query
@param  array  $values
@return string


public function compileDelete(Builder $query) {
		$table = $this->wrap($query->from[0]);

		$where = $this->compileWheres($query);

		if (isset($query->joins)) {
			$joins = ' '.$this->compileJoins($query, $query->joins);

			$sql = trim("delete $table from {$table}{$joins} $where");

		} else {
			$sql = trim("delete from $table $where");

			if (isset($query->orders)) {
				$sql .= ' '.$this->compileOrders($query, $query->orders);
			}

			if (isset($query->limit)) {
				$sql .= ' '.$this->compileLimit($query, $query->limit);
			}
		}
		return $sql;

	}

Compile a delete statement into SQL.

@param  Builder $query
@return string


private function wrap($value) {

		if (strpos(strtolower($value), 'null') !== false) {
			return $value;
		}

		// If the value being wrapped has a column alias we will need to separate out
		// the pieces so we can wrap each of the segments of the expression on it
		// own, and then joins them both back together with the "as" connector.
		if (strpos(strtolower($value), ' as ') !== false) {
			$segments = explode(' ', $value);

			return $this->wrap($segments[0]).' as '.$this->wrapValue($segments[2]);
		}

		$wrapped = array();

		$segments = explode('.', $value);

		// If the value is not an aliased table expression, we'll just wrap it like
		// normal, so if there is more than one segment, we will wrap the first
		// segments as if it was a table and the rest as just regular values.
		foreach ($segments as $key => $segment) {
			$wrapped[] = $this->wrapValue($segment);
		}

		return implode('.', $wrapped);
	}

Wrap a value in keyword identifiers.

@param  string  $value
@return string


public function withArguments($arguments)
    {
        if (is_array($arguments)) {
            $arguments = new Argument\ArgumentsWildcard($arguments);
        }

        if (!$arguments instanceof Argument\ArgumentsWildcard) {
            throw new InvalidArgumentException(sprintf(
                "Either an array or an instance of ArgumentsWildcard expected as\n".
                'a `FunctionProphecy::withArguments()` argument, but got %s.',
                gettype($arguments)
            ));
        }

        $this->argumentsWildcard = $arguments;

        return $this;
    }

Sets argument wildcard.

@param array|Argument\ArgumentsWildcard $arguments

@return $this

@throws InvalidArgumentException


public function will($promise)
    {
        if (is_callable($promise)) {
            $promise = new Promise\CallbackPromise($promise);
        }

        if (!$promise instanceof Promise\PromiseInterface) {
            throw new InvalidArgumentException(sprintf(
                'Expected callable or instance of PromiseInterface, but got %s.',
                gettype($promise)
            ));
        }

        $this->bind();
        $this->promise = $promise;

        return $this;
    }

Sets custom promise to the prophecy.

@param callable|Promise\PromiseInterface $promise

@return $this

@throws \Prophecy\Exception\InvalidArgumentException


public function should($prediction)
    {
        if (is_callable($prediction)) {
            $prediction = new Prediction\CallbackPrediction($prediction);
        }

        if (!$prediction instanceof Prediction\PredictionInterface) {
            throw new InvalidArgumentException(sprintf(
                'Expected callable or instance of PredictionInterface, but got %s.',
                gettype($prediction)
            ));
        }

        $this->bind();
        $this->prediction = $prediction;

        return $this;
    }

Sets custom prediction to the prophecy.

@param callable|Prediction\PredictionInterface $prediction

@return $this

@throws InvalidArgumentException

Sets custom prediction to the prophecy .


public function shouldHave($prediction)
    {
        if (is_callable($prediction)) {
            $prediction = new Prediction\CallbackPrediction($prediction);
        }

        if (!$prediction instanceof Prediction\PredictionInterface) {
            throw new InvalidArgumentException(sprintf(
                'Expected callable or instance of PredictionInterface, but got %s.',
                gettype($prediction)
            ));
        }

        if (null === $this->promise) {
            $this->willReturn();
        }

        $calls = $this->namespaceProphecy->findCalls($this->name, $this->getArgumentsWildcard());

        try {
            $prediction->check($calls, $this);
            $this->checkedPredictions[] = $prediction;
        } catch (\Exception $e) {
            $this->checkedPredictions[] = $prediction;

            throw $e;
        }

        return $this;
    }

Checks provided prediction immediately.

@param callable|Prediction\PredictionInterface $prediction

@return $this

@throws InvalidArgumentException
@throws \Exception

Checks provided prediction immediately .


public function newGallery(GalleryAdapter $gallery = null)
    {
        if (empty($gallery)) {
            $class   = $this->getNamespaceService() . 'Gallery';
            $gallery = new $class;
        }

        if (! empty($this->plugins)) {
            array_walk($this->plugins, [$gallery, 'addPlugin']);
        }

        return $gallery;

    }

public function newGallery ( GalleryAdapter $ gallery = null ) { if ( empty ( $ gallery ) ) { $ class = $ this -> getNamespaceService ( ) . 'Gallery' ; $ gallery = new $ class ; } if ( ! empty ( $ this -> plugins ) ) { array_walk ( $ this -> plugins , [ $ gallery , 'addPlugin' ] ) ; } return $ gallery ; }

This method create a new service gallery object to interact with the external api service.

@return RestGalleries\APIs\<service>\Gallery

This method create a new service gallery object to interact with the external api service .


public static function connect($callback = '')
    {
        $instance = new static;
        $user     = $instance->newUser();

        if (! empty($callback)) {
            $instance->clientCredentials['callback'] = $callback;
        }

        return $user->connect($instance->clientCredentials);

    }

public static function connect ( $ callback = '' ) { $ instance = new static ; $ user = $ instance -> newUser ( ) ; if ( ! empty ( $ callback ) ) { $ instance -> clientCredentials [ 'callback' ] = $ callback ; } return $ user -> connect ( $ instance -> clientCredentials ) ; }

Takes account credentials and calls the user object to make the requests to get the api authorization.

@param  string $callback
@return \Illuminate\Support\Fluent

Takes account credentials and calls the user object to make the requests to get the api authorization .


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

        return true;
    }

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


public function toSql()
    {
        $table = $this->table();
        $values = $this->values();
        $quoteChar = $this->quoteChar();

        if(is_null($table)){
            throw new \Exception("Define table to insert.");
        }

        if (empty($this->values)) {
            throw new \Exception("No values to insert.");
        }

        // usuwam rzeczy zwiazane z przetwarzaniem zapytania
        $this->reset(true);

        // zliczam ilosc kolumn
        $count = count($this->columns);

        // tworze naglowek
        $scolumns = "";
        for ($i=0; $i < $count; $i++) {
            $column = $this->columns[$i];

            $scolumns .= "{$quoteChar}{$column}{$quoteChar}";

            if ($i != $count-1) {
                $scolumns .= ",";
            }
        }

        // values
        $svalues = "";
        $ccount = count($this->columns);
        $vcount = count($this->values);

        for ($i=0; $i < $vcount; $i++) {
            // pobieram wszystkie wartosci
            $values = $this->values[$i];

            // pobieram klucze
            $keys = array_keys($values);

            // zmienna przetrzymuje wartosci dla VALUES w insercie
            $svalues .= "(";

            for ($j=0; $j < $ccount; $j++) {
                // nazwa kolumny
                $column = $this->columns[$j];

                if (!in_array($column, $keys)) {
                    throw new \Exception("Incorrect values to insert.");
                }

                // pobieram wartosc kolumny
                $value = $values[$column];

                $direct = false;
                if (is_int($value)) {
                    $value = (int)$value;
                    $direct = true;
                }

                if (is_float($value)) {
                    $value = (float)$value;
                    $direct = true;
                }

                if (is_null($value)) {
                    $value = "null";
                    $direct = true;
                }

                if ($direct) {
                    $svalues .= "{$value}";
                }else{
                    $uId = \Labi\Database\Utility\Uid::uId();
                    $svalues .= ":$uId";
                    $this->param($uId, $value, true);
                }

                if ($j !== $ccount-1) {
                    $svalues .= ",";
                }
            }

            $svalues .= ")";

            if ($i !== $vcount-1) {
                $svalues .= ",";
            }
        }

        // budowanie insertu
        $sql = "insert into {$quoteChar}{$table}{$quoteChar} ({$scolumns}) VALUES {$svalues}";

        return $sql;
    }


public function scan(GenericResource $resource, $content)
    {
        // Match all URL references.
        preg_match_all(self::PATH_PATTERN, $content, $matches);
        foreach ($matches[1] as $path) {
            try {
                $this->queue->add(new GenericResource($resource->resolvePath($path)));
            }
            catch (\InvalidArgumentException $e) {
                // Ignore unrecognized paths.
            }
        }
    }

public
function
scan
(
GenericResource
$
resource
,
$
content
)
{
// Match all URL references.
preg_match_all
(
self
::
PATH_PATTERN
,
$
content
,
$
matches
)
;
foreach
(
$
matches
[
1
]
as
$
path
)
{
try
{
$
this
->
queue
->
add
(
new
GenericResource
(
$
resource
->
resolvePath
(
$
path
)
)
)
;
}
catch
(
\
InvalidArgumentException
$
e
)
{
// Ignore unrecognized paths.
}
}
}

Scans CSS content for resources.

@param GenericResource $resource
@param string $content


public function flatMap($flatMapper) {
        if (!is_callable($flatMapper)) {
            throw new Exception("Can't call Some#flatMap with a non callable.");
        }
        $flatMapped = $flatMapper($this->_value);
        if (!($flatMapped instanceof Option)) {
            throw new Exception(
                "Function passed to Some#flatMap must retrun Option"
            );
        }
        return $flatMapped;
    }

This method takes a callable type that takes the wrapped value of the
current `Some` as it's arguments and returns an `Option` type. The
`Option` type returned by the passed in callable is returned by this
method

@param Callable $flatMapper - Fuction to call on the wrapped value
@return Option              - The `Option` produced by the flat mapper
@throws Exception

This method takes a callable type that takes the wrapped value of the current Some as it s arguments and returns an Option type . The Option type returned by the passed in callable is returned by this method


public function filter($predicate) {
        if (!is_callable($predicate)) {
            throw new Exception("Can't call Some#filter with a non callable.");
        }
        if ($predicate($this->_value)) {
            return $this;
        } else {
            return new None();
        }
    }

This function takes a callable as a predicate that takes the wrapped
value of the current `Some` as it's argument. If the predicate returns
true the current `Some` is returned. If the predicate returns false
a new `None` is returned.

@param Callable $predicate - The predicate to check the wrapped value
@return Option             - `Some` on success `None` on failure
@throws Exception

This function takes a callable as a predicate that takes the wrapped value of the current Some as it s argument . If the predicate returns true the current Some is returned . If the predicate returns false a new None is returned .


protected function _executeCallbackStack()
    {
        if (!empty($this->callback_stack)) {
            $_meth = '_executeCallbackAs'.ucfirst($this->callback_response_type);
            foreach ($this->callback_stack as $_callback) {
                $response = $this->$_meth( $_callback, $this->value );
            }
            return $response;
        }
        return null;
    }

protected function _executeCallbackStack ( ) { if ( ! empty ( $ this -> callback_stack ) ) { $ _meth = '_executeCallbackAs' . ucfirst ( $ this -> callback_response_type ) ; foreach ( $ this -> callback_stack as $ _callback ) { $ response = $ this -> $ _meth ( $ _callback , $ this -> value ) ; } return $ response ; } return null ; }

Execution of a callback array on an entry of the data array

@return  mixed


protected function _executeCallbackAsReference($fct, &$entry_value)
    {
        list($fct_name, $args) = $this->_parseCallbackFunctionName($fct);
        array_unshift($args, $entry_value);
        $entry_value = $this->_executeCallback($fct_name, $args);
        return $entry_value;
    }

protected function _executeCallbackAsReference ( $ fct , & $ entry_value ) { list ( $ fct_name , $ args ) = $ this -> _parseCallbackFunctionName ( $ fct ) ; array_unshift ( $ args , $ entry_value ) ; $ entry_value = $ this -> _executeCallback ( $ fct_name , $ args ) ; return $ entry_value ; }

Execution of one callback on a value returning it by reference

@param   string  $fct            The function name to execute, it will be called passing the current value as first argument
@param   mixed   $entry_value    The entry value to execute the callback, passed by reference
@return  mixed


protected function _parseCallbackFunctionName($fct)
    {
        $fct_name = $fct;
        $args = array();

        // case "fct_name(arg1,arg2)"
        if (0!=preg_match('/^
            ([^\(]+)                # the function name
            \(                      # the opening parenthesis of arguments
                (?:
                    ([^\)]+)        # anything but a coma
                ){1,}               # 1 or more times
            \)                      # the closing parenthesis of arguments
        $/xi', $fct, $matches)) {
            $fct_name = $matches[1];
            $args = explode(',', $matches[2]);
        }

        return array($fct_name, $args);
    }

Parse a function name for a callback extracting the arguments if so

@param   string  $fct   The function name to parse
@return  array   An array composed of the function name to execute and the arguments array to pass


public function getConstraints($options)
    {
        $constraints = array();

        if ($options['validate']) {
            $constraints[] = new Image(array(
                'mimeTypes' => array(
                    'image/gif',
                    'image/png',
                    'image/jpg',
                    'image/jpeg'
                ),
                'minWidth'  => $this->calcMin('width', $options),
                'minHeight' => $this->calcMin('height', $options)
            ));
        }

        return $constraints;
    }

public function getConstraints ( $ options ) { $ constraints = array ( ) ; if ( $ options [ 'validate' ] ) { $ constraints [ ] = new Image ( array ( 'mimeTypes' => array ( 'image/gif' , 'image/png' , 'image/jpg' , 'image/jpeg' ) , 'minWidth' => $ this -> calcMin ( 'width' , $ options ) , 'minHeight' => $ this -> calcMin ( 'height' , $ options ) ) ) ; } return $ constraints ; }

Creates and returns constraints for a file field

@param $options
@return array


public function calcMin($option, array $options)
    {
        $min = (isset($options[$option]) ? (int)$options[$option] : 0);

        if (isset($options['instances']) && is_array($options['instances'])) {
            foreach ($options['instances'] as $instance) {
                $value = (isset($instance[$option]) ? (int)$instance[$option] : 0);

                if ($value > $min) {
                    $min = $value;
                }
            }
        }

        return $min;
    }

public function calcMin ( $ option , array $ options ) { $ min = ( isset ( $ options [ $ option ] ) ? ( int ) $ options [ $ option ] : 0 ) ; if ( isset ( $ options [ 'instances' ] ) && is_array ( $ options [ 'instances' ] ) ) { foreach ( $ options [ 'instances' ] as $ instance ) { $ value = ( isset ( $ instance [ $ option ] ) ? ( int ) $ instance [ $ option ] : 0 ) ; if ( $ value > $ min ) { $ min = $ value ; } } } return $ min ; }

Calculates and returns values for the size constraint

@param $option
@param array $options
@return int


public function getController()
    {
        if (!isset($this->_controller)) {
            $data = $this->_dispatchedData;
            if (isset($data[1]) && $data[1] instanceof ControllerInterface) {
                $this->_controller = $data[1];
            }
        }
        return $this->_controller;
    }

public function getController ( ) { if ( ! isset ( $ this -> _controller ) ) { $ data = $ this -> _dispatchedData ; if ( isset ( $ data [ 1 ] ) && $ data [ 1 ] instanceof ControllerInterface ) { $ this -> _controller = $ data [ 1 ] ; } } return $ this -> _controller ; }

Get controller if applicable
@return Controller|null


public function getAction()
    {
        if (!isset($this->_action)) {
            $data = $this->_dispatchedData;
            if (isset($data[2]) && is_string($data[2])) {
                $this->_action = $data[2];
            }
        }
        return $this->_action;
    }

public function getAction ( ) { if ( ! isset ( $ this -> _action ) ) { $ data = $ this -> _dispatchedData ; if ( isset ( $ data [ 2 ] ) && is_string ( $ data [ 2 ] ) ) { $ this -> _action = $ data [ 2 ] ; } } return $ this -> _action ; }

Get controller action if applicable
@return string


public function resolve()
    {
        $callable = [$this->_controller, $this->_controllerMethod];
        $args = $this->_params;
        array_unshift($args, $this->app, $this->_action);
        $promise = new Promise(function($r) use ($callable, $args) {
            $result = call_user_func_array($callable, $args);
            $r($result);
        });
        return $promise->then(
            function($response) {
                return $this->processResponse($response);
            }
        );
    }

public function resolve ( ) { $ callable = [ $ this -> _controller , $ this -> _controllerMethod ] ; $ args = $ this -> _params ; array_unshift ( $ args , $ this -> app , $ this -> _action ) ; $ promise = new Promise ( function ( $ r ) use ( $ callable , $ args ) { $ result = call_user_func_array ( $ callable , $ args ) ; $ r ( $ result ) ; } ) ; return $ promise -> then ( function ( $ response ) { return $ this -> processResponse ( $ response ) ; } ) ; }

Resolve route for request
@return ExtendedPromiseInterface


protected function processDispatchedData() {
        list($code, $controller, $action, $params) = $this->_dispatchedData;

        if ($code === RouterInterface::ERROR_OK) {
            $this->_controllerMethod = static::CONTROLLER_RESOLVE_ACTION;
            $this->_controller = $controller;
            $this->_action = $action;
            $this->_params = $this->_paramsClean = $params;
            //Overwrite query parameters
            if (ArrayHelper::isAssociative($this->_params)) {
                $queryParams = ArrayHelper::merge($this->app->reqHelper->getQueryParams(), $this->_params);
                $this->app->reqHelper->setQueryParams($queryParams);
            }
        } else {
            $exception = $this->getRouterException($code);
            throw $exception;
        }
    }

protected
function
processDispatchedData
(
)
{
list
(
$
code
,
$
controller
,
$
action
,
$
params
)
=
$
this
->
_dispatchedData
;
if
(
$
code
===
RouterInterface
::
ERROR_OK
)
{
$
this
->
_controllerMethod
=
static
::
CONTROLLER_RESOLVE_ACTION
;
$
this
->
_controller
=
$
controller
;
$
this
->
_action
=
$
action
;
$
this
->
_params
=
$
this
->
_paramsClean
=
$
params
;
//Overwrite query parameters
if
(
ArrayHelper
::
isAssociative
(
$
this
->
_params
)
)
{
$
queryParams
=
ArrayHelper
::
merge
(
$
this
->
app
->
reqHelper
->
getQueryParams
(
)
,
$
this
->
_params
)
;
$
this
->
app
->
reqHelper
->
setQueryParams
(
$
queryParams
)
;
}
}
else
{
$
exception
=
$
this
->
getRouterException
(
$
code
)
;
throw
$
exception
;
}
}

Parse data from dispatcher
@throws \Throwable


protected function processResponse($response) {
        if ($response instanceof ResponseInterface) {
            return $response;
        }
        if ($response instanceof ResponseBuilderInterface) {
            return $response->build();
        }
        //Do not throw error on console app
        if (Reaction::isConsoleApp()) {
            return $response;
        }
        $type = is_object($response) ? get_class($response) : gettype($response);
        $message = sprintf('Return value must be instance of "%s", but "%s" given', ResponseInterface::class, $type);
        throw new InvalidArgumentException($message);
    }

Process response from controller action
@param ResponseInterface|ResponseBuilderInterface $response
@return ResponseInterface


protected function getRouterException($code) {
        $errors = [
            RouterInterface::ERROR_NOT_FOUND => NotFoundException::class,
            RouterInterface::ERROR_METHOD_NOT_ALLOWED => MethodNotAllowedException::class,
            '*' => NotSupportedException::class,
        ];
        $errorClass = isset($errors[$code]) ? $errors[$code] : $errors['*'];
        try {
            $exception = Reaction::create($errorClass);
        } catch (InvalidConfigException $createException) {
            return $createException;
        }
        return $exception;
    }

protected function getRouterException ( $ code ) { $ errors = [ RouterInterface :: ERROR_NOT_FOUND => NotFoundException :: class , RouterInterface :: ERROR_METHOD_NOT_ALLOWED => MethodNotAllowedException :: class , '*' => NotSupportedException :: class , ] ; $ errorClass = isset ( $ errors [ $ code ] ) ? $ errors [ $ code ] : $ errors [ '*' ] ; try { $ exception = Reaction :: create ( $ errorClass ) ; } catch ( InvalidConfigException $ createException ) { return $ createException ; } return $ exception ; }

Get Exception by Router error code
@param int $code
@return \Throwable


public static function getTerminalSizes()
    {
        if (self::getOperatingSystem()->equals(OS::WINDOWS) || self::getOperatingSystem()->equals(OS::UNKNOWN)) {
            return ['width' => 100, 'height' => 100];
        }
        preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output);
        if (sizeof($output) == 3) {
            return [
                "height" => @$output[1][0],
                "width"  => @$output[2][0]
            ];
        } else {
            return [
                "width"  => 100,
                "height" => 100
            ];
        }
    }

public
static
function
getTerminalSizes
(
)
{
if
(
self
::
getOperatingSystem
(
)
->
equals
(
OS
::
WINDOWS
)
||
self
::
getOperatingSystem
(
)
->
equals
(
OS
::
UNKNOWN
)
)
{
return
[
'width'
=>
100
,
'height'
=>
100
]
;
}
preg_match_all
(
"/rows.([0-9]+);.columns.([0-9]+);/"
,
strtolower
(
exec
(
'stty -a |grep columns'
)
)
,
$
output
)
;
if
(
sizeof
(
$
output
)
==
3
)
{
return
[
"height"
=>
@
$
output
[
1
]
[
0
]
,
"width"
=>
@
$
output
[
2
]
[
0
]
]
;
}
else
{
return
[
"width"
=>
100
,
"height"
=>
100
]
;
}
}

Get terminal width and height

@return array


public static function getOperatingSystem()
    {
        if (is_null(self::$operatingSystem)) {
            $name = strtolower(php_uname());
            $operatingSystem   = OS::UNKNOWN;
            if (strpos($name, 'darwin') !== false) {
                $operatingSystem = OS::DARWIN;
            } elseif (strpos($name, 'win') !== false) {
                $operatingSystem = OS::WINDOWS;
            } elseif (strpos($name, 'linux') !== false) {
                $operatingSystem = OS::LINUX;
            }
            self::$operatingSystem = new OS($operatingSystem);
        }

        return self::$operatingSystem;
    }

public static function getOperatingSystem ( ) { if ( is_null ( self :: $ operatingSystem ) ) { $ name = strtolower ( php_uname ( ) ) ; $ operatingSystem = OS :: UNKNOWN ; if ( strpos ( $ name , 'darwin' ) !== false ) { $ operatingSystem = OS :: DARWIN ; } elseif ( strpos ( $ name , 'win' ) !== false ) { $ operatingSystem = OS :: WINDOWS ; } elseif ( strpos ( $ name , 'linux' ) !== false ) { $ operatingSystem = OS :: LINUX ; } self :: $ operatingSystem = new OS ( $ operatingSystem ) ; } return self :: $ operatingSystem ; }

Get the current operating system

@return OS


public static function trans($arg1, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
    {
        $i18n = self::getContainer()->get('i18n');
        if (is_object($arg1) && ($arg1 instanceof \DateTime)) {
            if (empty($i18n)) {
                return $arg1->format( !empty($arg2) ? $arg2 : 'Y-m-d H:i:s');
            }
            return \I18n\I18n::getLocalizedDateString($arg1, $arg2, $arg3, $arg4);
        } elseif (is_array($arg1)) {
            if (empty($i18n)) {
                return isset($arg1[$arg2]) ? $arg1[$arg2] : array_shift($arg1);
            }
            return \I18n\I18n::pluralize($arg1, $arg2, $arg3, $arg4);
        } elseif (is_string($arg1)) {
            if ($arg1==='number') {
                if (empty($i18n)) {
                    return $arg2;
                }
                return \I18n\I18n::getLocalizedNumberString($arg2, $arg3);
            } elseif($arg1==='price') {
                if (empty($i18n)) {
                    return $arg2;
                }
                return \I18n\I18n::getLocalizedPriceString($arg2, $arg3);
            } else {
                if (empty($i18n)) {
                    return $arg1;
                }
                return \I18n\I18n::translate($arg1, $arg2, $arg3);
            }
        } else {
            return null;
        }
    }

public
static
function
trans
(
$
arg1
,
$
arg2
=
,
$
arg3
=
,
$
arg4
=
,
$
arg5
=
)
{
$
i18n
=
self
::
getContainer
(
)
->
get
(
'i18n'
)
;
if
(
is_object
(
$
arg1
)
&&
(
$
arg1
instanceof
\
DateTime
)
)
{
if
(
empty
(
$
i18n
)
)
{
return
$
arg1
->
format
(
!
empty
(
$
arg2
)
$
arg2
:
'Y-m-d H:i:s'
)
;
}
return
\
I18n
\
I18n
::
getLocalizedDateString
(
$
arg1
,
$
arg2
,
$
arg3
,
$
arg4
)
;
}
elseif
(
is_array
(
$
arg1
)
)
{
if
(
empty
(
$
i18n
)
)
{
return
isset
(
$
arg1
[
$
arg2
]
)
$
arg1
[
$
arg2
]
:
array_shift
(
$
arg1
)
;
}
return
\
I18n
\
I18n
::
pluralize
(
$
arg1
,
$
arg2
,
$
arg3
,
$
arg4
)
;
}
elseif
(
is_string
(
$
arg1
)
)
{
if
(
$
arg1
===
'number'
)
{
if
(
empty
(
$
i18n
)
)
{
return
$
arg2
;
}
return
\
I18n
\
I18n
::
getLocalizedNumberString
(
$
arg2
,
$
arg3
)
;
}
elseif
(
$
arg1
===
'price'
)
{
if
(
empty
(
$
i18n
)
)
{
return
$
arg2
;
}
return
\
I18n
\
I18n
::
getLocalizedPriceString
(
$
arg2
,
$
arg3
)
;
}
else
{
if
(
empty
(
$
i18n
)
)
{
return
$
arg1
;
}
return
\
I18n
\
I18n
::
translate
(
$
arg1
,
$
arg2
,
$
arg3
)
;
}
}
else
{
return
;
}
}

Full aliasing of internationalization

- will `datify` if `$arg1` is a `DateTime`:
`\I18n\I18n::getLocalizedDateString( date: $arg1 = DateTime , [mask: $arg2 = null] , [charset: $arg3 = 'UTF-8'] , [lang: $arg4 = null] )`
- will `pluralize` if `$arg1` is an array:
`\I18n\I18n::pluralize( indexes: $arg1 = array , [count: $arg2 = 0] , [args: $arg3 = array] , [lang: $arg4 = null] )`
- will `numberify` if `$arg1`=='number':
`\I18n\I18n::getLocalizedNumberString( number: $arg2 = float , [lang: $arg3 = null] )`
- will `currencify` if `$arg1`=='price':
`\I18n\I18n::getLocalizedPriceString( price: $arg2 = float , [lang: $arg3 = null] )`
- will `translate` if `$arg1` is a string and not 'number' or 'price':
`\I18n\I18n::translate( index: $arg1 = string, [params: $arg2 = array] , [lang: $arg3 = null] )`

@param   string/DateTime     $arg1
@param   string/int          $arg2
@param   array/string        $arg3
@param   string              $arg4
@param   string              $arg5
@return  mixed
@alias   \I18n\I18n::translate($index, $args, $lang)
@alias   \I18n\I18n::pluralize($indexes, $number, $args, $lang)
@alias   \I18n\I18n::getLocalizedDateString($date, $mask, $charset, $lang)
@alias   \I18n\I18n::getLocalizedNumberString($number, $lang)
@alias   \I18n\I18n::getLocalizedPriceString($number, $lang)


public static function locate($filename, $type = null)
    {
        $locator = self::getContainer()->get('locator');
        switch ($type) {
            case 'data':
                return $locator->locateData($filename);
                break;
            case 'config':
                return $locator->locateConfig($filename, true);
                break;
            case 'language': case 'i18n':
                return $locator->locateLanguage($filename, true);
                break;
            case 'view':
                return $locator->locateView($filename, true);
                break;
            case 'controller':
                return $locator->locateController($filename);
                break;
            default:
                return $locator->locate($filename);
                break;
        }
    }

public static function locate ( $ filename , $ type = null ) { $ locator = self :: getContainer ( ) -> get ( 'locator' ) ; switch ( $ type ) { case 'data' : return $ locator -> locateData ( $ filename ) ; break ; case 'config' : return $ locator -> locateConfig ( $ filename , true ) ; break ; case 'language' : case 'i18n' : return $ locator -> locateLanguage ( $ filename , true ) ; break ; case 'view' : return $ locator -> locateView ( $ filename , true ) ; break ; case 'controller' : return $ locator -> locateController ( $ filename ) ; break ; default : return $ locator -> locate ( $ filename ) ; break ; } }

Full `\CarteBlanche\App\Locator` handler

@param   string          $filename
@param   null|string     $type   'data', 'config', 'language' or 'i18n', 'view', 'controller'
@alias   \CarteBlanche\App\Locator::locate($filename)

Full \ CarteBlanche \ App \ Locator handler


public function asText($value, $encoding = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        return Html::encode($value, true, $encoding);
    }

public function asText ( $ value , $ encoding = null ) { if ( $ value === null ) { return $ this -> nullDisplay ; } return Html :: encode ( $ value , true , $ encoding ) ; }

Formats the value as an HTML-encoded plain text.
@param string $value the value to be formatted.
@param string $encoding
@return string the formatted result.

Formats the value as an HTML - encoded plain text .


public function asEmail($value, $options = [], $encoding = null)
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        return Html::mailto(Html::encode($value, true, $encoding), $value, $options);
    }

public function asEmail ( $ value , $ options = [ ] , $ encoding = null ) { if ( $ value === null ) { return $ this -> nullDisplay ; } return Html :: mailto ( Html :: encode ( $ value , true , $ encoding ) , $ value , $ options ) ; }

Formats the value as a mailto link.
@param string $value the value to be formatted.
@param array  $options the tag options in terms of name-value pairs. See [[Html::mailto()]].
@param string $encoding
@return string the formatted result.


public function asDecimal($value, $decimals = null, $options = [], $textOptions = [])
    {
        if ($value === null) {
            return $this->nullDisplay;
        }
        $value = $this->normalizeNumericValue($value);

        if ($this->_intlLoaded) {
            $f = $this->createNumberFormatter(NumberFormatter::DECIMAL, $decimals, $options, $textOptions);
            if (($result = $f->format($value)) === false) {
                throw new InvalidArgumentException('Formatting decimal value failed: ' . $f->getErrorCode() . ' ' . $f->getErrorMessage());
            }

            return $result;
        }

        if ($decimals === null) {
            $decimals = 2;
        }

        return number_format($value, $decimals, $this->decimalSeparator, $this->thousandSeparator);
    }

public
function
asDecimal
(
$
value
,
$
decimals
=
,
$
options
=
[
]
,
$
textOptions
=
[
]
)
{
if
(
$
value
===
)
{
return
$
this
->
nullDisplay
;
}
$
value
=
$
this
->
normalizeNumericValue
(
$
value
)
;
if
(
$
this
->
_intlLoaded
)
{
$
f
=
$
this
->
createNumberFormatter
(
NumberFormatter
::
DECIMAL
,
$
decimals
,
$
options
,
$
textOptions
)
;
if
(
(
$
result
=
$
f
->
format
(
$
value
)
)
===
false
)
{
throw
new
InvalidArgumentException
(
'Formatting decimal value failed: '
.
$
f
->
getErrorCode
(
)
.
' '
.
$
f
->
getErrorMessage
(
)
)
;
}
return
$
result
;
}
if
(
$
decimals
===
)
{
$
decimals
=
2
;
}
return
number_format
(
$
value
,
$
decimals
,
$
this
->
decimalSeparator
,
$
this
->
thousandSeparator
)
;
}

Formats the value as a decimal number.

Property [[decimalSeparator]] will be used to represent the decimal point. The
value is rounded automatically to the defined decimal digits.

@param mixed $value the value to be formatted.
@param int $decimals the number of digits after the decimal point.
If not given, the number of digits depends in the input value and is determined based on
`NumberFormatter::MIN_FRACTION_DIGITS` and `NumberFormatter::MAX_FRACTION_DIGITS`, which can be configured
using [[$numberFormatterOptions]].
If the [PHP intl extension](http://php.net/manual/en/book.intl.php) is not available, the default value is `2`.
If you want consistent behavior between environments where intl is available and not, you should explicitly
specify a value here.
@param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
@param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
@return string the formatted result.
@throws InvalidArgumentException if the input value is not numeric or the formatting failed.
@see decimalSeparator
@see thousandSeparator


public function asShortSize($value, $decimals = null, $options = [], $textOptions = [])
    {
        if ($value === null) {
            return $this->nullDisplay;
        }

        list($params, $position) = $this->formatNumber($value, $decimals, 4, $this->sizeFormatBase, $options, $textOptions);

        if ($this->sizeFormatBase == 1024) {
            switch ($position) {
                case 0:
                    return Reaction::t('rct', '{nFormatted} B', $params, $this->locale);
                case 1:
                    return Reaction::t('rct', '{nFormatted} KiB', $params, $this->locale);
                case 2:
                    return Reaction::t('rct', '{nFormatted} MiB', $params, $this->locale);
                case 3:
                    return Reaction::t('rct', '{nFormatted} GiB', $params, $this->locale);
                case 4:
                    return Reaction::t('rct', '{nFormatted} TiB', $params, $this->locale);
                default:
                    return Reaction::t('rct', '{nFormatted} PiB', $params, $this->locale);
            }
        } else {
            switch ($position) {
                case 0:
                    return Reaction::t('rct', '{nFormatted} B', $params, $this->locale);
                case 1:
                    return Reaction::t('rct', '{nFormatted} KB', $params, $this->locale);
                case 2:
                    return Reaction::t('rct', '{nFormatted} MB', $params, $this->locale);
                case 3:
                    return Reaction::t('rct', '{nFormatted} GB', $params, $this->locale);
                case 4:
                    return Reaction::t('rct', '{nFormatted} TB', $params, $this->locale);
                default:
                    return Reaction::t('rct', '{nFormatted} PB', $params, $this->locale);
            }
        }
    }

public
function
asShortSize
(
$
value
,
$
decimals
=
,
$
options
=
[
]
,
$
textOptions
=
[
]
)
{
if
(
$
value
===
)
{
return
$
this
->
nullDisplay
;
}
list
(
$
params
,
$
position
)
=
$
this
->
formatNumber
(
$
value
,
$
decimals
,
4
,
$
this
->
sizeFormatBase
,
$
options
,
$
textOptions
)
;
if
(
$
this
->
sizeFormatBase
==
1024
)
{
switch
(
$
position
)
{
case
0
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} B'
,
$
params
,
$
this
->
locale
)
;
case
1
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} KiB'
,
$
params
,
$
this
->
locale
)
;
case
2
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} MiB'
,
$
params
,
$
this
->
locale
)
;
case
3
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} GiB'
,
$
params
,
$
this
->
locale
)
;
case
4
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} TiB'
,
$
params
,
$
this
->
locale
)
;
default
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} PiB'
,
$
params
,
$
this
->
locale
)
;
}
}
else
{
switch
(
$
position
)
{
case
0
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} B'
,
$
params
,
$
this
->
locale
)
;
case
1
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} KB'
,
$
params
,
$
this
->
locale
)
;
case
2
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} MB'
,
$
params
,
$
this
->
locale
)
;
case
3
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} GB'
,
$
params
,
$
this
->
locale
)
;
case
4
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} TB'
,
$
params
,
$
this
->
locale
)
;
default
:
return
Reaction
::
t
(
'rct'
,
'{nFormatted} PB'
,
$
params
,
$
this
->
locale
)
;
}
}
}

Formats the value in bytes as a size in human readable form for example `12 KB`.

This is the short form of [[asSize]].

If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix) (e.g. kibibyte/KiB, mebibyte/MiB, ...)
are used in the formatting result.

@param string|int|float $value value in bytes to be formatted.
@param int $decimals the number of digits after the decimal point.
@param array $options optional configuration for the number formatter. This parameter will be merged with [[numberFormatterOptions]].
@param array $textOptions optional configuration for the number formatter. This parameter will be merged with [[numberFormatterTextOptions]].
@return string the formatted result.
@throws InvalidArgumentException if the input value is not numeric or the formatting failed.
@see sizeFormatBase
@see asSize

Formats the value in bytes as a size in human readable form for example 12 KB .


public function actionCreate() {
        /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */
        $model = \Yii::createObject([
                    'class' => $this->modelClass,
                    'scenario' => 'create',
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('create', [
                    'model' => $model,
        ]);
    }

Shows create form.
@return string|Response
@throws \yii\base\InvalidConfigException


public function actionUpdate($name) {
        /** @var \jarrus90\User\models\Role|\jarrus90\User\models\Permission $model */
        $item = $this->getItem($name);
        $model = \Yii::createObject([
                    'class' => $this->modelClass,
                    'scenario' => 'update',
                    'item' => $item,
        ]);

        $this->performAjaxValidation($model);

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('update', [
                    'model' => $model,
        ]);
    }

Shows update form.
@param  string $name
@return string|Response
@throws NotFoundHttpException
@throws \yii\base\InvalidConfigException


public function exists(): bool
    {
        // convert namespace into path
        $class = str_replace('\\', '/', $this->classname);

        // append .php?
        if (strpos($class, '.php') === false) {
            $class .= '.php';
        }

        $class = $this->replaceDirectorySeperator($class);

        if (!empty($this->basedir)) {
            $class = $this->basedir .= DIRECTORY_SEPARATOR;
        }

        return file_exists($class);
    }

public
function
exists
(
)
:
bool
{
// convert namespace into path
$
class
=
str_replace
(
'\\'
,
'/'
,
$
this
->
classname
)
;
// append .php?
if
(
strpos
(
$
class
,
'.php'
)
===
false
)
{
$
class
.=
'.php'
;
}
$
class
=
$
this
->
replaceDirectorySeperator
(
$
class
)
;
if
(
!
empty
(
$
this
->
basedir
)
)
{
$
class
=
$
this
->
basedir
.=
DIRECTORY_SEPARATOR
;
}
return
file_exists
(
$
class
)
;
}

Checks for existing class file of a given classname

Takes care of namespaces.

@return boolean


public function fetchObject($query, array $values, $instance, $fetchMode = PDO::FETCH_INTO) {
		$obj = null;
		try {
			$statement = $this->pdo->prepare($query);
			$statement->setFetchMode($fetchMode, $instance);
			if ($statement->execute($values)) {
				$obj = $statement->fetch($fetchMode);
				if (!$obj) return null;
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $obj;
	}

public function fetchObject ( $ query , array $ values , $ instance , $ fetchMode = PDO :: FETCH_INTO ) { $ obj = null ; try { $ statement = $ this -> pdo -> prepare ( $ query ) ; $ statement -> setFetchMode ( $ fetchMode , $ instance ) ; if ( $ statement -> execute ( $ values ) ) { $ obj = $ statement -> fetch ( $ fetchMode ) ; if ( ! $ obj ) return null ; } else { $ errorInfo = $ statement -> errorInfo ( ) ; error_log ( $ errorInfo [ 2 ] ) ; } } catch ( PDOException $ e ) { error_log ( $ e -> getMessage ( ) ) ; } return $ obj ; }

Set corresponding fields in an object from result set.

@param string $query
@param array $values
@param object $instance - the initialized object that the fields should be set in
@param array $callback [default=array()]
@return object

Set corresponding fields in an object from result set .


public function fetchColumn($query, array $values) {
		$col = null;
		try {
			$statement = $this->pdo->prepare($query);
			if ($statement->execute($values)) {
				$col = $statement->fetchColumn();
				if (!$col) return null;
			} else {
				$errorInfo = $statement->errorInfo();
				error_log($errorInfo[2]);
			}
		} catch (PDOException $e) {
			error_log($e->getMessage());
		}
		return $col;
	}

public function fetchColumn ( $ query , array $ values ) { $ col = null ; try { $ statement = $ this -> pdo -> prepare ( $ query ) ; if ( $ statement -> execute ( $ values ) ) { $ col = $ statement -> fetchColumn ( ) ; if ( ! $ col ) return null ; } else { $ errorInfo = $ statement -> errorInfo ( ) ; error_log ( $ errorInfo [ 2 ] ) ; } } catch ( PDOException $ e ) { error_log ( $ e -> getMessage ( ) ) ; } return $ col ; }

Retrieve first column in results set

@param string $query
@param array $values
@return string


protected function scopeExcludeTrashed(QueryBuilder $query) {
        $time = new DateTime();

        return $query
            ->andWhere('o.deletedAt is NULL')
            ->orWhere('o.deletedAt > :currentTimestamp')
            ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s'));
    }

protected
function
scopeExcludeTrashed
(
QueryBuilder
$
query
)
{
$
time
=
new
DateTime
(
)
;
return
$
query
->
andWhere
(
'o.deletedAt is NULL'
)
->
orWhere
(
'o.deletedAt > :currentTimestamp'
)
->
setParameter
(
'currentTimestamp'
,
$
time
->
format
(
'Y-m-d H:i:s'
)
)
;
}

Filters out trashed entities.

@param QueryBuilder $query
@return QueryBuilder


protected function scopeOnlyTrashed(QueryBuilder $query) {
        $time = new DateTime();

        return $query
            ->andWhere('o.deletedAt is not NULL')
            ->andWhere(':currentTimestamp > o.deletedAt')
            ->setParameter('currentTimestamp', $time->format('Y-m-d H:i:s'));
    }

protected
function
scopeOnlyTrashed
(
QueryBuilder
$
query
)
{
$
time
=
new
DateTime
(
)
;
return
$
query
->
andWhere
(
'o.deletedAt is not NULL'
)
->
andWhere
(
':currentTimestamp > o.deletedAt'
)
->
setParameter
(
'currentTimestamp'
,
$
time
->
format
(
'Y-m-d H:i:s'
)
)
;
}

Filters everything except trashed entities.

@param QueryBuilder $query
@return QueryBuilder

Filters everything except trashed entities .


public function runConsoleRequest() {
        $promise = resolve(true);
        //Delayed stop
        $loopStop = function() {
            $this->loop->addTimer(0.5, function() {
                $this->loop->stop();
            });
        };
        $promise->then(
            function() {
                return $this->processRequest($this->createRequest());
            }
        )->then(
            function($response = null) {
                if ($response instanceof Response) {
                    $body = $response->getBody();
                    if (is_object($body) && method_exists($body, '__toString')) {
                        $body = (string)$body;
                    }
                    return $body;
                }
                return $response;
            }
        )->done(function($result = null) use ($loopStop) {
            if (is_string($result)) {
                $this->logger->logRaw($result);
            }
            $loopStop();
        }, function($error) use ($loopStop) {
            \Reaction::error($error);
            $loopStop();
        });
    }

public
function
runConsoleRequest
(
)
{
$
promise
=
resolve
(
true
)
;
//Delayed stop
$
loopStop
=
function
(
)
{
$
this
->
loop
->
addTimer
(
0.5
,
function
(
)
{
$
this
->
loop
->
stop
(
)
;
}
)
;
}
;
$
promise
->
then
(
function
(
)
{
return
$
this
->
processRequest
(
$
this
->
createRequest
(
)
)
;
}
)
->
then
(
function
(
$
response
=
)
{
if
(
$
response
instanceof
Response
)
{
$
body
=
$
response
->
getBody
(
)
;
if
(
is_object
(
$
body
)
&&
method_exists
(
$
body
,
'__toString'
)
)
{
$
body
=
(
string
)
$
body
;
}
return
$
body
;
}
return
$
response
;
}
)
->
done
(
function
(
$
result
=
)
use
(
$
loopStop
)
{
if
(
is_string
(
$
result
)
)
{
$
this
->
logger
->
logRaw
(
$
result
)
;
}
$
loopStop
(
)
;
}
,
function
(
$
error
)
use
(
$
loopStop
)
{
\
Reaction
::
error
(
$
error
)
;
$
loopStop
(
)
;
}
)
;
}


public static function getUnset (&$arr, $key, $default = null)
    {
        $value                  = isset($arr[$key]) ? $arr[$key] : $default;
        if (isset($arr[$key]))
            unset($arr[$key]);
        return $value;
    }

public static function getUnset ( & $ arr , $ key , $ default = null ) { $ value = isset ( $ arr [ $ key ] ) ? $ arr [ $ key ] : $ default ; if ( isset ( $ arr [ $ key ] ) ) unset ( $ arr [ $ key ] ) ; return $ value ; }

Get the value and if it's set, unset it
@param       array       $arr
@param       string      $key
@param       null        $default
@return      null


public function getHeader($name)
    {
        $headers = [];
        $name = strtolower((string)$name);

        foreach ($this->headers as $k => $v) {
            if ($name == strtolower($k)) {
                $headers = array_merge($headers, $v);
            }
        }

        return array_unique($headers);
    }

public function getHeader ( $ name ) { $ headers = [ ] ; $ name = strtolower ( ( string ) $ name ) ; foreach ( $ this -> headers as $ k => $ v ) { if ( $ name == strtolower ( $ k ) ) { $ headers = array_merge ( $ headers , $ v ) ; } } return array_unique ( $ headers ) ; }

Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given
case-insensitive header name.
If the header does not appear in the message, this method MUST return an
empty array.

@param string $name Case-insensitive header field name.
@return string[] An array of string values as provided for the given
header. If the header does not appear in the message, this method MUST
return an empty array.

Retrieves a message header value by the given case - insensitive name . This method returns an array of all the header values of the given case - insensitive header name . If the header does not appear in the message this method MUST return an empty array .


public function withoutHeader($name)
    {
        $message = clone $this;

        $name = strtolower((string)$name);
        foreach (array_keys($message->headers) as $k) {
            if ($name == strtolower($k)) {
                unset($message->headers[$k]);
            }
        }

        return $message;
    }

public function withoutHeader ( $ name ) { $ message = clone $ this ; $ name = strtolower ( ( string ) $ name ) ; foreach ( array_keys ( $ message -> headers ) as $ k ) { if ( $ name == strtolower ( $ k ) ) { unset ( $ message -> headers [ $ k ] ) ; } } return $ message ; }

Return an instance without the specified header.
Header resolution MUST be done without case-sensitivity.
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that removes
the named header.

@param string $name Case-insensitive header field name to remove.
@return MessageInterface

Return an instance without the specified header . Header resolution MUST be done without case - sensitivity . This method MUST be implemented in such a way as to retain the immutability of the message and MUST return an instance that removes the named header .


public function withBody(StreamInterface $body)
    {
        if (false) {
            // Body is forced to a StreamInterface in parameters.
            // How can it be invalid ?
            throw new InvalidArgumentException('Body is not valid.');
        }
        $message = clone $this;
        $message->stream = $body;

        return $message;
    }

Return an instance with the specified message body.
The body MUST be a StreamInterface object.
This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return a new instance that has the
new body stream.

@param StreamInterface $body Body.
@return MessageInterface
@throws \InvalidArgumentException When the body is not valid.

Return an instance with the specified message body . The body MUST be a StreamInterface object . This method MUST be implemented in such a way as to retain the immutability of the message and MUST return a new instance that has the new body stream .


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

        return $icon;
    }

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

Get icon type.

@param  bool $isNegativeAmount
@return string


public static function getAllTypes()
    {
        $list = array(
            self::CB,
            self::VIR,
            self::PRE,
            self::PPL,
            self::CHQ,
        );

        $types = array();
        foreach ($list as $value) {
            $types[$value] = new self($value);
        }

        return $types;
    }

public static function getAllTypes ( ) { $ list = array ( self :: CB , self :: VIR , self :: PRE , self :: PPL , self :: CHQ , ) ; $ types = array ( ) ; foreach ( $ list as $ value ) { $ types [ $ value ] = new self ( $ value ) ; } return $ types ; }


public function bind(string $alias, string $template, array $params = []): void {
    $this->bindCallback($alias, function(Generator $generator) use($template, $params): void {
      $compiled = $generator->generate($template, $params);
      $generator->includeFile($compiled);
    });
  }

public function bind ( string $ alias , string $ template , array $ params = [ ] ) : void { $ this -> bindCallback ( $ alias , function ( Generator $ generator ) use ( $ template , $ params ) : void { $ compiled = $ generator -> generate ( $ template , $ params ) ; $ generator -> includeFile ( $ compiled ) ; } ) ; }

Bind a class to a template with specified parameters

@param  string   $alias
@param  string   $template
@param  mixed[]  $params    (optional)

@return  void


protected function renderException($exception)
    {
        if ($exception instanceof UnknownCommandException) {
            // display message and suggest alternatives in case of unknown command
            $message = $this->formatMessage($exception->getName() . ': ') . $exception->command;
            $alternatives = $exception->getSuggestedAlternatives();
            if (count($alternatives) === 1) {
                $message .= "\n\nDid you mean \"" . reset($alternatives) . '"?';
            } elseif (count($alternatives) > 1) {
                $message .= "\n\nDid you mean one of these?\n    - " . implode("\n    - ", $alternatives);
            }
        } elseif ($exception instanceof Exception && ($exception instanceof UserException || !Reaction::isDebug())) {
            $message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
        } elseif (Reaction::isDebug()) {
            if ($exception instanceof Exception) {
                $message = $this->formatMessage("Exception ({$exception->getName()})");
            } elseif ($exception instanceof ErrorException) {
                $message = $this->formatMessage($exception->getName());
            } else {
                $message = $this->formatMessage('Exception');
            }
            $message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
                . ' with message ' . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
                . "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
                . ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n";
            $trace = static::getExceptionTrace($exception, true);
            //$trace = $exception->getTraceAsString();
            $message .= "\n" . $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $trace;
        } else {
            $message = $this->formatMessage('Error: ') . $exception->getMessage();
        }

        if (Reaction::isConsoleApp()) {
            Console::stderr($message . "\n");
        } else {
            echo $message . "\n";
        }
    }

"\n\nDid you mean one of these?\n    - "

Renders an exception using ansi format for console output.
@param \Exception $exception the exception to be rendered.

Renders an exception using ansi format for console output .


protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
    {
        $stream = Reaction::isConsoleApp() ? \STDERR : \STDOUT;
        // try controller first to allow check for --color switch
        if (Reaction::isConsoleApp() && Console::streamSupportsAnsiColors($stream)) {
            $message = Console::ansiFormat($message, $format);
        }

        return $message;
    }

Colorizes a message for console output.
@param string $message the message to colorize.
@param array $format the message format.
@return string the colorized message.
@see Console::ansiFormat() for details on how to specify the message format.

Colorizes a message for console output .


public function getForHeader($validationKey = null) {
        if ($this->expire != 1 && isset($validationKey)) {
            $value = \Reaction::$app->security->hashData(serialize([$this->name, $this->value]), $validationKey);
        }
        $value = isset($value) && $value !== "" ? urlencode($value) : '';
        $name = urlencode($this->name);
        $data = [
            'Secure' => $this->secure ? null : '',
            'HttpOnly' => $this->httpOnly ? null : '',
            'Domain' => isset($this->domain) ? $this->domain : '',
            'Path' => isset($this->path) ? $this->path : '',
            'Expires' => !empty($this->expire) ? gmdate('D, d M Y H:i:s T', $this->expire) : '',
        ];
        foreach ($data as $key => $val) {
            if ($val === '') {
                unset($data[$key]);
            }
        }
        $data = ArrayHelper::merge([$name => $value], $data);

        return $this->convertArrayToHeaderString($data);
    }

public
function
getForHeader
(
$
validationKey
=
)
{
if
(
$
this
->
expire
!=
1
&&
isset
(
$
validationKey
)
)
{
$
value
=
\
Reaction
::
$
app
->
security
->
hashData
(
serialize
(
[
$
this
->
name
,
$
this
->
value
]
)
,
$
validationKey
)
;
}
$
value
=
isset
(
$
value
)
&&
$
value
!==
""
urlencode
(
$
value
)
:
''
;
$
name
=
urlencode
(
$
this
->
name
)
;
$
data
=
[
'Secure'
=>
$
this
->
secure
:
''
,
'HttpOnly'
=>
$
this
->
httpOnly
:
''
,
'Domain'
=>
isset
(
$
this
->
domain
)
$
this
->
domain
:
''
,
'Path'
=>
isset
(
$
this
->
path
)
$
this
->
path
:
''
,
'Expires'
=>
!
empty
(
$
this
->
expire
)
gmdate
(
'D, d M Y H:i:s T'
,
$
this
->
expire
)
:
''
,
]
;
foreach
(
$
data
as
$
key
=>
$
val
)
{
if
(
$
val
===
''
)
{
unset
(
$
data
[
$
key
]
)
;
}
}
$
data
=
ArrayHelper
::
merge
(
[
$
name
=>
$
value
]
,
$
data
)
;
return
$
this
->
convertArrayToHeaderString
(
$
data
)
;
}

Get cookie for Set-Cookie header
@param string $validationKey Cookie validation key
@return string
@throws \Reaction\Exceptions\InvalidConfigException