public function validate_config($config)
    {
        $message = '';

        while ($message === '') {
            if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.content_dir'])) {
                $message = 'Content directory does not exist';
                break;
            }

            if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.plugins_dir'])) {
                $message = 'Plugins directory does not exist';
                break;
            }

            if (!is_dir($this->app['ROOT_DIR'] . $config['sonic.templates_dir'])) {
                $message = 'Templates directory does not exist';
                break;
            }

            if (
                !is_file("{$config['sonic.templates_dir']}/{$config['sonic.default_template']}")
            ) {
                $message = 'No default template exists';
            break;
            }

            if ($config['sonic.environment'] !== 'dev') {
                preg_match('#^(https?://)?([\da-z\.-]+)\.([a-z\.]{2,6})([/\w \.-]*)*/+$#', $config['site.site_root']) === 0
                    ? $message = 'Site root is invalid. Should be like http://www.example.com/'
                    : $message = '';
            }
            break;
        }

        if ($message === '') {
            return TRUE;
        }
        else {
            throw new \InvalidArgumentException($message);
        }

    }

Validates a configuration array

@param  array   $config
@return boolean
@throws InvalidArgumentException If a setting is invalid
@static


public static function get_excerpt($text, $br_limit = 3)
    {
        if (substr_count($text, PHP_EOL) > $br_limit) {
            $excerpt = explode(PHP_EOL, $text, ++$br_limit);
            array_pop($excerpt);
            return implode(' ', $excerpt);
        }
        return $text;
    }

public
static
function
get_excerpt
(
$
text
,
$
br_limit
=
3
)
{
if
(
substr_count
(
$
text
,
PHP_EOL
)
>
$
br_limit
)
{
$
excerpt
=
explode
(
PHP_EOL
,
$
text
,
++
$
br_limit
)
;
array_pop
(
$
excerpt
)
;
return
implode
(
' '
,
$
excerpt
)
;
}
return
$
text
;
}

Returns an excerpt of a string by breaking at new lines

@param  array  $text
@param  int    $br_limit
@return string


public static function handle_errors($err_no, $err_str = '', $err_file = '', $err_line = '')
    {
        if (!($err_no & error_reporting())) {
            return;
        }
        throw new \ErrorException($err_str, $err_no, 0, $err_file, $err_line);
    }

public static function handle_errors ( $ err_no , $ err_str = '' , $ err_file = '' , $ err_line = '' ) { if ( ! ( $ err_no & error_reporting ( ) ) ) { return ; } throw new \ ErrorException ( $ err_str , $ err_no , 0 , $ err_file , $ err_line ) ; }

Convert errors into ErrorException objects

@param  int            $err_no
@param  string         $err_str
@param  string         $err_file
@param  int            $err_line
@return bool
@throws \ErrorException


private function dot_extensions()
    {
        $extensions = $this->app['settings']['sonic.content_ext'];

        foreach ($extensions as $extension) {
            $dotted_extensions[] = '.' . $extension;
        }

        return $dotted_extensions;
    }

private function dot_extensions ( ) { $ extensions = $ this -> app [ 'settings' ] [ 'sonic.content_ext' ] ; foreach ( $ extensions as $ extension ) { $ dotted_extensions [ ] = '.' . $ extension ; } return $ dotted_extensions ; }

Adds a '.' to each extension given

@return array


private function validateWidgetId(?string $widgetId)
    {
        if (!isset($widgetId) && current_user_can('administrator')) {
            throw new WidgetMissingId('Missing request "widgetId" key!');
        }
        $this->arrPayload['widgetId'] = $widgetId;
    }

private
function
validateWidgetId
(
string
$
widgetId
)
{
if
(
!
isset
(
$
widgetId
)
&&
current_user_can
(
'administrator'
)
)
{
throw
new
WidgetMissingId
(
'Missing request "widgetId" key!'
)
;
}
$
this
->
arrPayload
[
'widgetId'
]
=
$
widgetId
;
}

Check for widget id presence
@param string $widgetId
@return null
@throws WidgetMissingId


public function setCxenseUserId()
    {
        if (!isset($_COOKIE['cX_P'])) {
            $this->cxenseUserId = '';
            return;
        }

        $this->cxenseUserId = $_COOKIE['cX_P'];
        $this->arrPayload['user']= ['ids' => ['usi' => $this->cxenseUserId]];
    }

public function setCxenseUserId ( ) { if ( ! isset ( $ _COOKIE [ 'cX_P' ] ) ) { $ this -> cxenseUserId = '' ; return ; } $ this -> cxenseUserId = $ _COOKIE [ 'cX_P' ] ; $ this -> arrPayload [ 'user' ] = [ 'ids' => [ 'usi' => $ this -> cxenseUserId ] ] ; }

Set cxenseUserId from Cookie. Might not work on WILLOW FRONTEND

Set cxenseUserId from Cookie . Might not work on WILLOW FRONTEND


public function get()
    {
        $result = $this->getDocuments();
        $objDocuments = isset($result->items) ? $result->items : [];
        return [
            'totalCount' => count($objDocuments),
            'matches' => $this->parseDocuments($objDocuments)
        ];
    }

public function get ( ) { $ result = $ this -> getDocuments ( ) ; $ objDocuments = isset ( $ result -> items ) ? $ result -> items : [ ] ; return [ 'totalCount' => count ( $ objDocuments ) , 'matches' => $ this -> parseDocuments ( $ objDocuments ) ] ; }

Return An array with total documents and matches
@return array


public function append($string, $delimiter = '')
    {
        if ($this->isValidStringAndDelimiter($string, $delimiter))
        {
            return new static($this->string.$this->retrieveValue($delimiter).$this->retrieveValue($string));
        }

        return $this;
    }

public function append ( $ string , $ delimiter = '' ) { if ( $ this -> isValidStringAndDelimiter ( $ string , $ delimiter ) ) { return new static ( $ this -> string . $ this -> retrieveValue ( $ delimiter ) . $ this -> retrieveValue ( $ string ) ) ; } return $ this ; }

Return String with appended delimiter and content.

@param mixed $string
@param mixed $delimiter
@return $this|static

Return String with appended delimiter and content .


public function prepend($string, $delimiter = '')
    {
        if ($this->isValidStringAndDelimiter($string, $delimiter))
        {
            return new static($this->retrieveValue($string).$this->retrieveValue($delimiter).$this->string);
        }

        return $this;
    }

public function prepend ( $ string , $ delimiter = '' ) { if ( $ this -> isValidStringAndDelimiter ( $ string , $ delimiter ) ) { return new static ( $ this -> retrieveValue ( $ string ) . $ this -> retrieveValue ( $ delimiter ) . $ this -> string ) ; } return $ this ; }

Return String with prepended content and delimiter.

@param mixed $string
@param mixed $delimiter
@return $this|static

Return String with prepended content and delimiter .


public function is($pattern)
    {
        return (bool) Str::matches($this->retrieveValue($pattern), $this->string);
    }

public function is ( $ pattern ) { return ( bool ) Str :: matches ( $ this -> retrieveValue ( $ pattern ) , $ this -> string ) ; }

Return true if String matches the supplied pattern, false otherwise.

@param string|StringContract $pattern
@return bool

Return true if String matches the supplied pattern false otherwise .


public function limitWords($limit, $end = '...')
    {
        return new static(Str::words($this->string, $this->getIntegerable($limit), $this->retrieveValue($end)));
    }

public function limitWords ( $ limit , $ end = '...' ) { return new static ( Str :: words ( $ this -> string , $ this -> getIntegerable ( $ limit ) , $ this -> retrieveValue ( $ end ) ) ) ; }

Limit the number of words in a String.

@param int|IntegerContract $limit
@param string|StringContract $end
@return static


public function uuid()
    {
        return new static(sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
            mt_rand(0, 0x0fff) | 0x4000,
            mt_rand(0, 0x3fff) | 0x8000,
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        ));
    }

Generates random Unique User Identifier

@return static


public function join($glue, $array)
    {
        if ($this->isArrayable($array))
        {
            $this->string = implode($this->retrieveValue($glue), $this->getArrayable($array));

            return $this;
        }

        throw new InvalidArgumentException('Argument 2 should be array, Container or instance of Arrayable');
    }

Join arrayable elements with a String

@param string|StringContract $glue
@param mixed $array
@return $this
@throws InvalidArgumentException


public function toEntities($flags = ENT_QUOTES, $encoding = 'UTF-8')
    {
        return new static(htmlentities($this->string, $flags, $this->retrieveValue($encoding)));
    }

public function toEntities ( $ flags = ENT_QUOTES , $ encoding = 'UTF-8' ) { return new static ( htmlentities ( $ this -> string , $ flags , $ this -> retrieveValue ( $ encoding ) ) ) ; }

Convert all applicable characters to HTML entities.

@param int $flags
@param string|StringContract $encoding
@return static

Convert all applicable characters to HTML entities .


public function cut($offset, $length = null, $encoding = 'UTF-8')
    {
        return new static(
            mb_substr(
                $this->string,
                $this->getIntegerable($offset),
                $this->getIntegerable($length),
                $this->retrieveValue($encoding)
            )
        );
    }

public function cut ( $ offset , $ length = null , $ encoding = 'UTF-8' ) { return new static ( mb_substr ( $ this -> string , $ this -> getIntegerable ( $ offset ) , $ this -> getIntegerable ( $ length ) , $ this -> retrieveValue ( $ encoding ) ) ) ; }

Get part of String

@param int|IntegerContract $offset
@param int|IntegerContract|null $length
@param string|StringContract $encoding
@return static


public function limit($limit = 100, $end = '...')
    {
        return new static(
            Str::limit($this->string, $this->getIntegerable($limit), $this->retrieveValue($end))
        );
    }

public function limit ( $ limit = 100 , $ end = '...' ) { return new static ( Str :: limit ( $ this -> string , $ this -> getIntegerable ( $ limit ) , $ this -> retrieveValue ( $ end ) ) ) ; }

Limit the number of characters in a String.

@param int|IntegerContract $limit
@param string|StringContract $end
@return static

Limit the number of characters in a String .


public function limitSafe($limit = 100, $end = '...')
    {
        return new static(
            StaticStringy::safeTruncate($this->string, $this->getIntegerable($limit)).$this->retrieveValue($end)
        );
    }

public function limitSafe ( $ limit = 100 , $ end = '...' ) { return new static ( StaticStringy :: safeTruncate ( $ this -> string , $ this -> getIntegerable ( $ limit ) ) . $ this -> retrieveValue ( $ end ) ) ; }

Truncates the string to a given length, while ensuring that it does not
split words. If word will be in the middle of limit, minus one word will be returned.

@param int|IntegerContract $limit
@param string|StringContract $end
@return static

Truncates the string to a given length while ensuring that it does not split words . If word will be in the middle of limit minus one word will be returned .


public function toVars()
    {
        $vars = [];

        return mb_parse_str($this->string, $vars) && ! is_null($vars) ? new Container($vars) : new Container;
    }

public function toVars ( ) { $ vars = [ ] ; return mb_parse_str ( $ this -> string , $ vars ) && ! is_null ( $ vars ) ? new Container ( $ vars ) : new Container ; }

Parse GET data.

@return \im\Primitive\Container\Container


public function encrypt($key, $expires)
    {
        $payload = [
            'exp' => $this->getIntegerable($expires),
            'string' => $this->string
        ];

        return JWT::encode($payload, $this->getStringable($key));
    }

public function encrypt ( $ key , $ expires ) { $ payload = [ 'exp' => $ this -> getIntegerable ( $ expires ) , 'string' => $ this -> string ] ; return JWT :: encode ( $ payload , $ this -> getStringable ( $ key ) ) ; }

Encrypt and sign a String into a JWT token.

@param string|StringContract $key to encrypt with
@param int|IntegerContract $expires timestamp
@return static

Encrypt and sign a String into a JWT token .


public function fromEncrypted($encrypted, $key)
    {
        $encrypted = $this->retrieveValue($encrypted);

        $key = $this->retrieveValue($key);

        if ($this->isEncryptedString($encrypted, $key))
        {
            $data = JWT::decode($encrypted, $key);

            return $this->initialize($data->string);
        }

        throw new BadMethodCallException('Expected encrypted String, got: ' . $encrypted);
    }

public
function
fromEncrypted
(
$
encrypted
,
$
key
)
{
$
encrypted
=
$
this
->
retrieveValue
(
$
encrypted
)
;
$
key
=
$
this
->
retrieveValue
(
$
key
)
;
if
(
$
this
->
isEncryptedString
(
$
encrypted
,
$
key
)
)
{
$
data
=
JWT
::
decode
(
$
encrypted
,
$
key
)
;
return
$
this
->
initialize
(
$
data
->
string
)
;
}
throw
new
BadMethodCallException
(
'Expected encrypted String, got: '
.
$
encrypted
)
;
}

Construct from proper encrypted String with JWT.

@param string|StringContract $encrypted
@param string|StringContract $key
@return $this

Construct from proper encrypted String with JWT .


public function toContainer()
    {
        $value = $this->value();

        if ( ! $this->isFile() || ! $this->isJson() || ! $this->isSerialized())
        {
            $value = [$value];
        }

        return new Container($value);
    }

public function toContainer ( ) { $ value = $ this -> value ( ) ; if ( ! $ this -> isFile ( ) || ! $ this -> isJson ( ) || ! $ this -> isSerialized ( ) ) { $ value = [ $ value ] ; } return new Container ( $ value ) ; }

Convert String Type to Container Type.
If String is proper json, serialized or file path with json or serialized
than it will grab contents decode it and construct Container from it.

@return \im\Primitive\Container\Container

Convert String Type to Container Type . If String is proper json serialized or file path with json or serialized than it will grab contents decode it and construct Container from it .


static function generateParserFromGrammar(
        string $grammarFilePath,
        string $parserName="MyParser",
        string $namespace="",
        Output $output=null,
        string $pathToHeaderComment="")
    {
        $parser = new MetaGrammarParser();

        $ast = !empty($grammarFilePath) ?
            $parser->parseFile($grammarFilePath) :
            $parser->parseStdin();

        if ($ast !== false) {

            $generator = new CodeGenerator($parserName, $namespace);
            $generator->setHeaderCommentFile($pathToHeaderComment);
            $generator->generate($ast, $output);

            return [true, ""];

        } else {

            return [false, $parser->error()];

        }
    }

static function generateParserFromGrammar ( string $ grammarFilePath , string $ parserName = "MyParser" , string $ namespace = "" , Output $ output = null , string $ pathToHeaderComment = "" ) { $ parser = new MetaGrammarParser ( ) ; $ ast = ! empty ( $ grammarFilePath ) ? $ parser -> parseFile ( $ grammarFilePath ) : $ parser -> parseStdin ( ) ; if ( $ ast !== false ) { $ generator = new CodeGenerator ( $ parserName , $ namespace ) ; $ generator -> setHeaderCommentFile ( $ pathToHeaderComment ) ; $ generator -> generate ( $ ast , $ output ) ; return [ true , "" ] ; } else { return [ false , $ parser -> error ( ) ] ; } }

Generate a parser from a grammar definition

@param string $grammarFilePath path of grammar file
@param string $parserName name of parser class
@param string $namespace namespace of parser class
@param Output $output output to be written to
@param string $pathToHeaderComment path to file that contains header comment
@return mixed[] [true, ""] in case of success, [false, <error_message>] in error cases


public function set_settings()
    {
        if ($strPrefix = WpCxense::instance()->settings->getOrganisationPrefix()) {
            $this->arrFields['organisation'] = array_map(function ($strValue) use ($strPrefix) {
                return $strPrefix . '-' . $strValue;
            }, $this->arrFields['organisation']);
        }
        return $this;
    }

public function set_settings ( ) { if ( $ strPrefix = WpCxense :: instance ( ) -> settings -> getOrganisationPrefix ( ) ) { $ this -> arrFields [ 'organisation' ] = array_map ( function ( $ strValue ) use ( $ strPrefix ) { return $ strPrefix . '-' . $ strValue ; } , $ this -> arrFields [ 'organisation' ] ) ; } return $ this ; }

Set settings object

@return DocumentSearch


public function get_documents()
    {
        $this->validate_query_key();

        $objDocuments = $this
            ->set_per_page()
            ->set_page()
            ->set_facets()
            ->set_filter()
            ->set_exclude_filter()
            ->set_sorting()
            ->set_spellcheck()
            ->set_highlights()
            ->set_result_fields()
            ->get();

        $objDocuments->matches = $this->parse_documents($objDocuments->matches);
        return $objDocuments;
    }

public function get_documents ( ) { $ this -> validate_query_key ( ) ; $ objDocuments = $ this -> set_per_page ( ) -> set_page ( ) -> set_facets ( ) -> set_filter ( ) -> set_exclude_filter ( ) -> set_sorting ( ) -> set_spellcheck ( ) -> set_highlights ( ) -> set_result_fields ( ) -> get ( ) ; $ objDocuments -> matches = $ this -> parse_documents ( $ objDocuments -> matches ) ; return $ objDocuments ; }

Get documents from search result

@return \stdClass


private function set_per_page($intCount = 10)
    {
        $this->arrPayload['count'] = $intCount;

        if (isset($this->arrSearch['count'])) {
            $this->arrPayload['count'] = $this->arrSearch['count'];
        }

        return $this;
    }

private function set_per_page ( $ intCount = 10 ) { $ this -> arrPayload [ 'count' ] = $ intCount ; if ( isset ( $ this -> arrSearch [ 'count' ] ) ) { $ this -> arrPayload [ 'count' ] = $ this -> arrSearch [ 'count' ] ; } return $ this ; }

Set page limit to the search array

@param integer $intCount Total items per page
@return $this


private function set_page($intPage = 1)
    {
        if (!isset($this->arrPayload['count'])) {
            throw new DocumentSearchMissingCount('\DocumentSearch::setPerPage() is required before \DocumentSearch::setPage()');
        }

        // get the page
        if (isset($this->arrSearch['page'])) {
            $intPage = $this->arrSearch['page'];
        }

        // set the starting point
        $this->arrPayload['start'] = $this->arrPayload['count'] * ($intPage - 1);

        return $this;
    }

Set page number for calculating the correct starting offset

@param integer $intPage Page number
@return $this
@throws DocumentSearchMissingCount


public function getNumberable($value, $default = null)
    {
        switch(true)
        {
            case is_int($value):
            case is_float($value):
                return $value;
            case is_numeric($value) && strpos($value, '.'):
                return (float) $value;
            case is_numeric($value):
            case is_bool($value):
                return (int) $value;
            case $value instanceof IntegerContract:
            case $value instanceof FloatContract:
                return $value->value();
            case $value instanceof BooleanContract:
                return $value->toInt()->value();
            case $value instanceof StringContract:
                return (int) $value->value();
            default:
                return value($default);
        }
    }

public function getNumberable ( $ value , $ default = null ) { switch ( true ) { case is_int ( $ value ) : case is_float ( $ value ) : return $ value ; case is_numeric ( $ value ) && strpos ( $ value , '.' ) : return ( float ) $ value ; case is_numeric ( $ value ) : case is_bool ( $ value ) : return ( int ) $ value ; case $ value instanceof IntegerContract : case $ value instanceof FloatContract : return $ value -> value ( ) ; case $ value instanceof BooleanContract : return $ value -> toInt ( ) -> value ( ) ; case $ value instanceof StringContract : return ( int ) $ value -> value ( ) ; default : return value ( $ default ) ; } }

Retrieve number from any type or return default.

@param $value
@param null|mixed $default
@return float|int|mixed

Retrieve number from any type or return default .


public function getSearchable($value, $default = [])
    {
        if ($this->isArrayable($value))
        {
            return $this->getArrayable($value, $default);
        }
        elseif ($this->isStringable($value))
        {
            return $this->getStringable($value, $default);
        }
        elseif ($value instanceof Closure)
        {
            return $value;
        }

        return value($default);
    }

public function getSearchable ( $ value , $ default = [ ] ) { if ( $ this -> isArrayable ( $ value ) ) { return $ this -> getArrayable ( $ value , $ default ) ; } elseif ( $ this -> isStringable ( $ value ) ) { return $ this -> getStringable ( $ value , $ default ) ; } elseif ( $ value instanceof Closure ) { return $ value ; } return value ( $ default ) ; }

Retrieve value that can be used in search methods.

@param mixed $value
@param mixed $default
@return array|string|\Closure|mixed

Retrieve value that can be used in search methods .


protected function boolFromString($value)
    {
        $grammar = $this->getGrammar();

        $value = $this->getStringable($value);

        if (isset($grammar[$value])) return $grammar[$value];

        return false;
    }

protected function boolFromString ( $ value ) { $ grammar = $ this -> getGrammar ( ) ; $ value = $ this -> getStringable ( $ value ) ; if ( isset ( $ grammar [ $ value ] ) ) return $ grammar [ $ value ] ; return false ; }

Construct proper Bool from string using grammar.

@param mixed $value
@return bool

Construct proper Bool from string using grammar .


protected function getGrammar()
    {
        return [
            'true' => true, 'false' => false,
            'on' => true,   'off' => false,
            'yes' => true,  'no' => false,
            'y' => true,    'n' => false,
            '+' => true,    '-' => false
        ];
    }

protected function getGrammar ( ) { return [ 'true' => true , 'false' => false , 'on' => true , 'off' => false , 'yes' => true , 'no' => false , 'y' => true , 'n' => false , '+' => true , '-' => false ] ; }

Return grammar to construct Bool from string.

@return array

Return grammar to construct Bool from string .


public function createGifCommand(array $sourcesImages, $resultImageName, $resultDirectory, $delay = 50, $loop = 0)
	{
		$cmd = $this->createGifCommandCmd($sourcesImages, $resultImageName, $resultDirectory, $delay, $loop);

		return `$cmd`;
	}

public function createGifCommand ( array $ sourcesImages , $ resultImageName , $ resultDirectory , $ delay = 50 , $ loop = 0 ) { $ cmd = $ this -> createGifCommandCmd ( $ sourcesImages , $ resultImageName , $ resultDirectory , $ delay , $ loop ) ; return `$cmd` ; }

Executes the command to create a gif image of the passed source images...

@param array  $sourcesImages   Array which contains the path to the source images.
@param string $resultImageName Name of the result image, the ".gif" extension will be added automatically.
@param string $resultDirectory Path to directory where the result image should be stored.
@param int    $delay           Delay of gif animation.
@param int    $loop            Amount of loops of gif image.

@return string

Executes the command to create a gif image of the passed source images ...


public function createGifCommandCmd(array $sourcesImages,
	                                    $resultImageName,
	                                    $resultDirectory,
	                                    $delay = 50,
	                                    $loop = 0)
	{
		$delayOption = $this->_createOption(Delay::class, $delay);
		$loopOption  = $this->_createOption(Loop::class, $loop);

		return 'convert ' . $delayOption . implode(' ', $sourcesImages) . ' ' . $loopOption . $resultDirectory
		       . DIRECTORY_SEPARATOR . $resultImageName . '.gif';
	}

public
function
createGifCommandCmd
(
array
$
sourcesImages
,
$
resultImageName
,
$
resultDirectory
,
$
delay
=
50
,
$
loop
=
0
)
{
$
delayOption
=
$
this
->
_createOption
(
Delay
::
class
,
$
delay
)
;
$
loopOption
=
$
this
->
_createOption
(
Loop
::
class
,
$
loop
)
;
return
'convert '
.
$
delayOption
.
implode
(
' '
,
$
sourcesImages
)
.
' '
.
$
loopOption
.
$
resultDirectory
.
DIRECTORY_SEPARATOR
.
$
resultImageName
.
'.gif'
;
}

Returns the command to create a gif image of the passed source images.

@param array  $sourcesImages   Array which contains the path to the source images.
@param string $resultImageName Name of the result image, the ".gif" extension will be added automatically.
@param string $resultDirectory Path to directory where the result image should be stored.
@param int    $delay           Delay of gif animation.
@param int    $loop            Amount of loops of gif image.

@return string

Returns the command to create a gif image of the passed source images .


public function lookupMany($n = 1)
    {
        if ($n > $this->bufSize) {
            $this->bufSize = $n;
        }

        $this->fillBuffer();

        $tokens = [];
        $size = min($n, count($this->tokens));
        for ($i=0; $i<$size; $i++) {
            $tokens[] = $this->tokens[$i];
        }

        return $tokens;
    }

public function lookupMany ( $ n = 1 ) { if ( $ n > $ this -> bufSize ) { $ this -> bufSize = $ n ; } $ this -> fillBuffer ( ) ; $ tokens = [ ] ; $ size = min ( $ n , count ( $ this -> tokens ) ) ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) { $ tokens [ ] = $ this -> tokens [ $ i ] ; } return $ tokens ; }


public function format($decimals = 2, $decimalDelimiter = '.', $thousandDelimiter = ' ')
    {
        return new String(
            number_format(
                (float) $this->value,
                $this->getIntegerable($decimals),
                $this->getStringable($decimalDelimiter),
                $this->getStringable($thousandDelimiter)
            )
        );
    }

public
function
format
(
$
decimals
=
2
,
$
decimalDelimiter
=
'.'
,
$
thousandDelimiter
=
' '
)
{
return
new
String
(
number_format
(
(
float
)
$
this
->
value
,
$
this
->
getIntegerable
(
$
decimals
)
,
$
this
->
getStringable
(
$
decimalDelimiter
)
,
$
this
->
getStringable
(
$
thousandDelimiter
)
)
)
;
}

Format a number with grouped thousands and return String.

@param int|IntegerContract $decimals
@param string|StringContract $decimalDelimiter
@param string|StringContract $thousandDelimiter

@return \im\Primitive\Float\Float

Format a number with grouped thousands and return String .


public function hasPropertyByName($name)
    {
        foreach ($this->properties as $property) {
            if ($property->getName() == $name) {
                return true;
            }
        }

        return false;
    }

public function hasPropertyByName ( $ name ) { foreach ( $ this -> properties as $ property ) { if ( $ property -> getName ( ) == $ name ) { return true ; } } return false ; }

Returns if a property exists by name.

@param string $name The property name.

@return bool If the property exists.

@api


public function getPropertyByName($name)
    {
        foreach ($this->properties as $property) {
            if ($property->getName() == $name) {
                return $property;
            }
        }

        throw new \InvalidArgumentException(sprintf('The property "%s" does not exists.', $name));
    }

public
function
getPropertyByName
(
$
name
)
{
foreach
(
$
this
->
properties
as
$
property
)
{
if
(
$
property
->
getName
(
)
==
$
name
)
{
return
$
property
;
}
}
throw
new
\
InvalidArgumentException
(
sprintf
(
'The property "%s" does not exists.'
,
$
name
)
)
;
}

Returns a property by name.

@param string $name The property name.

@return Mandango\Mondator\Definition\Property The property.

@throws \InvalidArgumentException If the property does not exists.

@api


public function removePropertyByName($name)
    {
        foreach ($this->properties as $key => $property) {
            if ($property->getName() == $name) {
                unset($this->properties[$key]);
                return;
            }
        }

        throw new \InvalidArgumentException(sprintf('The property "%s" does not exists.', $name));
    }

public
function
removePropertyByName
(
$
name
)
{
foreach
(
$
this
->
properties
as
$
key
=>
$
property
)
{
if
(
$
property
->
getName
(
)
==
$
name
)
{
unset
(
$
this
->
properties
[
$
key
]
)
;
return
;
}
}
throw
new
\
InvalidArgumentException
(
sprintf
(
'The property "%s" does not exists.'
,
$
name
)
)
;
}

Remove property by name.

@param string $name The property name.

@throws \InvalidArgumentException If the property does not exists.

@api


public function hasMethodByName($name)
    {
        foreach ($this->methods as $method) {
            if ($method->getName() == $name) {
                return true;
            }
        }

        return false;
    }

public function hasMethodByName ( $ name ) { foreach ( $ this -> methods as $ method ) { if ( $ method -> getName ( ) == $ name ) { return true ; } } return false ; }

Returns if exists a method by name.

@param string $name The method name.

@return bool If the method exists.

@api


public function getMethodByName($name)
    {
        foreach ($this->methods as $method) {
            if ($method->getName() == $name) {
                return $method;
            }
        }

        throw new \InvalidArgumentException(sprintf('The method "%s" does not exists.', $name));
    }

public
function
getMethodByName
(
$
name
)
{
foreach
(
$
this
->
methods
as
$
method
)
{
if
(
$
method
->
getName
(
)
==
$
name
)
{
return
$
method
;
}
}
throw
new
\
InvalidArgumentException
(
sprintf
(
'The method "%s" does not exists.'
,
$
name
)
)
;
}

Return a method by name.

@param string $name The method name.

@return Mandango\Mondator\Definition\Method The method.

@throws \InvalidArgumentException If the method does not exists.

@api


public function removeMethodByName($name)
    {
        foreach ($this->methods as $key => $method) {
            if ($method->getName() == $name) {
                unset($this->methods[$key]);
                return;
            }
        }

        throw new \InvalidArgumentException(sprintf('The method "%s" does not exists.', $name));
    }

public
function
removeMethodByName
(
$
name
)
{
foreach
(
$
this
->
methods
as
$
key
=>
$
method
)
{
if
(
$
method
->
getName
(
)
==
$
name
)
{
unset
(
$
this
->
methods
[
$
key
]
)
;
return
;
}
}
throw
new
\
InvalidArgumentException
(
sprintf
(
'The method "%s" does not exists.'
,
$
name
)
)
;
}

Remove a method by name.

@param string $name The method name.

@throws \InvalidArgumentException If the method does not exists.

@api


protected function parse_meta($file)
    {
        // Grab meta section between '/* ... */' in the content file
        preg_match_all('#/\*(.*?)\*/#s', $file, $meta);

        // Retrieve individual meta fields
        preg_match_all('#^[\t]?(\w*):(.*)$#mi', $meta[1][0], $match);

        for ($i=0; $i < count($match[1]); $i++) {
            $result[strtolower($match[1][$i])] = trim(htmlentities($match[2][$i]));
        }

        return $result;
    }

Parses Markdown file headers for metadata

@param  string $file The loaded Markdown file as a string
@return array        An array containing file metadata
@codeCoverageIgnore


public function run_hooks($hook_id, $args = array())
    {
        // If plugins are disabled, do not run
        if ($this->app['settings']['sonic.plugins_enabled'] === FALSE) {
            return FALSE;
        }

        // Run hooks associated with that event
        foreach ($this->app['plugins'] as $plugin_id => $plugin) {
            if (is_callable(array($plugin, $hook_id))) {
                call_user_func_array(array($plugin, $hook_id), $args);
            }
        }
        return TRUE;
    }

public
function
run_hooks
(
$
hook_id
,
$
args
=
array
(
)
)
{
// If plugins are disabled, do not run
if
(
$
this
->
app
[
'settings'
]
[
'sonic.plugins_enabled'
]
===
FALSE
)
{
return
FALSE
;
}
// Run hooks associated with that event
foreach
(
$
this
->
app
[
'plugins'
]
as
$
plugin_id
=>
$
plugin
)
{
if
(
is_callable
(
array
(
$
plugin
,
$
hook_id
)
)
)
{
call_user_func_array
(
array
(
$
plugin
,
$
hook_id
)
,
$
args
)
;
}
}
return
TRUE
;
}

Runs all hooks registered to the specified hook name

@param  string  $hook_id
@param  string  $args
@return boolean


protected function load_plugins()
    {
        if ($this->app['settings']['sonic.plugins_enabled'] === TRUE) {

            // Load plugins from 'plugins' folder
            $file_list    = $this->app['filesystem']->listContents($this->app['settings']['sonic.plugins_dir']);

            $plugin_files = array_filter($file_list, function ($file) {
                return preg_match('#^([A-Z]+\w+)Plugin.php$#', $file['basename']) === 1
                    ? TRUE
                    : FALSE;
            });

            foreach ($plugin_files as $plugin_file) {
                $plugin = $this->app['filesystem']->include($plugin_file['path']);
                $plugin->set_app($this);
                $plugins[$plugin_file['filename']] = $plugin;
            }

            $this->app['plugins'] = $plugins;
        }
    }

protected
function
load_plugins
(
)
{
if
(
$
this
->
app
[
'settings'
]
[
'sonic.plugins_enabled'
]
===
TRUE
)
{
// Load plugins from 'plugins' folder
$
file_list
=
$
this
->
app
[
'filesystem'
]
->
listContents
(
$
this
->
app
[
'settings'
]
[
'sonic.plugins_dir'
]
)
;
$
plugin_files
=
array_filter
(
$
file_list
,
function
(
$
file
)
{
return
preg_match
(
'#^([A-Z]+\w+)Plugin.php$#'
,
$
file
[
'basename'
]
)
===
1
TRUE
:
FALSE
;
}
)
;
foreach
(
$
plugin_files
as
$
plugin_file
)
{
$
plugin
=
$
this
->
app
[
'filesystem'
]
->
include
(
$
plugin_file
[
'path'
]
)
;
$
plugin
->
set_app
(
$
this
)
;
$
plugins
[
$
plugin_file
[
'filename'
]
]
=
$
plugin
;
}
$
this
->
app
[
'plugins'
]
=
$
plugins
;
}
}

Loads all plugins from the 'plugins' directory

@return

Loads all plugins from the plugins directory


protected function setup_router()
    {
        // Only because you can't use $this->app in the callback
        $app       = $this->app;
        $file_list = $app['filesystem']->listContents($app['settings']['sonic.content_dir'], true);

        $files     = array_filter($file_list, function ($file) {
            return isset($file['extension']) && $file['extension'] === 'md'
                ? TRUE
                : FALSE;
        });

        // Add each as a route
        foreach ($files as $file) {

            // Get filename without extension
            $file_path = str_replace(
                $app['settings']['sonic.content_dir'],
                '',
                $file['dirname'] . '/' . $file['filename']
            );

            $route = '/' . trim(str_replace('/index', '/', $file_path), '/');

            $this->app['router']->route(new Routes\DefaultRoute($route));
        }
    }

Does the initial setup for the router. This entails creating the routes
for the application, mainly

@return

Does the initial setup for the router . This entails creating the routes for the application mainly


public function get($key, $default = null)
    {
        return Arr::get($this->items, $this->getKey($key), $default);
    }

public function get ( $ key , $ default = null ) { return Arr :: get ( $ this -> items , $ this -> getKey ( $ key ) , $ default ) ; }

Getter. Supports dot notation.

@param mixed $key
@param mixed $default
@return mixed


public function set($key, $value)
    {
        Arr::set($this->items, $this->getKey($key), $value);

        return $this;
    }

public function set ( $ key , $ value ) { Arr :: set ( $ this -> items , $ this -> getKey ( $ key ) , $ value ) ; return $ this ; }

Setter. Supports dot notation.

@param mixed $key
@param mixed $value
@return $this


public function pushToKey($key, $value)
    {
        if ( ! $this->has($key))
        {
            $this->set($key, []);
        }

        $keyValue = $this->get($key);

        if ($keyValue instanceof static)
        {
            $keyValue->push($value);
        }
        elseif (is_array($keyValue))
        {
            $keyValue[] = $value;
        }
        else
        {
            $this->set($key, [])->pushToKey($key, $keyValue);

            return $this;
        }

        $this->set($key, $keyValue);

        return $this;
    }

public function pushToKey ( $ key , $ value ) { if ( ! $ this -> has ( $ key ) ) { $ this -> set ( $ key , [ ] ) ; } $ keyValue = $ this -> get ( $ key ) ; if ( $ keyValue instanceof static ) { $ keyValue -> push ( $ value ) ; } elseif ( is_array ( $ keyValue ) ) { $ keyValue [ ] = $ value ; } else { $ this -> set ( $ key , [ ] ) -> pushToKey ( $ key , $ keyValue ) ; return $ this ; } $ this -> set ( $ key , $ keyValue ) ; return $ this ; }

Push value to specified key

@param mixed $key
@param mixed $value
@return $this


public function search($value, $strict = false)
    {
        return Arr::search($this->items, $this->getSearchable($value, $value), $this->getBoolable($strict));
    }

public function search ( $ value , $ strict = false ) { return Arr :: search ( $ this -> items , $ this -> getSearchable ( $ value , $ value ) , $ this -> getBoolable ( $ strict ) ) ; }

Search for specified value, return key on success, otherwise false.
If value is nested deeper than 1 level dot notation key will be returned.
You can specify strict search with 2 argument.

@param mixed $value
@param bool|BooleanContract $strict
@return mixed

Search for specified value return key on success otherwise false . If value is nested deeper than 1 level dot notation key will be returned . You can specify strict search with 2 argument .


public function keysByField($keyBy)
    {
        $byField = [];

        $keyBy = $this->getStringable($keyBy);

        foreach ($this->items as $item)
        {
            $key = _data_get($item, $keyBy);

            $byField[$key] = $item;
        }

        return new static($byField);
    }

public function keysByField ( $ keyBy ) { $ byField = [ ] ; $ keyBy = $ this -> getStringable ( $ keyBy ) ; foreach ( $ this -> items as $ item ) { $ key = _data_get ( $ item , $ keyBy ) ; $ byField [ $ key ] = $ item ; } return new static ( $ byField ) ; }

Key an associative array by a field.

@param  string|StringContract  $keyBy
@return static


public function unique($recursive = false)
    {
        if ($this->getBoolable($recursive))
        {
            return new static($this->uniqueRecursive($this->items));
        }

        return new static(array_unique($this->items));
    }

public function unique ( $ recursive = false ) { if ( $ this -> getBoolable ( $ recursive ) ) { return new static ( $ this -> uniqueRecursive ( $ this -> items ) ) ; } return new static ( array_unique ( $ this -> items ) ) ; }

Unique Container items.

@param bool|BooleanContract $recursive
@return $this


public function numericKeys()
    {
        $keys = new static;

        foreach ($this->items as $key => $value)
        {
            if (is_numeric($key)) $keys->set($key, $value);
        }

        return $keys;
    }

public function numericKeys ( ) { $ keys = new static ; foreach ( $ this -> items as $ key => $ value ) { if ( is_numeric ( $ key ) ) $ keys -> set ( $ key , $ value ) ; } return $ keys ; }

Return items only with numeric keys.

@return static


public function join($glue = '')
    {
        foreach ($copy = Arr::flatten($this->items) as $key => $object)
        {
            $copy[$key] = $this->getStringable($object);
        }

        return string(implode($this->getStringable($glue, ''), $copy));
    }

public function join ( $ glue = '' ) { foreach ( $ copy = Arr :: flatten ( $ this -> items ) as $ key => $ object ) { $ copy [ $ key ] = $ this -> getStringable ( $ object ) ; } return string ( implode ( $ this -> getStringable ( $ glue , '' ) , $ copy ) ) ; }

Return joined Container items.

@param string|StringContract $glue
@return \im\Primitive\String\String


public function joinByKey($key, $glue = null)
    {
        return string(implode($glue, $this->lists($this->getKey($key))->all()));
    }

public function joinByKey ( $ key , $ glue = null ) { return string ( implode ( $ glue , $ this -> lists ( $ this -> getKey ( $ key ) ) -> all ( ) ) ) ; }

Concatenate values of a given key as a string.

@param mixed $key
@param null|mixed $glue
@return \im\Primitive\String\String

Concatenate values of a given key as a string .


public function lists($valueByKey, $key = null)
    {
        return new static(Arr::pluck($this->items, $this->getKey($valueByKey), $this->getKey($key)));
    }

public function lists ( $ valueByKey , $ key = null ) { return new static ( Arr :: pluck ( $ this -> items , $ this -> getKey ( $ valueByKey ) , $ this -> getKey ( $ key ) ) ) ; }

Get new Container with the values of a given key.
1 Argument is key to make value from.
2 Argument is key from the same Arrayable which will be the key.

@param  mixed $valueByKey
@param  mixed $key
@return static

Get new Container with the values of a given key . 1 Argument is key to make value from . 2 Argument is key from the same Arrayable which will be the key .


public function chunk($size = 2, $preserveKeys = false)
    {
        $size = $this->getIntegerable($size);

        if ( ! is_integer($size) || $size > $this->length())
        {
            throw new BadLengthException('Chunk size is larger than container length');
        }

        $chunks = new static;

        foreach (array_chunk($this->items, $size, $this->getBoolable($preserveKeys)) as $value)
        {
            $chunks->push(new static($value));
        }

        return $chunks;
    }

Return split Container items into chunks wrapped with new Container.

@param int|IntegerContract  $size
@param bool|BooleanContract $preserveKeys
@return \im\Primitive\Container\Container
@throws \im\Primitive\Container\Exceptions\BadLengthException

Return split Container items into chunks wrapped with new Container .


public function filter(callable $function, $recursive = false)
    {
        if ( ! $this->getBoolable($recursive))
        {
            return new static(array_filter($this->items, $function));
        }

        return new static($this->filterRecursive($function, $this->items));
    }

public function filter ( callable $ function , $ recursive = false ) { if ( ! $ this -> getBoolable ( $ recursive ) ) { return new static ( array_filter ( $ this -> items , $ function ) ) ; } return new static ( $ this -> filterRecursive ( $ function , $ this -> items ) ) ; }

Return filtered Container.
You can specify recursive filter with the second argument.

@param callable $function
@param bool|BooleanContract $recursive
@return Container

Return filtered Container . You can specify recursive filter with the second argument .


public function walk(callable $callback, $recursive = false, $userdata = null)
    {
        $function = $this->getBoolable($recursive) ? 'array_walk_recursive' : 'array_walk';

        $function($this->items, $callback, $userdata);

        return $this;
    }

public function walk ( callable $ callback , $ recursive = false , $ userdata = null ) { $ function = $ this -> getBoolable ( $ recursive ) ? 'array_walk_recursive' : 'array_walk' ; $ function ( $ this -> items , $ callback , $ userdata ) ; return $ this ; }

Apply a user function to every Container item.
You can specify recursive walk with the second argument.

@param callable $callback
@param bool|BooleanContract $recursive
@param null|mixed $userdata
@return $this

Apply a user function to every Container item . You can specify recursive walk with the second argument .


public function merge($items)
    {
        if ( ! $this->isArrayable($items))
        {
            throw new BadMethodCallException('Argument 1 must be array, Container or implement Arrayable interface');
        }

        return new static(array_merge($this->items, $this->retrieveValue($items)));
    }

Merge Arrayable with Container.

@param  mixed $items
@throws BadMethodCallException
@return $this


public function mergeWithKey($items, $key, $default = null)
    {
        $key = $this->getKey($key);

        if ( ! $this->has($key)) throw new InvalidArgumentException('Key: '.$key.' not exists');

        $get = $this->get($key, $default);

        $value = array_merge($get, $this->retrieveValue($items));

        return $this->copy()->set($key, $value);
    }

public
function
mergeWithKey
(
$
items
,
$
key
,
$
default
=
)
{
$
key
=
$
this
->
getKey
(
$
key
)
;
if
(
!
$
this
->
has
(
$
key
)
)
throw
new
InvalidArgumentException
(
'Key: '
.
$
key
.
' not exists'
)
;
$
get
=
$
this
->
get
(
$
key
,
$
default
)
;
$
value
=
array_merge
(
$
get
,
$
this
->
retrieveValue
(
$
items
)
)
;
return
$
this
->
copy
(
)
->
set
(
$
key
,
$
value
)
;
}

Merge Arrayable with specified key in Container.

@param mixed $items
@param mixed $key
@param null $default
@return $this
@throws InvalidArgumentException

Merge Arrayable with specified key in Container .


public function increase($increaseSize = 1, $value = null)
    {
        $this->items = array_pad($this->items, $this->length() + $this->getIntegerable($increaseSize), $value);

        return $this;
    }

public function increase ( $ increaseSize = 1 , $ value = null ) { $ this -> items = array_pad ( $ this -> items , $ this -> length ( ) + $ this -> getIntegerable ( $ increaseSize ) , $ value ) ; return $ this ; }

Increase Container to the specified length with a value.

@param int|IntegerContract $increaseSize
@param null|mixed $value
@return $this

Increase Container to the specified length with a value .


public function randomKey($quantity = 1)
    {
        $quantity = $this->getIntegerable($quantity);

        if ($this->isNotEmpty() && $this->length() >= $quantity && $quantity > 0)
        {
            $random = array_rand($this->items, $quantity);

            return is_array($random) ? new static($random) : $random;
        }

        throw new BadMethodCallException("1 Argument should be between 1 and the number of elements in the Container, got: {$quantity}");
    }

Return pseudo-random index from Container.

@param int|IntegerContract $quantity
@throws BadMethodCallException
@return mixed

Return pseudo - random index from Container .


public function random($quantity = 1)
    {
        $quantity = $this->getIntegerable($quantity);

        $result = new static;

        while($quantity--)
        {
            $result->push($this->items[$this->randomKey()]);
        }

        return $result->length() === 1 ? $result->first() : $result;
    }

public function random ( $ quantity = 1 ) { $ quantity = $ this -> getIntegerable ( $ quantity ) ; $ result = new static ; while ( $ quantity -- ) { $ result -> push ( $ this -> items [ $ this -> randomKey ( ) ] ) ; } return $ result -> length ( ) === 1 ? $ result -> first ( ) : $ result ; }

Return pseudo-random item from Container.

@param int|IntegerContract $quantity
@return array

Return pseudo - random item from Container .


public function cut($offset, $length = null, $preserveKeys = false, $set = false)
    {
        $result = array_slice(
            $this->items,
            $this->getIntegerable($offset),
            $this->getIntegerable($length),
            $this->getBoolable($preserveKeys)
        );

        if ($this->getBoolable($set))
        {
            $this->items = empty($result) ? [] : $result;

            return $this;
        }

        return new static($result);
    }

public function cut ( $ offset , $ length = null , $ preserveKeys = false , $ set = false ) { $ result = array_slice ( $ this -> items , $ this -> getIntegerable ( $ offset ) , $ this -> getIntegerable ( $ length ) , $ this -> getBoolable ( $ preserveKeys ) ) ; if ( $ this -> getBoolable ( $ set ) ) { $ this -> items = empty ( $ result ) ? [ ] : $ result ; return $ this ; } return new static ( $ result ) ; }

Cut a slice of a Container.
You can return result or assign to Container with the forth argument.

@param int|IntegerContract $offset
@param null|int|IntegerContract $length
@param bool|BooleanContract $preserveKeys
@param bool|BooleanContract $set
@return static|$this

Cut a slice of a Container . You can return result or assign to Container with the forth argument .


public function reject($callback)
    {
        if (is_callable($callback))
        {
            return $this->copy()->filter(function($item) use ($callback)
            {
                return ! $callback($item);
            });
        }

        $callback = $this->getStringable($callback);

        return $this->copy()->filter(function($item) use ($callback)
        {
            return $item != $callback;
        });
    }

public function reject ( $ callback ) { if ( is_callable ( $ callback ) ) { return $ this -> copy ( ) -> filter ( function ( $ item ) use ( $ callback ) { return ! $ callback ( $ item ) ; } ) ; } $ callback = $ this -> getStringable ( $ callback ) ; return $ this -> copy ( ) -> filter ( function ( $ item ) use ( $ callback ) { return $ item != $ callback ; } ) ; }

Create new Container of all elements that do not pass a given truth test.

@param callable|string|StringContract $callback
@return static

Create new Container of all elements that do not pass a given truth test .


public function forget($key)
    {
        Arr::forget($this->items, $this->getStringable($key));

        return $this;
    }

public function forget ( $ key ) { Arr :: forget ( $ this -> items , $ this -> getStringable ( $ key ) ) ; return $ this ; }

Remove key from Container. Supports dot notation.

@param mixed $key
@return $this

Remove key from Container . Supports dot notation .


public function reverse($preserveKeys = true)
    {
        $this->items = array_reverse($this->items, $this->getBoolable($preserveKeys));

        return $this;
    }

public function reverse ( $ preserveKeys = true ) { $ this -> items = array_reverse ( $ this -> items , $ this -> getBoolable ( $ preserveKeys ) ) ; return $ this ; }

Reverse Container items.

@param bool|BooleanContract $preserveKeys
@return $this


public function groupBy($groupBy)
    {
        if ($this->isStringable($groupBy, true)) $groupBy = $this->getStringable($groupBy);

        $results = [];

        foreach ($this->items as $key => $value)
        {
            $results[$this->getGroupByKey($groupBy, $key, $value)][] = $value;
        }

        return new static($results);
    }

public function groupBy ( $ groupBy ) { if ( $ this -> isStringable ( $ groupBy , true ) ) $ groupBy = $ this -> getStringable ( $ groupBy ) ; $ results = [ ] ; foreach ( $ this -> items as $ key => $ value ) { $ results [ $ this -> getGroupByKey ( $ groupBy , $ key , $ value ) ] [ ] = $ value ; } return new static ( $ results ) ; }

Group an associative array by a field or callback value.

@param  \Closure|string|StringContract  $groupBy
@return static

Group an associative array by a field or callback value .


public function exceptIndex($nth)
    {
        $nth = $this->getIntegerable($nth);

        if ($this->isEmpty() || $nth >= $this->length())
        {
            throw new OffsetNotExistsException('Offset: '. $nth .' not exist');
        }

        return $this->copy()->forget($this->keys()->get($nth));
    }

public
function
exceptIndex
(
$
nth
)
{
$
nth
=
$
this
->
getIntegerable
(
$
nth
)
;
if
(
$
this
->
isEmpty
(
)
||
$
nth
>=
$
this
->
length
(
)
)
{
throw
new
OffsetNotExistsException
(
'Offset: '
.
$
nth
.
' not exist'
)
;
}
return
$
this
->
copy
(
)
->
forget
(
$
this
->
keys
(
)
->
get
(
$
nth
)
)
;
}

Return copy of Container except given index.

@param int|IntegerContract $nth
@throws OffsetNotExistsException
@return Container

Return copy of Container except given index .


public function restAfterIndex($index)
    {
        $index = $this->getIntegerable($index);

        if ( ! is_numeric($index))
        {
            throw new BadMethodCallException('Argument 1: ' . $index . ' is not numeric');
        }

        $length = $this->length();

        if ($length <= $index)
        {
            throw new OffsetNotExistsException('Offset: '. $index .' not exists');
        }

        $index++;

        $keys = $this->keys()->cut($index, $length - 1)->flip();

        $values = $this->values()->cut($index, $length - 1)->all();

        return $keys->combine($values, 'values');
    }

public
function
restAfterIndex
(
$
index
)
{
$
index
=
$
this
->
getIntegerable
(
$
index
)
;
if
(
!
is_numeric
(
$
index
)
)
{
throw
new
BadMethodCallException
(
'Argument 1: '
.
$
index
.
' is not numeric'
)
;
}
$
length
=
$
this
->
length
(
)
;
if
(
$
length
<=
$
index
)
{
throw
new
OffsetNotExistsException
(
'Offset: '
.
$
index
.
' not exists'
)
;
}
$
index
++
;
$
keys
=
$
this
->
keys
(
)
->
cut
(
$
index
,
$
length
1
)
->
flip
(
)
;
$
values
=
$
this
->
values
(
)
->
cut
(
$
index
,
$
length
1
)
->
all
(
)
;
return
$
keys
->
combine
(
$
values
,
'values'
)
;
}

Return rest items after given index.

@param int|IntegerContract $index
@return \im\Primitive\Container\Container
@throws \im\Primitive\Container\Exceptions\BadLengthException
@throws \im\Primitive\Container\Exceptions\ContainerException
@throws \im\Primitive\Support\Exceptions\OffsetNotExistsException


public function restAfterKey($key)
    {
        $key = $this->getKey($key);

        if ( ! array_key_exists($key, $this->items))
        {
            throw new OffsetNotExistsException('Key: '. $key .' not exists');
        }

        $index = $this->keys()->flip()->get($key);

        return $this->restAfterIndex($index);
    }

public
function
restAfterKey
(
$
key
)
{
$
key
=
$
this
->
getKey
(
$
key
)
;
if
(
!
array_key_exists
(
$
key
,
$
this
->
items
)
)
{
throw
new
OffsetNotExistsException
(
'Key: '
.
$
key
.
' not exists'
)
;
}
$
index
=
$
this
->
keys
(
)
->
flip
(
)
->
get
(
$
key
)
;
return
$
this
->
restAfterIndex
(
$
index
)
;
}

Return rest items after given key.

@param mixed $key
@return \im\Primitive\Container\Container
@throws \im\Primitive\Container\Exceptions\ContainerException
@throws \im\Primitive\Support\Exceptions\OffsetNotExistsException


public function difference($items)
    {
        if ($this->isArrayable($items))
        {
            return new static(array_diff_key($this->items, $this->retrieveValue($items)));
        }

        throw new BadMethodCallException('Argument 1 should be array, Container or implement ArrayableContract');
    }

Calculate difference of Container and given Arrayable.

@param mixed $items
@return static

Calculate difference of Container and given Arrayable .


public function take($key)
    {
        $take = [];

        $key = $this->getKey($key);

        $this->walk(function ($_value_, $_key_) use ($key, & $take)
        {
            if ($_key_ == $key) $take[] = $_value_;

        }, true);

        return new static($take);
    }

public function take ( $ key ) { $ take = [ ] ; $ key = $ this -> getKey ( $ key ) ; $ this -> walk ( function ( $ _value_ , $ _key_ ) use ( $ key , & $ take ) { if ( $ _key_ == $ key ) $ take [ ] = $ _value_ ; } , true ) ; return new static ( $ take ) ; }

Take all items recursively by key.

@param mixed $key
@return static


public function pull($key)
    {
        $key = $this->getKey($key);

        if ( ! $this->has($key))
        {
            throw new OffsetNotExistsException("Key: {$key} not exists");
        }

        return Arr::pull($this->items, $key);
    }

public
function
pull
(
$
key
)
{
$
key
=
$
this
->
getKey
(
$
key
)
;
if
(
!
$
this
->
has
(
$
key
)
)
{
throw
new
OffsetNotExistsException
(
"Key: {$key} not exists"
)
;
}
return
Arr
::
pull
(
$
this
->
items
,
$
key
)
;
}

Get a value from a Container, and remove it.

@param mixed $key
@return mixed
@throws OffsetNotExistsException

Get a value from a Container and remove it .


public function intersect($array, $assoc = false)
    {
        $function = $this->getBoolable($assoc) ? 'array_intersect_assoc' : 'array_intersect';

        return new static($function($this->items, $this->retrieveValue($array)));
    }

public function intersect ( $ array , $ assoc = false ) { $ function = $ this -> getBoolable ( $ assoc ) ? 'array_intersect_assoc' : 'array_intersect' ; return new static ( $ function ( $ this -> items , $ this -> retrieveValue ( $ array ) ) ) ; }

Return intersection with Arrayable.
You can specify second argument to with additional index check.

@param mixed $array
@param bool|BooleanContract $assoc
@return Container

Return intersection with Arrayable . You can specify second argument to with additional index check .


public function where($condition, $preserveKeys = true)
    {
        $condition = $this->retrieveValue($condition);

        if (empty($condition)) return $this;

        return new static($this->whereCondition($condition, $this->getBoolable($preserveKeys)));
    }

public function where ( $ condition , $ preserveKeys = true ) { $ condition = $ this -> retrieveValue ( $ condition ) ; if ( empty ( $ condition ) ) return $ this ; return new static ( $ this -> whereCondition ( $ condition , $ this -> getBoolable ( $ preserveKeys ) ) ) ; }

Find all items by key or key value pairs.
You can specify second parameter to preserve keys reset.

@param mixed $condition
@param bool|BooleanContract $preserveKeys
@throws ContainerException
@throws EmptyContainerException
@return static

Find all items by key or key value pairs . You can specify second parameter to preserve keys reset .


public function fromJson($json)
    {
        $json = $this->getStringable($json);

        if ($this->isJson($json))
        {
            $this->initialize(json_decode($json, true));
        }

        return $this;
    }

public function fromJson ( $ json ) { $ json = $ this -> getStringable ( $ json ) ; if ( $ this -> isJson ( $ json ) ) { $ this -> initialize ( json_decode ( $ json , true ) ) ; } return $ this ; }

Construct from Json.

@param $json
@return $this


public function fromFile($file)
    {
        $file = $this->getStringable($file);

        if ( ! $this->isFile($file)) throw new NotIsFileException('Not is file: ' . $file);

        $content = file_get_contents($file);

        if ($this->isJson($content))
        {
            return $this->initialize(json_decode($content, true));
        }
        elseif ($this->isSerialized($content))
        {
            return $this->initialize(unserialize($content));
        }

        throw new ContainerException('Can\'t convert file to Container');
    }

public
function
fromFile
(
$
file
)
{
$
file
=
$
this
->
getStringable
(
$
file
)
;
if
(
!
$
this
->
isFile
(
$
file
)
)
throw
new
NotIsFileException
(
'Not is file: '
.
$
file
)
;
$
content
=
file_get_contents
(
$
file
)
;
if
(
$
this
->
isJson
(
$
content
)
)
{
return
$
this
->
initialize
(
json_decode
(
$
content
,
true
)
)
;
}
elseif
(
$
this
->
isSerialized
(
$
content
)
)
{
return
$
this
->
initialize
(
unserialize
(
$
content
)
)
;
}
throw
new
ContainerException
(
'Can\'t convert file to Container'
)
;
}

Construct from file.
Contents can be json or serialized array.

@param string|StringContract $file
@throws ContainerException
@throws NotIsFileException
@return $this

Construct from file . Contents can be json or serialized array .


public function fromSerialized($content)
    {
        $content = $this->getStringable($content);

        if ($this->isSerialized($content))
        {
            return $this->initialize(unserialize($content));
        }

        throw new BadMethodCallException('Expected serialized, got: ' . $content);
    }

public
function
fromSerialized
(
$
content
)
{
$
content
=
$
this
->
getStringable
(
$
content
)
;
if
(
$
this
->
isSerialized
(
$
content
)
)
{
return
$
this
->
initialize
(
unserialize
(
$
content
)
)
;
}
throw
new
BadMethodCallException
(
'Expected serialized, got: '
.
$
content
)
;
}

Construct from serialized.

@param string|StringContract $content
@return $this


public function fromEncrypted($encrypted, $key)
    {
        $encrypted = $this->getStringable($encrypted);

        $key = $this->getStringable($key);

        if ($this->isEncryptedContainer($encrypted, $key))
        {
            $data = JWT::decode($encrypted, $key);

            return $this->fromJson($data->container);
        }

        throw new BadMethodCallException('Expected encrypted Container, got: ' . $encrypted);
    }

public
function
fromEncrypted
(
$
encrypted
,
$
key
)
{
$
encrypted
=
$
this
->
getStringable
(
$
encrypted
)
;
$
key
=
$
this
->
getStringable
(
$
key
)
;
if
(
$
this
->
isEncryptedContainer
(
$
encrypted
,
$
key
)
)
{
$
data
=
JWT
::
decode
(
$
encrypted
,
$
key
)
;
return
$
this
->
fromJson
(
$
data
->
container
)
;
}
throw
new
BadMethodCallException
(
'Expected encrypted Container, got: '
.
$
encrypted
)
;
}

Construct from Encrypted Container.

@param string|StringContract $encrypted
@param string|StringContract $key
@return \im\Primitive\Container\Container


protected function fromString($string)
    {
        if ($this->isFile($string))
        {
            return $this->fromFile($string);
        }
        elseif ($this->isJson($string))
        {
            return $this->initialize(json_decode($string, true));
        }
        elseif ($this->isSerialized($string))
        {
            return $this->initialize(unserialize($string));
        }

        throw new BadMethodCallException('Argument 1 should be valid json, serialized or file with json or serialized data');
    }

Construct from string.

@param string|StringContract $string
@return $this
@throws \im\Primitive\Container\Exceptions\ContainerException
@throws \im\Primitive\Support\Exceptions\NotIsFileException


protected function whereCondition(array $conditions, $preserveKeys)
    {
        $key = first_key($conditions);  $value = array_shift($conditions);

        $where = $this->whereRecursive($this->items, $key, $value, $preserveKeys);

        foreach ($conditions as $key => $value)
        {
            $where = $this->whereRecursive($where, $key, $value, $preserveKeys);
        }

        return $where;
    }

protected function whereCondition ( array $ conditions , $ preserveKeys ) { $ key = first_key ( $ conditions ) ; $ value = array_shift ( $ conditions ) ; $ where = $ this -> whereRecursive ( $ this -> items , $ key , $ value , $ preserveKeys ) ; foreach ( $ conditions as $ key => $ value ) { $ where = $ this -> whereRecursive ( $ where , $ key , $ value , $ preserveKeys ) ; } return $ where ; }

Find where condition is array.

@param array $conditions
@param bool $preserveKeys
@return array
@throws EmptyContainerException


protected function whereRecursive($array, $key, $value = null, $preventKeys = false)
    {
        $outputArray = [];

        $iterator = new RecursiveIteratorIterator(
            new RecursiveContainerIterator($array),
            RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $sub)
        {
            $subIterator = $iterator->getSubIterator();

            if (isset($subIterator[$key]) && (( ! is_null($value) && $subIterator[$key] == $value ) || is_null($value)))
            {
                $outputArray += $this->iteratorToArray($iterator, $subIterator, $outputArray, $preventKeys);
            }
        }

        return $outputArray;
    }

protected function whereRecursive ( $ array , $ key , $ value = null , $ preventKeys = false ) { $ outputArray = [ ] ; $ iterator = new RecursiveIteratorIterator ( new RecursiveContainerIterator ( $ array ) , RecursiveIteratorIterator :: SELF_FIRST ) ; foreach ( $ iterator as $ sub ) { $ subIterator = $ iterator -> getSubIterator ( ) ; if ( isset ( $ subIterator [ $ key ] ) && ( ( ! is_null ( $ value ) && $ subIterator [ $ key ] == $ value ) || is_null ( $ value ) ) ) { $ outputArray += $ this -> iteratorToArray ( $ iterator , $ subIterator , $ outputArray , $ preventKeys ) ; } } return $ outputArray ; }

Recursively traversing tree.

@param $array
@param $key
@param $value
@param $preventKeys
@return array


protected function iteratorToArray(RecursiveIteratorIterator $iterator, Iterator $subIterator, array $outputArray, $preventKeys = false)
    {
        if ($preventKeys === false)
        {
            $key = $iterator->getSubIterator($iterator->getDepth() - 1)->key();

            $outputArray[$key] = iterator_to_array($subIterator);
        }
        else
        {
            $outputArray[] = iterator_to_array($subIterator);
        }

        return $outputArray;
    }

protected function iteratorToArray ( RecursiveIteratorIterator $ iterator , Iterator $ subIterator , array $ outputArray , $ preventKeys = false ) { if ( $ preventKeys === false ) { $ key = $ iterator -> getSubIterator ( $ iterator -> getDepth ( ) - 1 ) -> key ( ) ; $ outputArray [ $ key ] = iterator_to_array ( $ subIterator ) ; } else { $ outputArray [ ] = iterator_to_array ( $ subIterator ) ; } return $ outputArray ; }

Convert iterator to array.

@param RecursiveIteratorIterator $iterator
@param Iterator $subIterator
@param array $outputArray
@param $preventKeys
@return array


protected function getGroupByKey($groupBy, $key, $value)
    {
        if ( ! is_string($groupBy) && $groupBy instanceof Closure)
        {
            return $groupBy($value, $key);
        }

        return _data_get($value, $groupBy);
    }

protected function getGroupByKey ( $ groupBy , $ key , $ value ) { if ( ! is_string ( $ groupBy ) && $ groupBy instanceof Closure ) { return $ groupBy ( $ value , $ key ) ; } return _data_get ( $ value , $ groupBy ) ; }

Get the "group by" key value.

@param  \Closure|string  $groupBy
@param  string  $key
@param  mixed  $value
@return string


protected function filterRecursive(Closure $function, $items)
    {
        if ( ! $this->isArrayable($items)) return $items;

        foreach ($items as $key => $item)
        {
            $items[$key] = $this->filterRecursive($function, $this->retrieveValue($item));
        }

        return array_filter($items, $function);
    }

protected function filterRecursive ( Closure $ function , $ items ) { if ( ! $ this -> isArrayable ( $ items ) ) return $ items ; foreach ( $ items as $ key => $ item ) { $ items [ $ key ] = $ this -> filterRecursive ( $ function , $ this -> retrieveValue ( $ item ) ) ; } return array_filter ( $ items , $ function ) ; }

Recursive filter.

@param \Closure $function
@param          $items
@return array


protected function forgetRecursive($forgetKey, $items)
    {
        Arr::forget($items, $forgetKey);

        foreach ($items as $key => $item)
        {
            if ($this->isArrayable($item))
            {
                $items[$key] = $this->forgetRecursive($forgetKey, $this->retrieveValue($item));
            }
        }

        return $items;
    }

protected function forgetRecursive ( $ forgetKey , $ items ) { Arr :: forget ( $ items , $ forgetKey ) ; foreach ( $ items as $ key => $ item ) { if ( $ this -> isArrayable ( $ item ) ) { $ items [ $ key ] = $ this -> forgetRecursive ( $ forgetKey , $ this -> retrieveValue ( $ item ) ) ; } } return $ items ; }

Recursive unset.

@param $forgetKey
@param mixed $items
@return mixed


protected function uniqueRecursive($items)
    {
        foreach ($items as $key => $item)
        {
            if ($this->isArrayable($item))
            {
                $this->items[$key] = $this->uniqueRecursive($this->retrieveValue($item));
            }
        }

        return array_unique($this->items);
    }

protected function uniqueRecursive ( $ items ) { foreach ( $ items as $ key => $ item ) { if ( $ this -> isArrayable ( $ item ) ) { $ this -> items [ $ key ] = $ this -> uniqueRecursive ( $ this -> retrieveValue ( $ item ) ) ; } } return array_unique ( $ this -> items ) ; }

Unique items recursively.

@param $items
@return array


protected function getKey($key, $default = null)
    {
        return ($this->isIntegerable($key, true)) ? $this->getIntegerable($key, $default)
                                                  : $this->getStringable($key, $default);
    }

protected function getKey ( $ key , $ default = null ) { return ( $ this -> isIntegerable ( $ key , true ) ) ? $ this -> getIntegerable ( $ key , $ default ) : $ this -> getStringable ( $ key , $ default ) ; }

Retrieve proper key.

@param mixed $key
@param null|mixed $default
@return int|string


protected function addOrEditObject($data = [], $redirect = TRUE)
	{
		$section = $this->getSession('Aprila.lastAddedObject');
		$stateOk = FALSE;

		try {
			if ($this->detailObject) {
				// Edit object
				$this->canUser('edit');
				$this->mainManager->edit($this->detailObject->id, $data);
				$stateOk = TRUE;
				$this->flashMessage('Object saved');

			} else {
				// Add object
				$this->canUser('add');
				$new = $this->mainManager->add($data);
				try {
					$object = $new->toArray();
				} catch (\Exception $e) {
					$object = NULL;
					$this->logger->log($e->getMessage(), ILogger::ERROR);
				}

				$section->newObject = ArrayHash::from($object);
				$stateOk = TRUE;
				$this->flashMessage('Object added');
			}

			// Do something
			$this->afterSaveObject($data);

		} catch (\Exception $e) {
			$this->flashMessage('System problem due saving object', 'error');
			$this->logger->log($e->getMessage(), ILogger::ERROR);
		}

		if ($redirect && $stateOk) {
			$this->redirect('default');
		}

	}

protected
function
addOrEditObject
(
$
data
=
[
]
,
$
redirect
=
TRUE
)
{
$
section
=
$
this
->
getSession
(
'Aprila.lastAddedObject'
)
;
$
stateOk
=
FALSE
;
try
{
if
(
$
this
->
detailObject
)
{
// Edit object
$
this
->
canUser
(
'edit'
)
;
$
this
->
mainManager
->
edit
(
$
this
->
detailObject
->
id
,
$
data
)
;
$
stateOk
=
TRUE
;
$
this
->
flashMessage
(
'Object saved'
)
;
}
else
{
// Add object
$
this
->
canUser
(
'add'
)
;
$
new
=
$
this
->
mainManager
->
add
(
$
data
)
;
try
{
$
object
=
$
new
->
toArray
(
)
;
}
catch
(
\
Exception
$
e
)
{
$
object
=
;
$
this
->
logger
->
log
(
$
e
->
getMessage
(
)
,
ILogger
::
ERROR
)
;
}
$
section
->
newObject
=
ArrayHash
::
from
(
$
object
)
;
$
stateOk
=
TRUE
;
$
this
->
flashMessage
(
'Object added'
)
;
}
// Do something
$
this
->
afterSaveObject
(
$
data
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
flashMessage
(
'System problem due saving object'
,
'error'
)
;
$
this
->
logger
->
log
(
$
e
->
getMessage
(
)
,
ILogger
::
ERROR
)
;
}
if
(
$
redirect
&&
$
stateOk
)
{
$
this
->
redirect
(
'default'
)
;
}
}

Simple implementation add or edit object

@param array $data
@param bool $redirect


public function getOption($value)
	{
		if(!in_array(strtolower($value), $this->allowedOptions, true))
		{
			throw new InvalidOptionValueException('Invalid $value argument "' . $value . '", allowed values: '
			                                      . implode(', ', $this->allowedOptions));
		}

		return '-compose ' . strtolower($value) . ' ';
	}

public
function
getOption
(
$
value
)
{
if
(
!
in_array
(
strtolower
(
$
value
)
,
$
this
->
allowedOptions
,
true
)
)
{
throw
new
InvalidOptionValueException
(
'Invalid $value argument "'
.
$
value
.
'", allowed values: '
.
implode
(
', '
,
$
this
->
allowedOptions
)
)
;
}
return
'-compose '
.
strtolower
(
$
value
)
.
' '
;
}

Returns a prepared compose options string.

@param string $value Expected option value.

@link http://www.imagemagick.org/script/compose.php

@return string
@throws \ImageMagick\Exceptions\InvalidOptionValueException

Returns a prepared compose options string .


public function excerpts($files)
    {
        // Create array to hold posts
        $posts = array();

        // Iterate through files and get excerpts for all of them
        foreach ($files as $file) {
            $file_contents = $this->sonic->app['filesystem']->parse($file);

            if (
                $file_contents['meta']['title'] !== 'Quote'
                &&
                $this->sonic->app['settings']['site.excerpt_newline_limit'] !== 0
            ) {
                $contents  = $this->sonic->app['helper']->get_excerpt(
                    $file_contents['contents'],
                    $this->sonic->app['settings']['site.excerpt_newline_limit']
                );

                $file_contents['contents'] = $contents;
            }
            $posts[str_replace('content/', '', $file)] = $file_contents;
        }

        return $posts;
    }

Gets file excerpts from all files

@param  array $files
@return array


public static function fetch($array, $key)
    {
        $results = [];

        foreach (explode('.', $key) as $segment)
        {
            foreach ($array as $value)
            {
                if (array_key_exists($segment, $value = (array) $value))
                {
                    $results[] = $value[$segment];
                }
            }

            $array = array_values($results);
        }

        return array_values($results);
    }

public static function fetch ( $ array , $ key ) { $ results = [ ] ; foreach ( explode ( '.' , $ key ) as $ segment ) { foreach ( $ array as $ value ) { if ( array_key_exists ( $ segment , $ value = ( array ) $ value ) ) { $ results [ ] = $ value [ $ segment ] ; } } $ array = array_values ( $ results ) ; } return array_values ( $ results ) ; }

Fetch a flattened array of a nested array element.

@param  array  $array
@param  string $key

@return array

Fetch a flattened array of a nested array element .


public static function forget(&$array, $keys)
    {
        $original =& $array;

        foreach ((array) $keys as $key)
        {
            $parts = explode('.', $key);

            while (count($parts) > 1)
            {
                $part = array_shift($parts);

                if ((is_array($array) && isset($array[$part]) && is_array($array[$part])) ||
                    (is_object($array) && isset($array->{$part}) && is_array($array->{$part})))
                {
                    if (is_array($array)) $array =& $array[$part];
                    elseif (is_object($array)) $array =& $array->{$part};
                }
            }

            $part = array_shift($parts);

            if (is_array($array)) unset($array[$part]);
            elseif (is_object($array)) unset($array->{$part});

            // clean up after each pass
            $array =& $original;
        }
    }

public
static
function
forget
(
&
$
array
,
$
keys
)
{
$
original
=
&
$
array
;
foreach
(
(
array
)
$
keys
as
$
key
)
{
$
parts
=
explode
(
'.'
,
$
key
)
;
while
(
count
(
$
parts
)
>
1
)
{
$
part
=
array_shift
(
$
parts
)
;
if
(
(
is_array
(
$
array
)
&&
isset
(
$
array
[
$
part
]
)
&&
is_array
(
$
array
[
$
part
]
)
)
||
(
is_object
(
$
array
)
&&
isset
(
$
array
->
{
$
part
}
)
&&
is_array
(
$
array
->
{
$
part
}
)
)
)
{
if
(
is_array
(
$
array
)
)
$
array
=
&
$
array
[
$
part
]
;
elseif
(
is_object
(
$
array
)
)
$
array
=
&
$
array
->
{
$
part
}
;
}
}
$
part
=
array_shift
(
$
parts
)
;
if
(
is_array
(
$
array
)
)
unset
(
$
array
[
$
part
]
)
;
elseif
(
is_object
(
$
array
)
)
unset
(
$
array
->
{
$
part
}
)
;
// clean up after each pass
$
array
=
&
$
original
;
}
}

Remove one or many array items from a given array using "dot" notation.

@param  array|object $array
@param  array|string $keys

@return void

Remove one or many array items from a given array using dot notation .


public static function get($array, $key, $default = null)
    {
        if (is_null($key)) return $array;

        if (isset($array[$key])) return $array[$key];

        return _data_get($array, $key, $default);
    }

public static function get ( $ array , $ key , $ default = null ) { if ( is_null ( $ key ) ) return $ array ; if ( isset ( $ array [ $ key ] ) ) return $ array [ $ key ] ; return _data_get ( $ array , $ key , $ default ) ; }

Get an item using "dot" notation.

@param  array|object  $array
@param  string $key
@param  mixed  $default

@return mixed


public static function has($array, $key)
    {
        if (empty($array) || is_null($key)) return false;

        if (array_key_exists($key, $array)) return true;

        return _data_get($array, $key, new Exception('Not Found')) instanceof Exception ? false : true;
    }

public
static
function
has
(
$
array
,
$
key
)
{
if
(
empty
(
$
array
)
||
is_null
(
$
key
)
)
return
false
;
if
(
array_key_exists
(
$
key
,
$
array
)
)
return
true
;
return
_data_get
(
$
array
,
$
key
,
new
Exception
(
'Not Found'
)
)
instanceof
Exception
false
:
true
;
}

Check if an item exists using "dot" notation.

@param  array|object  $array
@param  string $key

@return bool

Check if an item exists using dot notation .


public static function set(&$array, $key, $value)
    {
        if (is_null($key)) return $array = $value;

        $keys = explode('.', $key);

        while (count($keys) > 1)
        {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if ((is_array($array) && ( ! isset($array[$key]) || ! is_array($array[$key]))) ||
                (is_object($array) && ( ! isset($array->{$key}) || ! is_array($array->{$key}))))
            {
                if (is_array($array)) $array[$key] = [];
                elseif (is_object($array)) $array->{$key} = [];
            }

            if (is_array($array)) $array =& $array[$key];
            elseif (is_object($array)) $array =& $array->{$key};
        }

        $key = array_shift($keys);

        if (is_array($array)) $array[$key] = $value;
        elseif (is_object($array)) $array->{$key} = $value;

        return $array;
    }

Set item to a given key using "dot" notation.

If no key is given to the method, the entire array will be replaced.

@param  array|object  $array
@param  string $key
@param  mixed  $value

@return array

Set item to a given key using dot notation .


public static function search($array, $value, $strict = false, $prepend = '', $default = null)
    {
        foreach ($array as $key => $_value_)
        {
            $key = $prepend === '' ? $key : $prepend.'.'.$key;

            if (($strict && $_value_ === $value) || ( ! $strict && $_value_ == $value))
            {
                return $key;
            }

            if (is_array($_value_) || $_value_ instanceof \Traversable)
            {
                $found = static::search($_value_, $value, $strict, $key, $default);

                if ($found === $default) continue;

                return $found;
            }
        }

        return $default;
    }

public static function search ( $ array , $ value , $ strict = false , $ prepend = '' , $ default = null ) { foreach ( $ array as $ key => $ _value_ ) { $ key = $ prepend === '' ? $ key : $ prepend . '.' . $ key ; if ( ( $ strict && $ _value_ === $ value ) || ( ! $ strict && $ _value_ == $ value ) ) { return $ key ; } if ( is_array ( $ _value_ ) || $ _value_ instanceof \ Traversable ) { $ found = static :: search ( $ _value_ , $ value , $ strict , $ key , $ default ) ; if ( $ found === $ default ) continue ; return $ found ; } } return $ default ; }

Search value in Traversable and return key using dot notation.

@param $array
@param $value
@param bool $strict
@param string $prepend
@param null $default
@return int|null|string

Search value in Traversable and return key using dot notation .


protected function renderLibrary($source, $callback = null)
    {
        if ($callback === null) {
            return sprintf('<script type="text/javascript" src="%s"></script>'.PHP_EOL, $source);
        }

        $output = array();

        $output[] = 'var s = document.createElement("script");'.PHP_EOL;
        $output[] = 's.type = "text/javascript";'.PHP_EOL;
        $output[] = 's.async = true;'.PHP_EOL;
        $output[] = sprintf('s.src = "%s";'.PHP_EOL, $source);
        $output[] = sprintf('s.addEventListener("load", function () { %s(); }, false);'.PHP_EOL, $callback);
        $output[] = 'document.getElementsByTagName("head")[0].appendChild(s);'.PHP_EOL;

        return implode('', $output);
    }

Renders a library.

@param string      $source   The library source.
@param string|null $callback The javascript callback.

@return string The HTML output.


public function htaccessDeny(string $dir, bool $allow_static_access = false): int
    {
        $deny = // `.htaccess` file.
            '<IfModule authz_core_module>'."\n".
            '	Require all denied'."\n".
            '</IfModule>'."\n".
            '<IfModule !authz_core_module>'."\n".
            '	deny from all'."\n".
            '</IfModule>';

        if ($allow_static_access) {
            $deny .= "\n\n".// Allow these file extensions.
            '<FilesMatch "\.(js|css|gif|jpg|png|svg|eot|woff|ttf|html|txt|md)$">'."\n".
            '	<IfModule authz_core_module>'."\n".
            '		Require all granted'."\n".
            '	</IfModule>'."\n".
            '	<IfModule !authz_core_module>'."\n".
            '		allow from all'."\n".
            '	</IfModule>'."\n".
            '</FilesMatch>';
        }
        return (int) file_put_contents($dir.'/.htaccess', $deny);
    }

Deny public access.

@since 160522 Apache utilities.

@param string $dir                 Directory to deny access in.
@param bool   $allow_static_access Allow static file access?

@return int Number of bytes written to file.


public function getNewToken(ClientEntityInterface $ClientEntity, array $scopes, $user_identifier = null)
    {
        return $this->App->Di->get(AccessTokenEntity::class);
    }

public function getNewToken ( ClientEntityInterface $ ClientEntity , array $ scopes , $ user_identifier = null ) { return $ this -> App -> Di -> get ( AccessTokenEntity :: class ) ; }

New access token entity.

@param ClientEntityInterface $ClientEntity    Client entity.
@param array                 $scopes          Scope entities.
@param mixed                 $user_identifier User identifier.

@return AccessTokenEntity Access token entity.


public function setInputId($inputId)
    {
        if (!is_string($inputId) || (strlen($inputId) === 0)) {
            throw PlaceException::invalidAutocompleteInputId();
        }

        $this->inputId = $inputId;
    }

public function setInputId ( $ inputId ) { if ( ! is_string ( $ inputId ) || ( strlen ( $ inputId ) === 0 ) ) { throw PlaceException :: invalidAutocompleteInputId ( ) ; } $ this -> inputId = $ inputId ; }

Sets the autocomplete input ID.

@param string $inputId The autocomplete input ID.

@throws \Ivory\GoogleMap\Exception\PlaceException If the input ID is not a valid string.


public function setBound()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Bound)) {
            $this->bound = $args[0];
        } elseif ((isset($args[0]) && ($args[0] instanceof Coordinate))
            && (isset($args[1]) && ($args[1] instanceof Coordinate))
        ) {
            if ($this->bound === null) {
                $this->bound = new Bound();
            }

            $this->bound->setSouthWest($args[0]);
            $this->bound->setNorthEast($args[1]);
        } elseif ((isset($args[0]) && is_numeric($args[0]))
            && (isset($args[1]) && is_numeric($args[1]))
            && (isset($args[2]) && is_numeric($args[2]))
            && (isset($args[3]) && is_numeric($args[3]))
        ) {
            if ($this->bound === null) {
                $this->bound = new Bound();
            }

            $this->bound->setSouthWest(new Coordinate($args[0], $args[1]));
            $this->bound->setNorthEast(new Coordinate($args[2], $args[3]));

            if (isset($args[4]) && is_bool($args[4])) {
                $this->bound->getSouthWest()->setNoWrap($args[4]);
            }

            if (isset($args[5]) && is_bool($args[5])) {
                $this->bound->getNorthEast()->setNoWrap($args[5]);
            }
        } elseif (!isset($args[0])) {
            $this->bound = null;
        } else {
            throw PlaceException::invalidAutocompleteBound();
        }
    }

public function setBound ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Bound ) ) { $ this -> bound = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) && ( isset ( $ args [ 1 ] ) && ( $ args [ 1 ] instanceof Coordinate ) ) ) { if ( $ this -> bound === null ) { $ this -> bound = new Bound ( ) ; } $ this -> bound -> setSouthWest ( $ args [ 0 ] ) ; $ this -> bound -> setNorthEast ( $ args [ 1 ] ) ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) && ( isset ( $ args [ 2 ] ) && is_numeric ( $ args [ 2 ] ) ) && ( isset ( $ args [ 3 ] ) && is_numeric ( $ args [ 3 ] ) ) ) { if ( $ this -> bound === null ) { $ this -> bound = new Bound ( ) ; } $ this -> bound -> setSouthWest ( new Coordinate ( $ args [ 0 ] , $ args [ 1 ] ) ) ; $ this -> bound -> setNorthEast ( new Coordinate ( $ args [ 2 ] , $ args [ 3 ] ) ) ; if ( isset ( $ args [ 4 ] ) && is_bool ( $ args [ 4 ] ) ) { $ this -> bound -> getSouthWest ( ) -> setNoWrap ( $ args [ 4 ] ) ; } if ( isset ( $ args [ 5 ] ) && is_bool ( $ args [ 5 ] ) ) { $ this -> bound -> getNorthEast ( ) -> setNoWrap ( $ args [ 5 ] ) ; } } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> bound = null ; } else { throw PlaceException :: invalidAutocompleteBound ( ) ; } }

Sets the autocomplete bound.

Available prototypes:
- function setBound(Ivory\GoogleMap\Base\Bound $bound = null)
- function setBount(Ivory\GoogleMap\Base\Coordinate $southWest, Ivory\GoogleMap\Base\Coordinate $northEast)
- function setBound(
double $southWestLatitude,
double $southWestLongitude,
double $northEastLatitude,
double $northEastLongitude,
boolean southWestNoWrap = true,
boolean $northEastNoWrap = true
)

@throws \Ivory\GoogleMap\Exception\PlaceException If the bound is not valid (prototypes).


public function addType($type)
    {
        if (!in_array($type, AutocompleteType::getAvailableAutocompleteTypes())) {
            throw PlaceException::invalidAutocompleteType();
        }

        if ($this->hasType($type)) {
            throw PlaceException::autocompleteTypeAlreadyExists($type);
        }

        $this->types[] = $type;
    }

public function addType ( $ type ) { if ( ! in_array ( $ type , AutocompleteType :: getAvailableAutocompleteTypes ( ) ) ) { throw PlaceException :: invalidAutocompleteType ( ) ; } if ( $ this -> hasType ( $ type ) ) { throw PlaceException :: autocompleteTypeAlreadyExists ( $ type ) ; } $ this -> types [ ] = $ type ; }

Adds a type to the autocomplete.

@param string $type The type to add.

@throws \Ivory\GoogleMap\Exception\PlaceException If the type is not valid.
@throws \Ivory\GoogleMap\Exception\PlaceException If the type already exists.


public function removeType($type)
    {
        if (!$this->hasType($type)) {
            throw PlaceException::autocompleteTypeDoesNotExist($type);
        }

        $index = array_search($type, $this->types);
        unset($this->types[$index]);
    }

public function removeType ( $ type ) { if ( ! $ this -> hasType ( $ type ) ) { throw PlaceException :: autocompleteTypeDoesNotExist ( $ type ) ; } $ index = array_search ( $ type , $ this -> types ) ; unset ( $ this -> types [ $ index ] ) ; }

Removes a type from the autocomplete.

@param string $type The type to remove.

@throws \Ivory\GoogleMap\Exception\PlaceException If the type does not exist.


public function getComponentRestriction($type)
    {
        if (!$this->hasComponentRestriction($type)) {
            throw PlaceException::autocompleteComponentRestrictionDoesNotExist($type);
        }

        return $this->componentRestrictions[$type];
    }

Gets a specific component restriction.

@param string $type The component restriction type.

@throws \Ivory\GoogleMap\Exception\PlaceException If the component restriction type does not exist.

@return mixed The component restriction.


public function setComponentRestrictions(array $componentRestrictions)
    {
        $this->componentRestrictions = array();

        foreach ($componentRestrictions as $type => $value) {
            $this->addComponentRestriction($type, $value);
        }
    }

public function setComponentRestrictions ( array $ componentRestrictions ) { $ this -> componentRestrictions = array ( ) ; foreach ( $ componentRestrictions as $ type => $ value ) { $ this -> addComponentRestriction ( $ type , $ value ) ; } }

Sets the component restrictions.

@param array $componentRestrictions The component restrictions.


public function addComponentRestriction($type, $value)
    {
        if (!in_array($type, AutocompleteComponentRestriction::getAvailableAutocompleteComponentRestrictions())) {
            throw PlaceException::invalidAutocompleteComponentRestriction();
        }

        if ($this->hasComponentRestriction($type)) {
            throw PlaceException::autocompleteComponentRestrictionAlreadyExists($type);
        }

        $this->componentRestrictions[$type] = $value;
    }

Adds a component restriction.

@param string $type  The component restriction type.
@param mixed  $value The component restriction value.

@throws \Ivory\GoogleMap\Exception\PlaceException If the component restriction type is not supported.
@throws \Ivory\GoogleMap\Exception\PlaceException If the component restriction type already exists.


public function removeComponentRestriction($type)
    {
        if (!$this->hasComponentRestriction($type)) {
            throw PlaceException::autocompleteComponentRestrictionDoesNotExist($type);
        }

        unset($this->componentRestrictions[$type]);
    }

Removes a component restriction.

@param string $type The component restriction.

@throws \Ivory\GoogleMap\Exception\PlaceException If the component restriction type does not exists.


public function setInputAttributes(array $inputAttributes)
    {
        $this->inputAttributes = array();

        foreach ($inputAttributes as $name => $value) {
            $this->setInputAttribute($name, $value);
        }
    }

public function setInputAttributes ( array $ inputAttributes ) { $ this -> inputAttributes = array ( ) ; foreach ( $ inputAttributes as $ name => $ value ) { $ this -> setInputAttribute ( $ name , $ value ) ; } }

Sets the autocomplete input attributes.

@param array $inputAttributes The autocomplete input attributes.

Sets the autocomplete input attributes .


public function setInputAttribute($name, $value)
    {
        if ($value === null) {
            if (isset($this->inputAttributes[$name])) {
                unset($this->inputAttributes[$name]);
            }
        } else {
            $this->inputAttributes[$name] = $value;
        }
    }

public function setInputAttribute ( $ name , $ value ) { if ( $ value === null ) { if ( isset ( $ this -> inputAttributes [ $ name ] ) ) { unset ( $ this -> inputAttributes [ $ name ] ) ; } } else { $ this -> inputAttributes [ $ name ] = $ value ; } }

Sets an autocomplete attribute.

You can remove an attribute by setting it to `null`.

@param string $name  The attribute name.
@param mixed  $value The attribute value.


public function identipattern(array $args): bool
    {
        if (!class_exists('Imagick')) {
            return false;
        }
        $default_args = [
            'string' => '',
            'for'    => '',

            'color'      => '',
            'base_color' => '',

            'output_file'   => '',
            'output_format' => '',
        ];
        $args += $default_args; // Defaults.
        $args = $this->parseFormatArgs($args);

        if (!$args['output_file'] || !$args['output_format']) {
            return false; // Required arguments.
        }
        $args['string'] = (string) $args['string'];
        $args['string'] = $args['string'] ?: (string) $args['for'];

        $args['color']      = (string) $args['color'];
        $args['base_color'] = (string) $args['base_color'];

        $output_file_existed_prior = is_file($args['output_file']);

        try { // Catch exceptions.
            $svg = (new Identipattern([
                'string'    => $args['string'] ?: null,
                'baseColor' => $args['base_color'] ?: null,
                'color'     => $args['color'] ?: null,
            ]))->toSVG(); // SVG format initially.

            if (file_put_contents($args['output_file'], $svg) === false) {
                throw $this->c::issue('Storage failure.');
            }
            if ($args['output_format'] !== 'svg') {
                if (!$this->convert([
                        'format' => 'svg',
                        'file'   => $args['output_file'],

                        'output_file'   => $args['output_file'],
                        'output_format' => $args['output_format'],
                    ])) {
                    throw $this->c::issue('Conversion failure.');
                }
            }
            return true; // Success.
            //
        } catch (\Throwable $Exception) {
            if (!$output_file_existed_prior && is_file($args['output_file'])) {
                unlink($args['output_file']);
            }
            return false;
        }
    }

public
function
identipattern
(
array
$
args
)
:
bool
{
if
(
!
class_exists
(
'Imagick'
)
)
{
return
false
;
}
$
default_args
=
[
'string'
=>
''
,
'for'
=>
''
,
'color'
=>
''
,
'base_color'
=>
''
,
'output_file'
=>
''
,
'output_format'
=>
''
,
]
;
$
args
+=
$
default_args
;
// Defaults.
$
args
=
$
this
->
parseFormatArgs
(
$
args
)
;
if
(
!
$
args
[
'output_file'
]
||
!
$
args
[
'output_format'
]
)
{
return
false
;
// Required arguments.
}
$
args
[
'string'
]
=
(
string
)
$
args
[
'string'
]
;
$
args
[
'string'
]
=
$
args
[
'string'
]
:
(
string
)
$
args
[
'for'
]
;
$
args
[
'color'
]
=
(
string
)
$
args
[
'color'
]
;
$
args
[
'base_color'
]
=
(
string
)
$
args
[
'base_color'
]
;
$
output_file_existed_prior
=
is_file
(
$
args
[
'output_file'
]
)
;
try
{
// Catch exceptions.
$
svg
=
(
new
Identipattern
(
[
'string'
=>
$
args
[
'string'
]
:
,
'baseColor'
=>
$
args
[
'base_color'
]
:
,
'color'
=>
$
args
[
'color'
]
:
,
]
)
)
->
toSVG
(
)
;
// SVG format initially.
if
(
file_put_contents
(
$
args
[
'output_file'
]
,
$
svg
)
===
false
)
{
throw
$
this
->
c
::
issue
(
'Storage failure.'
)
;
}
if
(
$
args
[
'output_format'
]
!==
'svg'
)
{
if
(
!
$
this
->
convert
(
[
'format'
=>
'svg'
,
'file'
=>
$
args
[
'output_file'
]
,
'output_file'
=>
$
args
[
'output_file'
]
,
'output_format'
=>
$
args
[
'output_format'
]
,
]
)
)
{
throw
$
this
->
c
::
issue
(
'Conversion failure.'
)
;
}
}
return
true
;
// Success.
//
}
catch
(
\
Throwable
$
Exception
)
{
if
(
!
$
output_file_existed_prior
&&
is_file
(
$
args
[
'output_file'
]
)
)
{
unlink
(
$
args
[
'output_file'
]
)
;
}
return
false
;
}
}

Identipattern generator.

@since 17xxxx Identipatterns.

@param array $args Named arguments.

@return bool True on success.


public function convert(array $args): bool
    {
        if (!class_exists('Imagick')) {
            return false;
        }
        $default_args = [
            'file'   => '',
            'format' => '',

            'output_file'   => '',
            'output_format' => '',
        ];
        $args += $default_args; // Defaults.
        $args = $this->parseFormatArgs($args);

        if (!is_file($args['file']) || !$args['format']) {
            return false; // Not possible.
        } elseif (!$args['output_file'] || !$args['output_format']) {
            return false; // Not possible.
        }
        $output_file_existed_prior = is_file($args['output_file']);

        try { // Catch exceptions.
            $image = new \Imagick();
            $image->setBackgroundColor('transparent');
            $image->readImage($args['format'].':'.$args['file']);

            $image->writeImage($args['output_format'].':'.$args['output_file']);
            return true; // Success.
            //
        } catch (\Throwable $Exception) {
            if (!$output_file_existed_prior && is_file($args['output_file'])) {
                unlink($args['output_file']);
            }
            return false;
        }
    }

public
function
convert
(
array
$
args
)
:
bool
{
if
(
!
class_exists
(
'Imagick'
)
)
{
return
false
;
}
$
default_args
=
[
'file'
=>
''
,
'format'
=>
''
,
'output_file'
=>
''
,
'output_format'
=>
''
,
]
;
$
args
+=
$
default_args
;
// Defaults.
$
args
=
$
this
->
parseFormatArgs
(
$
args
)
;
if
(
!
is_file
(
$
args
[
'file'
]
)
||
!
$
args
[
'format'
]
)
{
return
false
;
// Not possible.
}
elseif
(
!
$
args
[
'output_file'
]
||
!
$
args
[
'output_format'
]
)
{
return
false
;
// Not possible.
}
$
output_file_existed_prior
=
is_file
(
$
args
[
'output_file'
]
)
;
try
{
// Catch exceptions.
$
image
=
new
\
Imagick
(
)
;
$
image
->
setBackgroundColor
(
'transparent'
)
;
$
image
->
readImage
(
$
args
[
'format'
]
.
':'
.
$
args
[
'file'
]
)
;
$
image
->
writeImage
(
$
args
[
'output_format'
]
.
':'
.
$
args
[
'output_file'
]
)
;
return
true
;
// Success.
//
}
catch
(
\
Throwable
$
Exception
)
{
if
(
!
$
output_file_existed_prior
&&
is_file
(
$
args
[
'output_file'
]
)
)
{
unlink
(
$
args
[
'output_file'
]
)
;
}
return
false
;
}
}

Convert image format.

@since 17xxxx Imagick utils.

@param array $args Named arguments.

@return bool True on success.