public function findTagWeights($limit = 20)
    {
        $models = self::find()
            ->orderBy('frequency DESC')
            ->limit($limit)
            -all();

        $total=0;
        foreach ($models as $model) {
            $total+=$model->frequency;
        }

        $tags=[];
        if ($total > 0)
        {
            foreach ($models as $model) {
                $tags[$model->name] = 8 + (int)(16*$model->frequency/($total+10));
            }
            ksort($tags);
        }

        return $tags;
    }

public
function
findTagWeights
(
$
limit
=
20
)
{
$
models
=
self
::
find
(
)
->
orderBy
(
'frequency DESC'
)
->
limit
(
$
limit
)
all
(
)
;
$
total
=
0
;
foreach
(
$
models
as
$
model
)
{
$
total
+=
$
model
->
frequency
;
}
$
tags
=
[
]
;
if
(
$
total
>
0
)
{
foreach
(
$
models
as
$
model
)
{
$
tags
[
$
model
->
name
]
=
8
+
(
int
)
(
16
*
$
model
->
frequency
/
(
$
total
+
10
)
)
;
}
ksort
(
$
tags
)
;
}
return
$
tags
;
}

Returns tag names and their corresponding weights.
Only the tags with the top weights will be returned.
@param integer the maximum number of tags that should be returned
@return array weights indexed by tag names.

Returns tag names and their corresponding weights . Only the tags with the top weights will be returned .


public static function addTags($tags, $tagType)
    {
        foreach ($tags as $name) {
            $tag = self::find()
                ->where(['name' => $name])
                ->andWhere(['tag_type' => $tagType])
                ->one();

            //if tag does not exists, insert it
            if (is_null($tag)) {
                $tag = new self();
                $tag->name = $name;
                $tag->tag_type = $tagType;
                $tag->frequency = self::DEFAULT_FREQUENCY;
                $tag->save(false);
            } else {
                //Update count of tags already exists
                $tag->updateCounters(['frequency' => self::DEFAULT_FREQUENCY]);
            }
        }
    }

public
static
function
addTags
(
$
tags
,
$
tagType
)
{
foreach
(
$
tags
as
$
name
)
{
$
tag
=
self
::
find
(
)
->
where
(
[
'name'
=>
$
name
]
)
->
andWhere
(
[
'tag_type'
=>
$
tagType
]
)
->
one
(
)
;
//if tag does not exists, insert it
if
(
is_null
(
$
tag
)
)
{
$
tag
=
new
self
(
)
;
$
tag
->
name
=
$
name
;
$
tag
->
tag_type
=
$
tagType
;
$
tag
->
frequency
=
self
::
DEFAULT_FREQUENCY
;
$
tag
->
save
(
false
)
;
}
else
{
//Update count of tags already exists
$
tag
->
updateCounters
(
[
'frequency'
=>
self
::
DEFAULT_FREQUENCY
]
)
;
}
}
}

Update count of tags already exists
if tag does not exists, insert it
@param $tags
@param $tagType

Update count of tags already exists if tag does not exists insert it


public static function removeTags($tags, $tagType)
    {
        if (empty($tags)) {
            return;
        }

        foreach ($tags as $name) {
            $tag = self::find()
                ->where(['name' => $name])
                ->andWhere(['tag_type' => $tagType])
                ->one();
            if (!is_null($tag)) {
                $tag->updateCounters(['frequency' => '-' . self::DEFAULT_FREQUENCY]);

                if ($tag->frequency <= 0) {
                    $tag->delete();
                }
            }
        }
    }

public static function removeTags ( $ tags , $ tagType ) { if ( empty ( $ tags ) ) { return ; } foreach ( $ tags as $ name ) { $ tag = self :: find ( ) -> where ( [ 'name' => $ name ] ) -> andWhere ( [ 'tag_type' => $ tagType ] ) -> one ( ) ; if ( ! is_null ( $ tag ) ) { $ tag -> updateCounters ( [ 'frequency' => '-' . self :: DEFAULT_FREQUENCY ] ) ; if ( $ tag -> frequency <= 0 ) { $ tag -> delete ( ) ; } } } }

Decrement frequency
if less then or equal to zero then delete row
@param $tags
@param $tagType


public function getTabParentOptions(): array
    {
        $columns[] = 'tl_content.type = ?';
        $columns[] = 'tl_content.pid = ?';
        $columns[] = 'tl_content.ptable = ?';

        $values[] = 'bs_tab_start';
        $values[] = CURRENT_ID;
        $values[] = $GLOBALS['TL_DCA']['tl_content']['config']['ptable'];

        $collection = $this->repository->findBy($columns, $values);
        $options    = [];

        if ($collection) {
            foreach ($collection as $model) {
                $options[$model->id] = sprintf(
                    '%s [%s]',
                    $model->bs_tab_name,
                    $model->id
                );
            }
        }

        return $options;
    }

public
function
getTabParentOptions
(
)
:
array
{
$
columns
[
]
=
'tl_content.type = ?'
;
$
columns
[
]
=
'tl_content.pid = ?'
;
$
columns
[
]
=
'tl_content.ptable = ?'
;
$
values
[
]
=
'bs_tab_start'
;
$
values
[
]
=
CURRENT_ID
;
$
values
[
]
=
$
GLOBALS
[
'TL_DCA'
]
[
'tl_content'
]
[
'config'
]
[
'ptable'
]
;
$
collection
=
$
this
->
repository
->
findBy
(
$
columns
,
$
values
)
;
$
options
=
[
]
;
if
(
$
collection
)
{
foreach
(
$
collection
as
$
model
)
{
$
options
[
$
model
->
id
]
=
sprintf
(
'%s [%s]'
,
$
model
->
bs_tab_name
,
$
model
->
id
)
;
}
}
return
$
options
;
}

Get all tab parent options.

@return array

@SuppressWarnings(PHPMD.Superglobals)


public function generateColumns($dataContainer)
    {
        if (!$dataContainer->activeRecord || $dataContainer->activeRecord->type !== 'bs_tab_start') {
            return;
        }

        /** @var ContentModel|Result $current */
        $current      = $dataContainer->activeRecord;
        $stopElement  = $this->getStopElement($current);
        $count        = $this->countRequiredSeparators($dataContainer->activeRecord->bs_tabs, $current);
        $nextElements = $this->getNextElements($stopElement);

        if ($count > 0) {
            $sorting = (int) $stopElement->sorting;
            $sorting = $this->createSeparators((int) $count, $current, $sorting);

            array_unshift($nextElements, $stopElement);
            $this->updateSortings($nextElements, $sorting);
        }
    }

Generate the columns.

@param DataContainer $dataContainer Data container driver.

@return void


private function countRequiredSeparators($definition, $current): int
    {
        $definition = StringUtil::deserialize($definition, true);
        $count      = -1;

        foreach ($definition as $item) {
            if ($item['type'] !== 'dropdown') {
                $count++;
            }
        }

        $count -= $this->repository->countBy(
            [
                'tl_content.ptable=?',
                'tl_content.pid=?',
                '(tl_content.type = ? AND tl_content.bs_tab_parent = ?)',
            ],
            [$current->ptable, $current->pid, 'bs_tab_separator', $current->id],
            ['order' => 'tl_content.sorting ASC']
        );

        return $count;
    }

Count the required separator fields which should be created.

@param mixed        $definition The tab definitions.
@param ContentModel $current    The current content model.

@return int

Count the required separator fields which should be created .


protected function createSeparators(int $value, $current, int $sorting): int
    {
        for ($count = 1; $count <= $value; $count++) {
            $sorting = ($sorting + 8);
            $this->createTabElement($current, 'bs_tab_separator', $sorting);
        }

        return $sorting;
    }

protected function createSeparators ( int $ value , $ current , int $ sorting ) : int { for ( $ count = 1 ; $ count <= $ value ; $ count ++ ) { $ sorting = ( $ sorting + 8 ) ; $ this -> createTabElement ( $ current , 'bs_tab_separator' , $ sorting ) ; } return $ sorting ; }

Create separators.

@param int          $value   Number of separators being created.
@param ContentModel $current Current model.
@param int          $sorting Current sorting value.

@return int


protected function createStopElement($current, int $sorting): Model
    {
        $sorting = ($sorting + 8);

        return $this->createTabElement($current, 'bs_tab_end', $sorting);
    }

protected function createStopElement ( $ current , int $ sorting ) : Model { $ sorting = ( $ sorting + 8 ) ; return $ this -> createTabElement ( $ current , 'bs_tab_end' , $ sorting ) ; }

Create the stop element.

@param ContentModel $current Model.
@param int          $sorting Last sorting value.

@return Model


protected function createTabElement($current, string $type, int &$sorting): Model
    {
        $model                = new ContentModel();
        $model->tstamp        = time();
        $model->pid           = $current->pid;
        $model->ptable        = $current->ptable;
        $model->sorting       = $sorting;
        $model->type          = $type;
        $model->bs_tab_parent = $current->id;
        $model->save();

        return $model;
    }

protected function createTabElement ( $ current , string $ type , int & $ sorting ) : Model { $ model = new ContentModel ( ) ; $ model -> tstamp = time ( ) ; $ model -> pid = $ current -> pid ; $ model -> ptable = $ current -> ptable ; $ model -> sorting = $ sorting ; $ model -> type = $ type ; $ model -> bs_tab_parent = $ current -> id ; $ model -> save ( ) ; return $ model ; }

Create a tab element.

@param ContentModel $current Current content model.
@param string       $type    Type of the content model.
@param int          $sorting The sorting value.

@return Model


protected function getStopElement($current): Model
    {
        $stopElement = $this->repository->findOneBy(
            ['tl_content.type=?', 'tl_content.bs_tab_parent=?'],
            ['bs_tab_end', $current->id]
        );

        if ($stopElement) {
            return $stopElement;
        }

        $nextElements = $this->getNextElements($current);
        $stopElement  = $this->createStopElement($current, (int) $current->sorting);
        $this->updateSortings($nextElements, (int) $stopElement->sorting);

        return $stopElement;
    }

protected function getStopElement ( $ current ) : Model { $ stopElement = $ this -> repository -> findOneBy ( [ 'tl_content.type=?' , 'tl_content.bs_tab_parent=?' ] , [ 'bs_tab_end' , $ current -> id ] ) ; if ( $ stopElement ) { return $ stopElement ; } $ nextElements = $ this -> getNextElements ( $ current ) ; $ stopElement = $ this -> createStopElement ( $ current , ( int ) $ current -> sorting ) ; $ this -> updateSortings ( $ nextElements , ( int ) $ stopElement -> sorting ) ; return $ stopElement ; }

Get related stop element.

@param ContentModel $current Current element.

@return ContentModel|Model


public function addIcon($row, $label, \DataContainer $dc, $args)
	{
		$image = 'member';

		$time = \Date::floorToMinute();

		$disabled = $row['start'] !== '' && $row['start'] > $time || $row['stop'] !== '' && $row['stop'] < $time;

		if ($row['disable'] || $disabled)
		{
			$image .= '_';
		}

		$objUsers = \Database::getInstance()
		                    ->prepare("SELECT
                                            tlm.id
                                        FROM
		                                    tl_member tlm, tl_beuseronline_session tls
                                        WHERE
		                                    tlm.id = tls.pid
                                        AND tlm.id = ?
                                        AND tls.tstamp > ?
                                        AND tls.name = ?")
                            ->execute($row['id'], time()-300, 'FE_USER_AUTH');
		if ($objUsers->numRows < 1)
		{
			//offline
			$status = sprintf('', TL_ASSETS_URL, \Backend::getTheme());
		}
		else
		{
			//online
			$status = sprintf('', TL_ASSETS_URL, \Backend::getTheme());
		}

		$args[0] = sprintf('
%s
', TL_ASSETS_URL, \Backend::getTheme(), $image, $disabled ? $image : rtrim($image, '_'), rtrim($image, '_') . '_', $status);

		return $args;
	}

'<img src="%ssystem/themes/%s/icons/invisible.svg" width="16" height="16" alt="Offline" style="padding-left: 18px;">'

'<img src="%ssystem/themes/%s/icons/visible.svg" width="16" height="16" alt="Online" style="padding-left: 18px;">'

Add an image to each record
@param array
@param string
@param DataContainer
@param array
@return string


public static function getSelectOptions($key = 'id', $value = 'title', $where = [])
    {
        $parents = self::find();
        if (!empty($where)) {
            $parents->where($where);
        }
        return \yii\helpers\ArrayHelper::map($parents->all(), $key, $value);
    }

public static function getSelectOptions ( $ key = 'id' , $ value = 'title' , $ where = [ ] ) { $ parents = self :: find ( ) ; if ( ! empty ( $ where ) ) { $ parents -> where ( $ where ) ; } return \ yii \ helpers \ ArrayHelper :: map ( $ parents -> all ( ) , $ key , $ value ) ; }

Return basic select options for the record.
@param string $key
@param string $value
@param array $where
@return array

Return basic select options for the record .


public function listStatus()
    {
        $data = [];

        // create a reflection class to get constants
        $refl = new ReflectionClass(get_called_class());
        $constants = $refl->getConstants();

        // check for status constants (e.g., STATUS_ACTIVE)
        foreach ($constants as $constantName => $constantValue) {

            // add prettified name to dropdown
            if (strpos($constantName, "STATUS_") === 0) {
                $prettyName = str_replace("STATUS_", "", $constantName);
                $prettyName = Inflector::humanize(strtolower($prettyName));
                $data[$constantValue] = $prettyName;
            }
        }

        return $data;
    }

Returns lists of status available
@return array


public function listTypes($type)
    {
        $data = [];
        // create a reflection class to get constants
        $refl = new ReflectionClass(get_called_class());
        $constants = $refl->getConstants();

        foreach ($constants as $constantName => $constantValue) {

            // add prettified name to dropdown
            if (strpos($constantName, $type) === 0) {
                $prettyName = preg_replace('/' . $type . '/', "", $constantName, 1);
                $prettyName = Inflector::humanize(strtolower($prettyName));
                $data[$constantValue] = trim(ucwords($prettyName));
            }
        }

        return $data;
    }

Returns types available
@param $type
@return array


public function getTypeLabel($type, $constId)
    {
        if (!is_null($type)) {
            $array = $this->listTypes($constId);
            if (isset($array[$type])) {
                return $array[$type];
            }
        }

        return false;
    }

public function getTypeLabel ( $ type , $ constId ) { if ( ! is_null ( $ type ) ) { $ array = $ this -> listTypes ( $ constId ) ; if ( isset ( $ array [ $ type ] ) ) { return $ array [ $ type ] ; } } return false ; }

Returns type label
@param $type
@param $constId
@return bool


public function getListingOrderArray()
    {
        $count = static::find()
            ->count();

        $array = [];
        for ($i = 1; $i <= $count; $i++) {
            $array[$i] = $i;
        }

        return $array;
    }

public function getListingOrderArray ( ) { $ count = static :: find ( ) -> count ( ) ; $ array = [ ] ; for ( $ i = 1 ; $ i <= $ count ; $ i ++ ) { $ array [ $ i ] = $ i ; } return $ array ; }

return array of listing order
@return array


public function findReplaceValue()
    {
        if (is_array($this->findText)) {
            //can be array
            $searchReplaceArray = [];
            foreach ($this->findText as $key => $value) {
                $searchReplaceArray[$value] = $this->replaceText;
            }
        } else {
            $searchReplaceArray = [
                $this->findText => $this->replaceText,
            ];
        }

        $this->owner->{$this->attribute} = str_replace(
            array_keys($searchReplaceArray),
            array_values($searchReplaceArray),
            $this->owner->{$this->attribute}
        );
    }

public
function
findReplaceValue
(
)
{
if
(
is_array
(
$
this
->
findText
)
)
{
//can be array
$
searchReplaceArray
=
[
]
;
foreach
(
$
this
->
findText
as
$
key
=>
$
value
)
{
$
searchReplaceArray
[
$
value
]
=
$
this
->
replaceText
;
}
}
else
{
$
searchReplaceArray
=
[
$
this
->
findText
=>
$
this
->
replaceText
,
]
;
}
$
this
->
owner
->
{
$
this
->
attribute
}
=
str_replace
(
array_keys
(
$
searchReplaceArray
)
,
array_values
(
$
searchReplaceArray
)
,
$
this
->
owner
->
{
$
this
->
attribute
}
)
;
}

Find and replace text
Accepts find as string or array


public function next(): void
    {
        if ($this->currentItem instanceof Dropdown) {
            $this->currentDropdownItem = next($this->dropdownItems) ?: null;

            if ($this->currentDropdownItem) {
                return;
            }
        }

        $this->currentItem = next($this->items) ?: null;

        if ($this->currentItem instanceof Dropdown) {
            $this->dropdownItems       = $this->currentItem->items();
            $this->currentDropdownItem = current($this->dropdownItems);
        } else {
            $this->dropdownItems       = [];
            $this->currentDropdownItem = null;
        }
    }

public function next ( ) : void { if ( $ this -> currentItem instanceof Dropdown ) { $ this -> currentDropdownItem = next ( $ this -> dropdownItems ) ? : null ; if ( $ this -> currentDropdownItem ) { return ; } } $ this -> currentItem = next ( $ this -> items ) ? : null ; if ( $ this -> currentItem instanceof Dropdown ) { $ this -> dropdownItems = $ this -> currentItem -> items ( ) ; $ this -> currentDropdownItem = current ( $ this -> dropdownItems ) ; } else { $ this -> dropdownItems = [ ] ; $ this -> currentDropdownItem = null ; } }


public function currentTitle(): array
    {
        if (!$this->currentItem) {
            return [];
        }

        $title = [$this->currentItem->title()];

        if ($this->currentItem instanceof Dropdown && $this->currentDropdownItem) {
            $title[] = $this->currentDropdownItem->title();
        }

        return $title;
    }

public function currentTitle ( ) : array { if ( ! $ this -> currentItem ) { return [ ] ; } $ title = [ $ this -> currentItem -> title ( ) ] ; if ( $ this -> currentItem instanceof Dropdown && $ this -> currentDropdownItem ) { $ title [ ] = $ this -> currentDropdownItem -> title ( ) ; } return $ title ; }

Get the title of the current item.

@return array


public function generateActiveField($attribute)
    {
        $tableSchema = $this->getTableSchema();
        if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
                return "\$form->field(\$model, '$attribute')->passwordInput()";
            } else {
                return "\$form->field(\$model, '$attribute')";
            }
        }
        $column = $tableSchema->columns[$attribute];

        if ($column->name === 'tags') {
            return "\$form->field(\$model, '$attribute')->widget(Select2::classname(), [
            'language' => 'en',
            'options' => [
                'multiple' => true,
                'placeholder' => 'Select a tag ...'
            ],
            'pluginOptions' => [
                'allowClear' => true,
                'tags' => \$tag->listTags(\$model->className()),
            ],
        ])";
        } elseif ($column->type === 'timestamp') {
            return "\$form->field(\$model, '$attribute')->widget(DatePicker::classname(), [
                'options' => [
                    'placeholder' => 'Select date ...',
                ],
                'pluginOptions' => [
                    'format' => 'yyyy-mm-dd',
                    'todayHighlight' => true
                ],
            ])";
        } elseif ($column->phpType === 'boolean' || $column->name === 'active' || $column->name === 'deleted') {
            return "\$form->field(\$model, '$attribute')->widget(SwitchInput::classname(), [
                'pluginOptions' => [
                    'size' => 'small'
                ],
            ])";
        } elseif ($column->type === 'text') {
            return "\$form->field(\$model, '$attribute')->widget(ImperaviWidget::classname())";
        } else {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
                $input = 'passwordInput';
            } else {
                $input = 'textInput';
            }
            if ($column->phpType !== 'string' || $column->size === null) {
                return "\$form->field(\$model, '$attribute')->$input()";
            } else {
                return "\$form->field(\$model, '$attribute')->$input(['maxlength' => $column->size])";
            }
        }
    }

Generates code for active field
@param  string $attribute
@return string


public function make($name, $attributes)
    {
        if (Str::contains($name, '.') || Str::contains($name, '/')) {
            throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
        }

        return $this->drivers[$name] = new Router($name, $attributes);
    }

Register a new resource.

@param  string  $name
@param  mixed  $attributes

@return \Orchestra\Resources\Router

@throws \InvalidArgumentException


public function of($name, $attributes = null)
    {
        if (! isset($this->drivers[$name])) {
            return $this->make($name, $attributes);
        }

        return $this->drivers[$name];
    }

public function of ( $ name , $ attributes = null ) { if ( ! isset ( $ this -> drivers [ $ name ] ) ) { return $ this -> make ( $ name , $ attributes ) ; } return $ this -> drivers [ $ name ] ; }

Get resource by given name, or create a new one.

@param  string  $name
@param  mixed  $attributes

@return \Orchestra\Resources\Router

Get resource by given name or create a new one .


public function call($name, $parameters = [])
    {
        $child = null;

        // Available drivers does not include childs, we should split the
        // name into two (parent.child) where parent would be the name of
        // the resource.
        if (false !== strpos($name, '.')) {
            list($name, $child) = explode('.', $name, 2);
        }

        // When the resources is not available, or register we should
        // return false to indicate this status. This would allow the callee
        // to return 404 abort status.
        if (! isset($this->drivers[$name])) {
            return false;
        }

        return $this->dispatcher->call($this->drivers[$name], $child, $parameters);
    }

Call a resource controller and action.

@param  string  $name
@param  array  $parameters

@return mixed


public function call(Router $driver, $name = null, array $parameters = [])
    {
        $resolver = $this->resolveDispatchDependencies($driver, $name, $parameters);

        // This would cater request to valid resource but pointing to an
        // invalid child. We should show a 404 response to the user on this
        // case.
        if (! $resolver->isValid()) {
            return false;
        }

        return $this->dispatch($driver, $name, $resolver);
    }

Create a new dispatch.

@param  \Orchestra\Resources\Router  $driver
@param  string|null  $name
@param  array  $parameters

@return mixed


public function resolveDispatchDependencies(Router $driver, $name, array $parameters)
    {
        $segments = $this->getNestedParameters($name, $parameters);
        $key      = implode('.', array_keys($segments));
        $uses     = $driver->get('uses');

        if (! is_null($name)) {
            if (isset($driver[$key]) && Str::startsWith($driver[$key], 'resource:')) {
                $uses = $driver[$key];
            } else {
                $uses = (isset($driver[$name]) ? $driver[$name] : null);
            }
        }

        return new Resolver($uses, $this->request->getMethod(), $parameters, $segments);
    }

public function resolveDispatchDependencies ( Router $ driver , $ name , array $ parameters ) { $ segments = $ this -> getNestedParameters ( $ name , $ parameters ) ; $ key = implode ( '.' , array_keys ( $ segments ) ) ; $ uses = $ driver -> get ( 'uses' ) ; if ( ! is_null ( $ name ) ) { if ( isset ( $ driver [ $ key ] ) && Str :: startsWith ( $ driver [ $ key ] , 'resource:' ) ) { $ uses = $ driver [ $ key ] ; } else { $ uses = ( isset ( $ driver [ $ name ] ) ? $ driver [ $ name ] : null ) ; } } return new Resolver ( $ uses , $ this -> request -> getMethod ( ) , $ parameters , $ segments ) ; }

Resolve dispatcher dependencies.

@param  \Orchestra\Resources\Router  $driver
@param  string  $name
@param  array  $parameters

@return \Orchestra\Resources\Resolver


protected function getNestedParameters($name, array $parameters)
    {
        $reserved = ['create', 'show', 'index', 'delete', 'destroy', 'edit'];
        $nested   = [];

        if (($nestedCount = count($parameters)) > 0) {
            $nested = [$name => $parameters[0]];

            for ($index = 1; $index < $nestedCount; $index += 2) {
                $value = null;

                if (($index + 1) < $nestedCount) {
                    $value = $parameters[($index + 1)];
                }

                $key = $parameters[$index];

                ! in_array($key, $reserved) && $nested[$key] = $value;
            }
        }

        return $nested;
    }

protected function getNestedParameters ( $ name , array $ parameters ) { $ reserved = [ 'create' , 'show' , 'index' , 'delete' , 'destroy' , 'edit' ] ; $ nested = [ ] ; if ( ( $ nestedCount = count ( $ parameters ) ) > 0 ) { $ nested = [ $ name => $ parameters [ 0 ] ] ; for ( $ index = 1 ; $ index < $ nestedCount ; $ index += 2 ) { $ value = null ; if ( ( $ index + 1 ) < $ nestedCount ) { $ value = $ parameters [ ( $ index + 1 ) ] ; } $ key = $ parameters [ $ index ] ; ! in_array ( $ key , $ reserved ) && $ nested [ $ key ] = $ value ; } } return $ nested ; }

Find nested parameters from route.

@param  string  $name
@param  array  $parameters

@return array


protected function findRoutableAttributes(Resolver $resolver)
    {
        $type = $resolver->getType();

        if (in_array($type, ['restful', 'resource'])) {
            $method = 'find'.Str::studly($type).'Routable';

            list($action, $parameters) = call_user_func([$this, $method], $resolver);
        } else {
            throw new InvalidArgumentException("Type [{$type}] not implemented.");
        }

        return [$action, $parameters];
    }

protected
function
findRoutableAttributes
(
Resolver
$
resolver
)
{
$
type
=
$
resolver
->
getType
(
)
;
if
(
in_array
(
$
type
,
[
'restful'
,
'resource'
]
)
)
{
$
method
=
'find'
.
Str
::
studly
(
$
type
)
.
'Routable'
;
list
(
$
action
,
$
parameters
)
=
call_user_func
(
[
$
this
,
$
method
]
,
$
resolver
)
;
}
else
{
throw
new
InvalidArgumentException
(
"Type [{$type}] not implemented."
)
;
}
return
[
$
action
,
$
parameters
]
;
}

Find route action and parameters content attributes from either
restful or resources routing.

@param  \Orchestra\Resources\Resolver  $resolver

@return array

@throws \InvalidArgumentException

Find route action and parameters content attributes from either restful or resources routing .


protected function findRestfulRoutable(Resolver $resolver)
    {
        $parameters = $resolver->getParameters();
        $verb       = $resolver->getVerb();

        $action = (count($parameters) > 0 ? array_shift($parameters) : 'index');
        $action = Str::camel("{$verb}_{$action}");

        return [$action, $parameters];
    }

protected function findRestfulRoutable ( Resolver $ resolver ) { $ parameters = $ resolver -> getParameters ( ) ; $ verb = $ resolver -> getVerb ( ) ; $ action = ( count ( $ parameters ) > 0 ? array_shift ( $ parameters ) : 'index' ) ; $ action = Str :: camel ( "{$verb}_{$action}" ) ; return [ $ action , $ parameters ] ; }

Resolve action from restful controller.

@param  \Orchestra\Resources\Resolver  $resolver

@return array

Resolve action from restful controller .


protected function findResourceRoutable(Resolver $resolver)
    {
        $verb      = $resolver->getVerb();
        $swappable = [
            'post'   => 'store',
            'put'    => 'update',
            'patch'  => 'update',
            'delete' => 'destroy',
        ];

        if (! isset($swappable[$verb])) {
            $action = $this->getAlternativeResourceAction($resolver);
        } else {
            $action = $swappable[$verb];
        }

        $parameters = array_values($resolver->getSegments());

        return [$action, $parameters];
    }

protected function findResourceRoutable ( Resolver $ resolver ) { $ verb = $ resolver -> getVerb ( ) ; $ swappable = [ 'post' => 'store' , 'put' => 'update' , 'patch' => 'update' , 'delete' => 'destroy' , ] ; if ( ! isset ( $ swappable [ $ verb ] ) ) { $ action = $ this -> getAlternativeResourceAction ( $ resolver ) ; } else { $ action = $ swappable [ $ verb ] ; } $ parameters = array_values ( $ resolver -> getSegments ( ) ) ; return [ $ action , $ parameters ] ; }

Resolve action from resource controller.

@param  \Orchestra\Resources\Resolver  $resolver

@return array

Resolve action from resource controller .


protected function getAlternativeResourceAction(Resolver $resolver)
    {
        $parameters = $resolver->getParameters();
        $segments   = $resolver->getSegments();

        $last       = array_pop($parameters);
        $resources  = array_keys($segments);

        if (in_array($last, ['edit', 'create', 'delete'])) {
            // Handle all possible GET routing.
            return $last;
        } elseif (! in_array($last, $resources) && ! empty($segments)) {
            return 'show';
        }

        return 'index';
    }

protected
function
getAlternativeResourceAction
(
Resolver
$
resolver
)
{
$
parameters
=
$
resolver
->
getParameters
(
)
;
$
segments
=
$
resolver
->
getSegments
(
)
;
$
last
=
array_pop
(
$
parameters
)
;
$
resources
=
array_keys
(
$
segments
)
;
if
(
in_array
(
$
last
,
[
'edit'
,
'create'
,
'delete'
]
)
)
{
// Handle all possible GET routing.
return
$
last
;
}
elseif
(
!
in_array
(
$
last
,
$
resources
)
&&
!
empty
(
$
segments
)
)
{
return
'show'
;
}
return
'index'
;
}

Get action name.

@param  \Orchestra\Resources\Resolver  $resolver

@return string


protected function dispatch(Router $driver, $name, Resolver $resolver)
    {
        // Next we need to the action and parameters before we can call
        // the destination controller, the resolver would determine both
        // restful and resource controller.
        list($action, $parameters) = $this->findRoutableAttributes($resolver);

        $route = new Route((array) $resolver->getVerb(), "{$driver->get('id')}/{$name}", [
            'uses' => $resolver->getController()."@{$action}",
        ]);

        $route->overrideParameters($parameters);

        // Resolve the controller from container.
        $dispatcher = new ControllerDispatcher($this->router, $this->app);

        return $dispatcher->dispatch($route, $this->request, $resolver->getController(), $action);
    }

Dispatch the resource.

@param  \Orchestra\Resources\Router  $driver
@param  string  $name
@param  \Orchestra\Resources\Resolver  $resolver

@return mixed


public function listAction(Request $request, ?string $method): Response
    {
        $calculator = $this->getCalculator($method);

        $params = $request->request->all();

        $pickupTemplate  = $this->getDefaultTemplate();
        $pickupCurrentId = null;
        $pickupList      = [];
        $currentAddress  = null;

        /** @var PickupCalculatorInterface $calculator */
        if ($calculator instanceof PickupCalculatorInterface) {
            if (!empty($calculator->getPickupTemplate())) {
                $pickupTemplate = $calculator->getPickupTemplate();
            }

            $cart = $this->getCurrentCart();
            if (null !== $cart->getId()) {
                $cart    = $this->getOrderRepository()->findCartForSummary($cart->getId());
                $address = $cart->getShippingAddress();

                $shipment = $cart->getShipments()->current();
                $pickupCurrentId = $shipment->getPickupId();

                foreach ($params as $field => $value) {
                    $setter = 'set' . preg_replace('/_/', '', ucwords($field, '_'));
                    if (method_exists($address, $setter)) {
                        $address->$setter($value);
                    }
                }
                $currentAddress = $address;

                $pickupList = $calculator->getPickupList($address, $cart, $this->getMethod($method));
            }
        }

        $pickup = [
            'pickup' => [
                'current_id' => $pickupCurrentId,
                'list'       => $pickupList,
            ],
            'address'   => $currentAddress,
            'countries' => $this->getAvailableCountries(),
            'index'     => $request->get('index', 0),
            'code'      => $method,
        ];

        return $this->render($pickupTemplate, ['method' => $pickup]);
    }

Display Pickup List

@param Request $request
@param string $method
@return Response|string


protected function getCalculator(string $shippingMethod): CalculatorInterface
    {
        $method = $this->getMethod($shippingMethod);

        if ($method === null) {
            return false;
        }

        /** @var CalculatorInterface $calculator */
        $calculator = $this->calculatorRegistry->get($method->getCalculator());

        return $calculator;
    }

Retrieve Shipping Method Calculator

@param string $shippingMethod
@return CalculatorInterface|bool


protected function getMethod(?string $shippingMethod): ShippingMethod
    {
        /** @var ShippingMethod|null $method */
        $method = $this->getShippingMethodRepository()->findOneBy(['code' => $shippingMethod]);

        if ($method === null) {
            return false;
        }

        return $method;
    }

protected
function
getMethod
(
string
$
shippingMethod
)
:
ShippingMethod
{
/** @var ShippingMethod|null $method */
$
method
=
$
this
->
getShippingMethodRepository
(
)
->
findOneBy
(
[
'code'
=>
$
shippingMethod
]
)
;
if
(
$
method
===
)
{
return
false
;
}
return
$
method
;
}

Retrieve Shipping Method

@param string $shippingMethod
@return ShippingMethod|bool


public function route($name, $uses)
    {
        if (in_array($name, $this->reserved)) {
            throw new InvalidArgumentException("Unable to use reserved keyword [{$name}].");
        } elseif (Str::contains($name, '/')) {
            throw new InvalidArgumentException("Invalid character in resource name [{$name}].");
        }

        $this->attributes['routes'][$name] = $uses;

        return $this;
    }

Map a child resource attributes.

@param  string  $name
@param  string  $uses

@return $this

@throws \InvalidArgumentException


protected function buildResourceSchema($name, $attributes)
    {
        $schema = [
            'name'    => '',
            'uses'    => '',
            'routes'  => [],
            'visible' => true,
        ];

        if (! is_array($attributes)) {
            $uses       = $attributes;
            $attributes = [
                'name' => Str::title($name),
                'uses' => $uses,
            ];
        }

        $attributes['id'] = $name;

        return array_merge($schema, $attributes);
    }

protected function buildResourceSchema ( $ name , $ attributes ) { $ schema = [ 'name' => '' , 'uses' => '' , 'routes' => [ ] , 'visible' => true , ] ; if ( ! is_array ( $ attributes ) ) { $ uses = $ attributes ; $ attributes = [ 'name' => Str :: title ( $ name ) , 'uses' => $ uses , ] ; } $ attributes [ 'id' ] = $ name ; return array_merge ( $ schema , $ attributes ) ; }

Build resource schema.

@param  string  $name
@param  mixed  $attributes

@return array


public function updateShippingAddress(ResourceControllerEvent $event): void
    {
        /** @var Order $order */
        $order = $event->getSubject();

        $pickup = $this->getPickupAddress($order);

        if (!empty($pickup)) {
            $shipping = clone $order->getShippingAddress();
            $shipping->setCompany($pickup['company']);
            $shipping->setStreet($pickup['street_1']);
            $shipping->setCity($pickup['city']);
            $shipping->setPostcode($pickup['postcode']);
            $shipping->setCountryCode($pickup['country']);

            $order->setShippingAddress($shipping);
        }
    }

public
function
updateShippingAddress
(
ResourceControllerEvent
$
event
)
:
void
{
/** @var Order $order */
$
order
=
$
event
->
getSubject
(
)
;
$
pickup
=
$
this
->
getPickupAddress
(
$
order
)
;
if
(
!
empty
(
$
pickup
)
)
{
$
shipping
=
clone
$
order
->
getShippingAddress
(
)
;
$
shipping
->
setCompany
(
$
pickup
[
'company'
]
)
;
$
shipping
->
setStreet
(
$
pickup
[
'street_1'
]
)
;
$
shipping
->
setCity
(
$
pickup
[
'city'
]
)
;
$
shipping
->
setPostcode
(
$
pickup
[
'postcode'
]
)
;
$
shipping
->
setCountryCode
(
$
pickup
[
'country'
]
)
;
$
order
->
setShippingAddress
(
$
shipping
)
;
}
}

Update Shipping Address on cart summary

@param ResourceControllerEvent $event
@return void


protected function call($instance, $route, $method)
    {
        $controller = get_class($instance);

        if (! method_exists($instance, $method)) {
            throw new NotFoundHttpException("Unable to call [{$controller}@{$method}].");
        }

        return parent::call($instance, $route, $method);
    }

Call the given controller instance method.

@param  \Orchestra\Routing\Controller    $instance
@param  \Illuminate\Routing\Route        $route
@param  string                           $method

@return mixed

Call the given controller instance method .


protected function handleIlluminateResponse(IlluminateResponse $content, Closure $callback = null)
    {
        $code     = $content->getStatusCode();
        $response = $content->getContent();

        if ($this->isRenderableResponse($response)) {
            return $response->render();
        } elseif ($this->isNoneHtmlResponse($content)) {
            return $content;
        } elseif ($content->isSuccessful()) {
            return $this->handleResponseCallback($response, $callback);
        }

        return $this->abort($code);
    }

protected function handleIlluminateResponse ( IlluminateResponse $ content , Closure $ callback = null ) { $ code = $ content -> getStatusCode ( ) ; $ response = $ content -> getContent ( ) ; if ( $ this -> isRenderableResponse ( $ response ) ) { return $ response -> render ( ) ; } elseif ( $ this -> isNoneHtmlResponse ( $ content ) ) { return $ content ; } elseif ( $ content -> isSuccessful ( ) ) { return $ this -> handleResponseCallback ( $ response , $ callback ) ; } return $ this -> abort ( $ code ) ; }

Handle Illuminate\Http\Response content.

@param  \Illuminate\Http\Response  $content
@param  \Closure  $callback

@return mixed

@throws \Symfony\Component\HttpKernel\Exception\HttpException
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException

Handle Illuminate \ Http \ Response content .


protected function handleResponseCallback($content, Closure $callback = null)
    {
        if ($callback instanceof Closure) {
            $content = call_user_func($callback, $content);
        }

        if (false === $content) {
            return $this->abort(404);
        } elseif (is_null($content)) {
            return new IlluminateResponse($content, 200);
        }

        return $content;
    }

protected function handleResponseCallback ( $ content , Closure $ callback = null ) { if ( $ callback instanceof Closure ) { $ content = call_user_func ( $ callback , $ content ) ; } if ( false === $ content ) { return $ this -> abort ( 404 ) ; } elseif ( is_null ( $ content ) ) { return new IlluminateResponse ( $ content , 200 ) ; } return $ content ; }

Handle response callback.

@param  mixed  $content
@param  \Closure|null  $callback

@return mixed


protected function abort($code, $message = '', array $headers = [])
    {
        if ($code == 404) {
            throw new NotFoundHttpException($message);
        }

        throw new HttpException($code, $message, null, $headers);
    }

protected function abort ( $ code , $ message = '' , array $ headers = [ ] ) { if ( $ code == 404 ) { throw new NotFoundHttpException ( $ message ) ; } throw new HttpException ( $ code , $ message , null , $ headers ) ; }

Handle abort response.

@param  int  $code
@param  string  $message
@param  array  $headers

@return void

@throws \Symfony\Component\HttpKernel\Exception\HttpException
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException


protected function isNoneHtmlResponse(IlluminateResponse $content)
    {
        $contentType = $content->headers->get('Content-Type');
        $isHtml      = Str::startsWith($contentType, 'text/html');

        return ! is_null($content) && ! $isHtml;
    }

protected function isNoneHtmlResponse ( IlluminateResponse $ content ) { $ contentType = $ content -> headers -> get ( 'Content-Type' ) ; $ isHtml = Str :: startsWith ( $ contentType , 'text/html' ) ; return ! is_null ( $ content ) && ! $ isHtml ; }

Is response none html.

@param  \Illuminate\Http\Response  $content

@return bool


public static function register(string $prefix, array $actions = [], array $options = [])
    {
        $handler = new ErrorHandler();
        $handler->register();

        Yii::$app->set('errorHandler', $handler);

        Yii::$app->controllerMap[$prefix] = [
            'class'         => get_called_class(),
            'actions'       => $actions,
            'optionAliases' => $options
        ];
    }

public static function register ( string $ prefix , array $ actions = [ ] , array $ options = [ ] ) { $ handler = new ErrorHandler ( ) ; $ handler -> register ( ) ; Yii :: $ app -> set ( 'errorHandler' , $ handler ) ; Yii :: $ app -> controllerMap [ $ prefix ] = [ 'class' => get_called_class ( ) , 'actions' => $ actions , 'optionAliases' => $ options ] ; }

Setup for actions and options

@deprecated 1.2.0 No longer recommended, use Bridge::registerGroup() instead

@param string $prefix
@param array  $actions
@param array  $options


public function options($actionID)
    {
        $actionClass   = $this->actions()[$actionID] ?? null;
        $action        = new \ReflectionClass($actionClass);
        $actionOptions = [];

        foreach ($action->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            if (in_array($property->getName(), array_values($this->optionAliases()))) {
                $actionOptions[] = $property->getName();
            }
        }

        return $actionOptions;

    }

public function options ( $ actionID ) { $ actionClass = $ this -> actions ( ) [ $ actionID ] ?? null ; $ action = new \ ReflectionClass ( $ actionClass ) ; $ actionOptions = [ ] ; foreach ( $ action -> getProperties ( \ ReflectionProperty :: IS_PUBLIC ) as $ property ) { if ( in_array ( $ property -> getName ( ) , array_values ( $ this -> optionAliases ( ) ) ) ) { $ actionOptions [ ] = $ property -> getName ( ) ; } } return $ actionOptions ; }

Get options from public Action properties


public function deleteItem($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);
        unset($this->cache[$key]);
        return true;
    }

public function deleteItem ( $ key ) { \ WildWolf \ Cache \ Validator :: validateKey ( $ key ) ; unset ( $ this -> cache [ $ key ] ) ; return true ; }

Removes the item from the pool.

@param string $key
The key to delete.

@throws InvalidArgumentException
If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
MUST be thrown.

@return bool
True if the item was successfully removed. False if there was an error.


public function save(\Psr\Cache\CacheItemInterface $item)
    {
        $key = $item->getKey();
        $val = $item->get();
        if (is_object($val)) {
            $val = clone $val;
        }

        if (!($item instanceof \WildWolf\Cache\CacheItem)) {
            $expires = null;
        } else {
            $expires = $item->expires();
        }

        $this->cache[$key] = [$val, $expires];
        return true;
    }

public function save ( \ Psr \ Cache \ CacheItemInterface $ item ) { $ key = $ item -> getKey ( ) ; $ val = $ item -> get ( ) ; if ( is_object ( $ val ) ) { $ val = clone $ val ; } if ( ! ( $ item instanceof \ WildWolf \ Cache \ CacheItem ) ) { $ expires = null ; } else { $ expires = $ item -> expires ( ) ; } $ this -> cache [ $ key ] = [ $ val , $ expires ] ; return true ; }

Persists a cache item immediately.

@param \Psr\Cache\CacheItemInterface $item
The cache item to save.

@return bool
True if the item was successfully persisted. False if there was an error.


public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = true, $escape = true)
    {
        $this->output->block($messages, $type, $style, $prefix, $padding, $escape);
    }

public
function
block
(
$
messages
,
$
type
=
,
$
style
=
,
$
prefix
=
' '
,
$
padding
=
true
,
$
escape
=
true
)
{
$
this
->
output
->
block
(
$
messages
,
$
type
,
$
style
,
$
prefix
,
$
padding
,
$
escape
)
;
}

Formats a message as a block of text.

@param string|array $messages The message to write in the block
@param string|null  $type     The block type (added in [] on first line)
@param string|null  $style    The style to apply to the whole block
@param string       $prefix   The prefix for the block
@param bool         $padding  Whether to add vertical padding
@param bool         $escape   Whether to escape the message


public function get($key, $default = null)
    {
        \WildWolf\Cache\Validator::validateKey($key);

        if (isset($this->cache[$key])) {
            list($data, $expires) = $this->cache[$key];

            if (null === $expires || (new \DateTime()) < $expires) {
                return $data;
            }

            unset($this->cache[$key]);
        }

        return $default;
    }

public function get ( $ key , $ default = null ) { \ WildWolf \ Cache \ Validator :: validateKey ( $ key ) ; if ( isset ( $ this -> cache [ $ key ] ) ) { list ( $ data , $ expires ) = $ this -> cache [ $ key ] ; if ( null === $ expires || ( new \ DateTime ( ) ) < $ expires ) { return $ data ; } unset ( $ this -> cache [ $ key ] ) ; } return $ default ; }

Fetches a value from the cache.

@param string $key     The unique key of this item in the cache.
@param mixed  $default Default value to return if the key does not exist.

@return mixed The value of the item from the cache, or $default in case of cache miss.

@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if the $key string is not a legal value.


public function set($key, $value, $ttl = null)
    {
        \WildWolf\Cache\Validator::validateKey($key);
        \WildWolf\Cache\Validator::validateTtl($ttl);

        if ($ttl instanceof \DateInterval) {
            $expires = new \DateTime();
            $expires->add($ttl);
        } elseif (is_numeric($ttl)) {
            $expires = new \DateTime('now +' . $ttl . ' seconds');
        } else {
            $expires = null;
        }

        if (is_object($value)) {
            $value = clone $value;
        }

        $this->cache[$key] = [$value, $expires];
        return true;
    }

public
function
set
(
$
key
,
$
value
,
$
ttl
=
)
{
\
WildWolf
\
Cache
\
Validator
::
validateKey
(
$
key
)
;
\
WildWolf
\
Cache
\
Validator
::
validateTtl
(
$
ttl
)
;
if
(
$
ttl
instanceof
\
DateInterval
)
{
$
expires
=
new
\
DateTime
(
)
;
$
expires
->
add
(
$
ttl
)
;
}
elseif
(
is_numeric
(
$
ttl
)
)
{
$
expires
=
new
\
DateTime
(
'now +'
.
$
ttl
.
' seconds'
)
;
}
else
{
$
expires
=
;
}
if
(
is_object
(
$
value
)
)
{
$
value
=
clone
$
value
;
}
$
this
->
cache
[
$
key
]
=
[
$
value
,
$
expires
]
;
return
true
;
}

Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.

@param string                $key   The key of the item to store.
@param mixed                 $value The value of the item to store, must be serializable.
@param null|int|\DateInterval $ttl  Optional. The TTL value of this item. If no value is sent and
the driver supports TTL then the library may set a default value
for it or let the driver take care of that.

@return bool True on success and false on failure.

@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if the $key string is not a legal value.

Persists data in the cache uniquely referenced by a key with an optional expiration TTL time .


public function setMultiple($values, $ttl = null)
    {
        \WildWolf\Cache\Validator::validateIterable($values);
        \WildWolf\Cache\Validator::validateTtl($ttl);

        $result = true;
        foreach ($values as $key => $value) {
            if (is_int($key)) {
                $key = (string)$key;
            }

            $result = $this->set($key, $value, $ttl) && $result;
        }

        return $result;
    }

public function setMultiple ( $ values , $ ttl = null ) { \ WildWolf \ Cache \ Validator :: validateIterable ( $ values ) ; \ WildWolf \ Cache \ Validator :: validateTtl ( $ ttl ) ; $ result = true ; foreach ( $ values as $ key => $ value ) { if ( is_int ( $ key ) ) { $ key = ( string ) $ key ; } $ result = $ this -> set ( $ key , $ value , $ ttl ) && $ result ; } return $ result ; }

Persists a set of key => value pairs in the cache, with an optional TTL.

@param iterable              $values A list of key => value pairs for a multiple-set operation.
@param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
the driver supports TTL then the library may set a default value
for it or let the driver take care of that.

@return bool True on success and false on failure.

@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if $values is neither an array nor a Traversable,
or if any of the $values are not a legal value.

Persists a set of key = > value pairs in the cache with an optional TTL .


public function deleteMultiple($keys)
    {
        \WildWolf\Cache\Validator::validateIterable($keys);

        $result = true;
        foreach ($keys as $key) {
            $result = $this->delete($key) && $result;
        }

        return $result;
    }

public function deleteMultiple ( $ keys ) { \ WildWolf \ Cache \ Validator :: validateIterable ( $ keys ) ; $ result = true ; foreach ( $ keys as $ key ) { $ result = $ this -> delete ( $ key ) && $ result ; } return $ result ; }

Deletes multiple cache items in a single operation.

@param iterable $keys A list of string-based keys to be deleted.

@return bool True if the items were successfully removed. False if there was an error.

@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if $keys is neither an array nor a Traversable,
or if any of the $keys are not a legal value.

Deletes multiple cache items in a single operation .


public function has($key)
    {
        \WildWolf\Cache\Validator::validateKey($key);

        if (isset($this->cache[$key])) {
            list(, $expires) = $this->cache[$key];

            if (null === $expires || (new \DateTime()) < $expires) {
                return true;
            }

            unset($this->cache[$key]);
        }

        return false;
    }

public function has ( $ key ) { \ WildWolf \ Cache \ Validator :: validateKey ( $ key ) ; if ( isset ( $ this -> cache [ $ key ] ) ) { list ( , $ expires ) = $ this -> cache [ $ key ] ; if ( null === $ expires || ( new \ DateTime ( ) ) < $ expires ) { return true ; } unset ( $ this -> cache [ $ key ] ) ; } return false ; }

Determines whether an item is present in the cache.

NOTE: It is recommended that has() is only to be used for cache warming type purposes
and not to be used within your live applications operations for get/set, as this method
is subject to a race condition where your has() will return true and immediately after,
another script can remove it making the state of your app out of date.

@param string $key The cache item key.

@return bool

@throws \Psr\SimpleCache\InvalidArgumentException
MUST be thrown if the $key string is not a legal value.

Determines whether an item is present in the cache .


public function getLabel($caption = NULL)
	{
		$label = clone $this->label;
		$label->for = $this->getHtmlId();

		if (!$label->getHtml()) {
			$label->setText($this->translate($caption === NULL ? $this->caption : $caption));
		}

		return $label;
	}

public function getLabel ( $ caption = NULL ) { $ label = clone $ this -> label ; $ label -> for = $ this -> getHtmlId ( ) ; if ( ! $ label -> getHtml ( ) ) { $ label -> setText ( $ this -> translate ( $ caption === NULL ? $ this -> caption : $ caption ) ) ; } return $ label ; }

Generates label's HTML element.
@param  string
@return Html|string


public function fullPathName($delimiter = '/')
    {
        $parents = $this->parents();

        return implode($delimiter, $parents->pluck('name')->toArray()) . $delimiter . $this->name;
    }

public function fullPathName ( $ delimiter = '/' ) { $ parents = $ this -> parents ( ) ; return implode ( $ delimiter , $ parents -> pluck ( 'name' ) -> toArray ( ) ) . $ delimiter . $ this -> name ; }

Get all category name

@param string $delimiter
@return string


public static function makeTree(\Illuminate\Database\Eloquent\Collection $collection, \Closure $map = null)
    {
        if (is_callable($map)) {
            $collection->map($map);
        }

        $categories = $collection->keyBy('id')->toArray();

        $nodesKey = (new static)->getNodesKey();

        foreach($categories as $cate) {
            $categories[$cate['parent_id']][$nodesKey][] = & $categories[$cate['id']];
        }

        return isset($categories[0][$nodesKey]) ? $categories[0][$nodesKey] : [];
    }

public static function makeTree ( \ Illuminate \ Database \ Eloquent \ Collection $ collection , \ Closure $ map = null ) { if ( is_callable ( $ map ) ) { $ collection -> map ( $ map ) ; } $ categories = $ collection -> keyBy ( 'id' ) -> toArray ( ) ; $ nodesKey = ( new static ) -> getNodesKey ( ) ; foreach ( $ categories as $ cate ) { $ categories [ $ cate [ 'parent_id' ] ] [ $ nodesKey ] [ ] = & $ categories [ $ cate [ 'id' ] ] ; } return isset ( $ categories [ 0 ] [ $ nodesKey ] ) ? $ categories [ 0 ] [ $ nodesKey ] : [ ] ; }

Get tree structures
@param \Illuminate\Database\Eloquent\Collection $collection
@param callable $map
@return array


public function type(string $command, string $style = "fg=white", $speed = 5, string $prepend = "$ ")
    {
        if (!is_null($prepend)) {
            $this->write($prepend);
        }

        $chars = str_split($command);

        foreach ($chars as $char) {

            $this->write(sprintf("<%s>%s</>", $style, $char));

            if (is_int($speed) && $speed > 0) {
                $delay = rand(10000, 1000000) / $speed;
                usleep($delay);
            }
        }

        // delay before new line
        usleep(1000000 / $speed);
        $this->newLine();
    }

public
function
type
(
string
$
command
,
string
$
style
=
"fg=white"
,
$
speed
=
5
,
string
$
prepend
=
"$ "
)
{
if
(
!
is_null
(
$
prepend
)
)
{
$
this
->
write
(
$
prepend
)
;
}
$
chars
=
str_split
(
$
command
)
;
foreach
(
$
chars
as
$
char
)
{
$
this
->
write
(
sprintf
(
"<%s>%s</>"
,
$
style
,
$
char
)
)
;
if
(
is_int
(
$
speed
)
&&
$
speed
>
0
)
{
$
delay
=
rand
(
10000
,
1000000
)
/
$
speed
;
usleep
(
$
delay
)
;
}
}
// delay before new line
usleep
(
1000000
/
$
speed
)
;
$
this
->
newLine
(
)
;
}

Emulate terminal typing

@param string $command
@param string $style
@param int    $speed
@param string|null $prepend


protected function setResourceMembers($resourcePath = null)
    {
        parent::setResourceMembers($resourcePath);

        $this->resource = array_get($this->resourceArray, 0);

        $pos = 1;
        $more = array_get($this->resourceArray, $pos);

        if (!empty($more)) {
            //  This will be the full resource path
            do {
                $this->resource .= '/' . $more;
                $pos++;
                $more = array_get($this->resourceArray, $pos);
            } while (!empty($more));
        }

        return $this;
    }

protected
function
setResourceMembers
(
$
resourcePath
=
)
{
parent
::
setResourceMembers
(
$
resourcePath
)
;
$
this
->
resource
=
array_get
(
$
this
->
resourceArray
,
0
)
;
$
pos
=
1
;
$
more
=
array_get
(
$
this
->
resourceArray
,
$
pos
)
;
if
(
!
empty
(
$
more
)
)
{
//  This will be the full resource path
do
{
$
this
->
resource
.=
'/'
.
$
more
;
$
pos
++
;
$
more
=
array_get
(
$
this
->
resourceArray
,
$
pos
)
;
}
while
(
!
empty
(
$
more
)
)
;
}
return
$
this
;
}

Apply the commonly used REST path members to the class.

@param string $resourcePath

@return $this

Apply the commonly used REST path members to the class .


private function loadPSRClass($class)
    {
        $prefix = $class;
        while (false !== $pos = strrpos($prefix, '\\')) {
            $prefix = substr($class, 0, $pos + 1);
            $relative_class = substr($class, $pos + 1);

            $mapped_file = $this->loadMappedFile($prefix, $relative_class);
            if ($mapped_file) {
                return $mapped_file;
            }
            $prefix = rtrim($prefix, '\\');
        }

        return false;
    }

private function loadPSRClass ( $ class ) { $ prefix = $ class ; while ( false !== $ pos = strrpos ( $ prefix , '\\' ) ) { $ prefix = substr ( $ class , 0 , $ pos + 1 ) ; $ relative_class = substr ( $ class , $ pos + 1 ) ; $ mapped_file = $ this -> loadMappedFile ( $ prefix , $ relative_class ) ; if ( $ mapped_file ) { return $ mapped_file ; } $ prefix = rtrim ( $ prefix , '\\' ) ; } return false ; }

PSR-4

@param string $class
@return bool|string
@throws CoreException


protected function setAccountId($config)
    {
        $config['version'] = '2010-05-08';
        $iam = new IamClient($config);
        $user = $iam->getUser()->get('User');
        $arn = explode(':', array_get($user, 'Arn'));
        $this->accountId = array_get($arn, 4);
    }

protected function setAccountId ( $ config ) { $ config [ 'version' ] = '2010-05-08' ; $ iam = new IamClient ( $ config ) ; $ user = $ iam -> getUser ( ) -> get ( 'User' ) ; $ arn = explode ( ':' , array_get ( $ user , 'Arn' ) ) ; $ this -> accountId = array_get ( $ arn , 4 ) ; }

Sets the AWS account id.

@param $config


static public function translateException(\Exception $exception, $add_msg = null)
    {
        $msg = strval($add_msg) . $exception->getMessage();
        switch (get_class($exception)) {
            case 'Aws\Sns\Exception\AuthorizationErrorException':
            case 'Aws\Sns\Exception\EndpointDisabledException':
            case 'Aws\Sns\Exception\InvalidParameterException':
            case 'Aws\Sns\Exception\PlatformApplicationDisabledException':
            case 'Aws\Sns\Exception\SubscriptionLimitExceededException':
            case 'Aws\Sns\Exception\TopicLimitExceededException':
                return new BadRequestException($msg, $exception->getCode());
            case 'Aws\Sns\Exception\NotFoundException':
                return new NotFoundException($msg, $exception->getCode());
            case 'Aws\Sns\Exception\SnsException':
            case 'Aws\Sns\Exception\InternalErrorException':
                return new InternalServerErrorException($msg, $exception->getCode());
            default:
                return null;
        }
    }

Translates AWS SNS Exceptions to DF Exceptions
If not an AWS SNS Exception, then null is returned.

@param \Exception  $exception
@param string|null $add_msg

@return BadRequestException|InternalServerErrorException|NotFoundException|null

Translates AWS SNS Exceptions to DF Exceptions If not an AWS SNS Exception then null is returned .


public function getConsole(Container $app = null)
    {
        return $this->console ?: (isset($app['console']) ? $app['console'] : new Console());
    }

public function getConsole ( Container $ app = null ) { return $ this -> console ? : ( isset ( $ app [ 'console' ] ) ? $ app [ 'console' ] : new Console ( ) ) ; }

Gets the console application.

@param Container $app
@return Console|null


function execute() {
        $data_to_post = array(
            'apikey'  => $this->apikey,
            'command' => $this->command,
            'params'  => json_encode($this->params)
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, PayPro::$apiUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_to_post);
        curl_setopt($ch, CURLOPT_CAINFO, $this->caBundleFile());

        $body = curl_exec($ch);

        if ($body === false) {
            $errno = curl_errno($ch);
            $message = curl_error($ch);

            curl_close($ch);

            $msg = "Could not connect to the PayPro API - [errno: $errno]: $message";
            throw new Error\Connection($msg);
        }

        curl_close($ch);

        $decodedResponse = json_decode($body, true);

        if (is_null($decodedResponse)) {
            $msg = "The API request returned an error or is invalid: $body";
            throw new Error\InvalidResponse($msg);
        }

        $params = array();
        return $decodedResponse;
    }

Executes the command. Connects with the PayPro API and returns the response.

On correct API calls it will return an array with all the fields.

@throws Error\Connection if the connection can not be established.
@throws Error\InvalidResponse if there is an error with the response.

Executes the command . Connects with the PayPro API and returns the response .


public static function values()
    {
        $class = get_called_class();

        if (!isset(self::$cache[$class])) {
            $reflected = new \ReflectionClass($class);
            self::$cache[$class] = $reflected->getConstants();
        }

        return self::$cache[$class];
    }

public static function values ( ) { $ class = get_called_class ( ) ; if ( ! isset ( self :: $ cache [ $ class ] ) ) { $ reflected = new \ ReflectionClass ( $ class ) ; self :: $ cache [ $ class ] = $ reflected -> getConstants ( ) ; } return self :: $ cache [ $ class ] ; }

Return the names and values of all the constants in the enum

@return array


public function listContainers($include_properties = false)
    {
        $this->checkConnection();

        if (!empty($this->container)) {
            return $this->listResource($include_properties);
        }

        /** @noinspection PhpUndefinedMethodInspection */
        $buckets = $this->blobConn->listBuckets()->get('Buckets');

        $out = [];
        foreach ($buckets as $bucket) {
            $name = rtrim($bucket['Name']);
            $out[] = ['name' => $name, 'path' => $name];
        }

        return $out;
    }

List all containers, just names if noted

@param bool $include_properties If true, additional properties are retrieved

@throws \Exception
@return array


public function updateContainerProperties($container, $properties = [])
    {
        $this->checkConnection();
        try {
            if ($this->blobConn->doesBucketExist($container)) {
                throw new \Exception("No container named '$container'");
            }
        } catch (\Exception $ex) {
            throw new DfException("Failed to update container '$container': " . $ex->getMessage());
        }
    }

Update a container with some properties

@param string $container
@param array  $properties

@throws DfException
@return void


public function blobExists($container = '', $name = '')
    {
        try {
            $this->checkConnection();

            return $this->blobConn->doesObjectExist($container, $name);
        } catch (\Exception $ex) {
            return false;
        }
    }

public function blobExists ( $ container = '' , $ name = '' ) { try { $ this -> checkConnection ( ) ; return $ this -> blobConn -> doesObjectExist ( $ container , $ name ) ; } catch ( \ Exception $ ex ) { return false ; } }

Check if a blob exists

@param  string $container Container name
@param  string $name      Blob name

@return boolean


public function encode(string $iss, string $aud, string $sub, string $expires = null, array $claims = []): string
    {
        $now = new DateTimeImmutable();

        $claims = array_merge($claims, [
            'iss' => $iss,
            'aud' => $aud,
            'sub' => $sub,
            'iat' => $now->getTimestamp(),
            'exp' => $this->expires($now, $expires)
        ]);

        return FirebaseJWT::encode($claims, $this->privateKey, self::ALGO);
    }

public function encode ( string $ iss , string $ aud , string $ sub , string $ expires = null , array $ claims = [ ] ) : string { $ now = new DateTimeImmutable ( ) ; $ claims = array_merge ( $ claims , [ 'iss' => $ iss , 'aud' => $ aud , 'sub' => $ sub , 'iat' => $ now -> getTimestamp ( ) , 'exp' => $ this -> expires ( $ now , $ expires ) ] ) ; return FirebaseJWT :: encode ( $ claims , $ this -> privateKey , self :: ALGO ) ; }

Generate JWT Token using private key

@param string $iss Issuer
@param string $aud Audition
@param string $sub Subject
@param string|null $expires Expiration constraint (example: + 10 days)
@param array $claims Public claims (example: ['user_id' => 10])
@return string Returns JWT token as string
@throws Exception


public function decode(string $token, bool $ignoreExceptions = false): ?array
    {
        try {
            $payload = FirebaseJWT::decode($token, $this->publicKey, [self::ALGO]);

            return json_decode(json_encode($payload), true);
        } catch (Exception $exception) {
            $this->exceptionHandler($exception, $ignoreExceptions);

            return null;
        }
    }

public function decode ( string $ token , bool $ ignoreExceptions = false ) : ? array { try { $ payload = FirebaseJWT :: decode ( $ token , $ this -> publicKey , [ self :: ALGO ] ) ; return json_decode ( json_encode ( $ payload ) , true ) ; } catch ( Exception $ exception ) { $ this -> exceptionHandler ( $ exception , $ ignoreExceptions ) ; return null ; } }

Decode JWT Token using public key

@param string $token JWT Token as string
@param bool $ignoreExceptions If true will ignore any kind of exception and return null
@return array|null Returns payload as array or null if exceptions are ignored
@throws Exception


public function payload(string $token): array
    {
        $segments = $this->segments($token);

        return json_decode(
            FirebaseJWT::urlsafeB64Decode($segments[1]), true
        );
    }

public function payload ( string $ token ) : array { $ segments = $ this -> segments ( $ token ) ; return json_decode ( FirebaseJWT :: urlsafeB64Decode ( $ segments [ 1 ] ) , true ) ; }

Extract payload of jwt token without validations

@param string $token JWT Token as string
@return array Returns payload as array
@throws Exception


protected function segments(string $token): array
    {
        $segments = explode('.', $token);

        if (3 !== count($segments)) {
            throw new Exception("Malformed jwt received.");
        }

        return $segments;
    }

protected
function
segments
(
string
$
token
)
:
array
{
$
segments
=
explode
(
'.'
,
$
token
)
;
if
(
3
!==
count
(
$
segments
)
)
{
throw
new
Exception
(
"Malformed jwt received."
)
;
}
return
$
segments
;
}

Verify the number of segments to assert a valid token

@param string $token
@return array
@throws Exception


protected function expires(DateTimeImmutable $now, string $expires = null)
    {
        return !$expires ? null : $now->modify($expires)->getTimestamp();
    }

protected function expires ( DateTimeImmutable $ now , string $ expires = null ) { return ! $ expires ? null : $ now -> modify ( $ expires ) -> getTimestamp ( ) ; }

Verify expiration contraint and return the timestamp of expiration date.
If null will return null too and token will never expire

@param DateTimeImmutable $now
@param string|null $expires
@return int|null

Verify expiration contraint and return the timestamp of expiration date . If null will return null too and token will never expire


public function createIndex($name, $table, $columns, $unique = false)
    {
        $cols = [];
        if (is_string($columns)) {
            $columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
        }
        foreach ($columns as $col) {
            if (strpos($col, '(') !== false) {
                $cols[] = $col;
            } else {
                $cols[] = $this->quoteColumnName($col);
            }
        }
        if ($unique) {
            return
                'ALTER TABLE ' .
                $this->quoteTableName($table) .
                ' ADD CONSTRAINT ' .
                $this->quoteTableName($name) .
                ' UNIQUE (' .
                implode(', ', $cols) .
                ')';
        } else {
            throw new BadRequestException('Indexes not supported.');
        }
    }

public
function
createIndex
(
$
name
,
$
table
,
$
columns
,
$
unique
=
false
)
{
$
cols
=
[
]
;
if
(
is_string
(
$
columns
)
)
{
$
columns
=
preg_split
(
'/\s*,\s*/'
,
$
columns
,
1
,
PREG_SPLIT_NO_EMPTY
)
;
}
foreach
(
$
columns
as
$
col
)
{
if
(
strpos
(
$
col
,
'('
)
!==
false
)
{
$
cols
[
]
=
$
col
;
}
else
{
$
cols
[
]
=
$
this
->
quoteColumnName
(
$
col
)
;
}
}
if
(
$
unique
)
{
return
'ALTER TABLE '
.
$
this
->
quoteTableName
(
$
table
)
.
' ADD CONSTRAINT '
.
$
this
->
quoteTableName
(
$
name
)
.
' UNIQUE ('
.
implode
(
', '
,
$
cols
)
.
')'
;
}
else
{
throw
new
BadRequestException
(
'Indexes not supported.'
)
;
}
}

Builds a SQL statement for creating a new index.

@param string  $name    the name of the index. The name will be properly quoted by the method.
@param string  $table   the table that the new index will be created for. The table name will be properly quoted
by the method.
@param string  $columns the column(s) that should be included in the index. If there are multiple columns,
please separate them by commas. Each column name will be properly quoted by the method,
unless a parenthesis is found in the name.
@param boolean $unique  whether to add UNIQUE constraint on the created index.
@return string the SQL statement for creating a new index.
@throws BadRequestException

Builds a SQL statement for creating a new index .


public function extractDefault(ColumnSchema $field, $defaultValue)
    {
        if ($defaultValue === 'true') {
            $field->defaultValue = true;
        } elseif ($defaultValue === 'false') {
            $field->defaultValue = false;
        } elseif (0 === stripos($defaultValue, '"identity"')) {
            $field->autoIncrement = true;
        } elseif (preg_match('/^\'(.*)\'::/', $defaultValue, $matches)) {
            parent::extractDefault($field, str_replace("''", "'", $matches[1]));
        } elseif (preg_match('/^(-?\d+(\.\d*)?)(::.*)?$/', $defaultValue, $matches)) {
            parent::extractDefault($field, $matches[1]);
        } else {
            // could be a internal function call like setting uuids
            $field->defaultValue = $defaultValue;
        }
    }

Extracts the default value for the column.
The value is typecasted to correct PHP type.

@param ColumnSchema $field
@param mixed        $defaultValue the default value obtained from metadata

Extracts the default value for the column . The value is typecasted to correct PHP type .


protected static function addPrevButton($sCode) {

        if(self::$iCurrentPage <= self::$arSettings[$sCode.'_button_limit']) {
            return;
        }

        //Get button value
        $sValue = self::getValue($sCode);

        //Get button name
        $sName = self::$arSettings[$sCode.'_button_name'];
        if(isset(self::$arSettings[$sCode.'_button_number']) && self::$arSettings[$sCode.'_button_number']) {
            $sName = $sValue;
        }

        self::$arResult[] = [
            'name' => $sName,
            'value' => $sValue,
            'class' => self::$arSettings[$sCode.'_button_class'],
            'code' => $sCode,
        ];
    }

protected
static
function
addPrevButton
(
$
sCode
)
{
if
(
self
::
$
iCurrentPage
<=
self
::
$
arSettings
[
$
sCode
.
'_button_limit'
]
)
{
return
;
}
//Get button value
$
sValue
=
self
::
getValue
(
$
sCode
)
;
//Get button name
$
sName
=
self
::
$
arSettings
[
$
sCode
.
'_button_name'
]
;
if
(
isset
(
self
::
$
arSettings
[
$
sCode
.
'_button_number'
]
)
&&
self
::
$
arSettings
[
$
sCode
.
'_button_number'
]
)
{
$
sName
=
$
sValue
;
}
self
::
$
arResult
[
]
=
[
'name'
=>
$
sName
,
'value'
=>
$
sValue
,
'class'
=>
self
::
$
arSettings
[
$
sCode
.
'_button_class'
]
,
'code'
=>
$
sCode
,
]
;
}

Add previous button
@param string $sCode


protected static function addNextButton($sCode) {

        if(self::$iCurrentPage + self::$arSettings[$sCode.'_button_limit'] > self::$iTotalCountPages) {
            return;
        }

        //Get button value
        $sValue = self::getValue($sCode);

        //Get button name
        $sName = self::$arSettings[$sCode.'_button_name'];
        if(isset(self::$arSettings[$sCode.'_button_number']) && self::$arSettings[$sCode.'_button_number']) {
            $sName = $sValue;
        }

        self::$arResult[] = [
            'name' => $sName,
            'value' => $sValue,
            'class' => self::$arSettings[$sCode.'_button_class'],
            'code' => $sCode,
        ];
    }

protected
static
function
addNextButton
(
$
sCode
)
{
if
(
self
::
$
iCurrentPage
+
self
::
$
arSettings
[
$
sCode
.
'_button_limit'
]
>
self
::
$
iTotalCountPages
)
{
return
;
}
//Get button value
$
sValue
=
self
::
getValue
(
$
sCode
)
;
//Get button name
$
sName
=
self
::
$
arSettings
[
$
sCode
.
'_button_name'
]
;
if
(
isset
(
self
::
$
arSettings
[
$
sCode
.
'_button_number'
]
)
&&
self
::
$
arSettings
[
$
sCode
.
'_button_number'
]
)
{
$
sName
=
$
sValue
;
}
self
::
$
arResult
[
]
=
[
'name'
=>
$
sName
,
'value'
=>
$
sValue
,
'class'
=>
self
::
$
arSettings
[
$
sCode
.
'_button_class'
]
,
'code'
=>
$
sCode
,
]
;
}


protected static function getValue($sCode) {

        switch($sCode) {
            case self::FIRST_BUTTON_CODE:
                return 1;
            case self::FIRST_MORE_BUTTON_CODE:
                return null;
            case self::PREV_BUTTON_CODE:
                $iValue = self::$iCurrentPage - 1;
                if($iValue  < 1) {
                    $iValue = 1;
                }

                return $iValue;
            case self::PREV_MORE_BUTTON_CODE:
                return null;
            case self::NEXT_MORE_BUTTON_CODE:
                return null;
            case self::NEXT_BUTTON_CODE:
                $iValue = self::$iCurrentPage + 1;
                if($iValue > self::$iTotalCountPages) {
                    $iValue = self::$iTotalCountPages;
                }

                return $iValue;
            case self::LAST_MORE_BUTTON_CODE:
                return null;
            case self::LAST_BUTTON_CODE:
                return self::$iTotalCountPages;
        }

        return null;
    }

protected static function getValue ( $ sCode ) { switch ( $ sCode ) { case self :: FIRST_BUTTON_CODE : return 1 ; case self :: FIRST_MORE_BUTTON_CODE : return null ; case self :: PREV_BUTTON_CODE : $ iValue = self :: $ iCurrentPage - 1 ; if ( $ iValue < 1 ) { $ iValue = 1 ; } return $ iValue ; case self :: PREV_MORE_BUTTON_CODE : return null ; case self :: NEXT_MORE_BUTTON_CODE : return null ; case self :: NEXT_BUTTON_CODE : $ iValue = self :: $ iCurrentPage + 1 ; if ( $ iValue > self :: $ iTotalCountPages ) { $ iValue = self :: $ iTotalCountPages ; } return $ iValue ; case self :: LAST_MORE_BUTTON_CODE : return null ; case self :: LAST_BUTTON_CODE : return self :: $ iTotalCountPages ; } return null ; }

Get page button value
@param string $sCode
@return int|null


public static function reveal($object)
    {
        if ($object instanceof RecordInterface) {
            return $object;
        } elseif ($object instanceof JsonSerializable) {
            return $object->jsonSerialize();
        } elseif ($object instanceof ArrayObject) {
            return $object->getArrayCopy();
        } elseif ($object instanceof Traversable) {
            return iterator_to_array($object);
        }

        return $object;
    }

public static function reveal ( $ object ) { if ( $ object instanceof RecordInterface ) { return $ object ; } elseif ( $ object instanceof JsonSerializable ) { return $ object -> jsonSerialize ( ) ; } elseif ( $ object instanceof ArrayObject ) { return $ object -> getArrayCopy ( ) ; } elseif ( $ object instanceof Traversable ) { return iterator_to_array ( $ object ) ; } return $ object ; }

Method which reveals the true value of an object if it has a known
interface. Note this resolves also all Traversable instances to an array

@param mixed $object
@return mixed

Method which reveals the true value of an object if it has a known interface . Note this resolves also all Traversable instances to an array


public static function isObject($value)
    {
        return $value instanceof RecordInterface || $value instanceof \stdClass || (is_array($value) && CurveArray::isAssoc($value));
    }

public static function isObject ( $ value ) { return $ value instanceof RecordInterface || $ value instanceof \ stdClass || ( is_array ( $ value ) && CurveArray :: isAssoc ( $ value ) ) ; }

Checks whether a value is an object type

@param mixed $value
@return boolean


public static function isEmpty($value)
    {
        if (empty($value)) {
            return true;
        } elseif ($value instanceof \stdClass) {
            return count((array) $value) === 0;
        } elseif ($value instanceof RecordInterface) {
            return count($value->getProperties()) === 0;
        }

        return false;
    }

public static function isEmpty ( $ value ) { if ( empty ( $ value ) ) { return true ; } elseif ( $ value instanceof \ stdClass ) { return count ( ( array ) $ value ) === 0 ; } elseif ( $ value instanceof RecordInterface ) { return count ( $ value -> getProperties ( ) ) === 0 ; } return false ; }

Checks whether a value is empty

@param mixed $value
@return boolean


public static function toRecord($data, RecordInterface $root = null)
    {
        $visitor   = new RecordSerializeVisitor($root);
        $traverser = new GraphTraverser();
        $traverser->traverse($data, $visitor);

        return $visitor->getObject();
    }

public static function toRecord ( $ data , RecordInterface $ root = null ) { $ visitor = new RecordSerializeVisitor ( $ root ) ; $ traverser = new GraphTraverser ( ) ; $ traverser -> traverse ( $ data , $ visitor ) ; return $ visitor -> getObject ( ) ; }

Transforms an arbitrary data structure into a record graph

@param mixed $data
@param \PSX\Record\RecordInterface $root
@return \PSX\Record\RecordInterface


private function parseResponse($data, $op)
    {
        $arr = array();
        $xml = new \SimpleXMLElement($data);
        $xml = $xml->xpath('/soap:Envelope/soap:Body');
        $xml = $xml[0];
        $data = json_decode(json_encode($xml));
        $opResponse = $op . 'Response';
        $opResult = $op . 'Result';
        $arr = $this->object2array($data->$opResponse->$opResult);
        return $arr;
    }

private function parseResponse ( $ data , $ op ) { $ arr = array ( ) ; $ xml = new \ SimpleXMLElement ( $ data ) ; $ xml = $ xml -> xpath ( '/soap:Envelope/soap:Body' ) ; $ xml = $ xml [ 0 ] ; $ data = json_decode ( json_encode ( $ xml ) ) ; $ opResponse = $ op . 'Response' ; $ opResult = $ op . 'Result' ; $ arr = $ this -> object2array ( $ data -> $ opResponse -> $ opResult ) ; return $ arr ; }

Parse the transaction response

@return array


public function getConfigurator(string $name): DatagridConfiguratorInterface
    {
        if (!isset($this->configurators[$name])) {
            $configurator = null;

            if (isset($this->lazyConfigurators[$name])) {
                $configurator = $this->lazyConfigurators[$name]();
            }

            if (!$configurator) {
                // Support fully-qualified class names.
                if (!class_exists($name) || !in_array(DatagridConfiguratorInterface::class, class_implements($name), true)) {
                    throw new InvalidArgumentException(sprintf('Could not load datagrid configurator "%s"', $name));
                }

                $configurator = new $name();
            }

            $this->configurators[$name] = $configurator;
        }

        return $this->configurators[$name];
    }

Returns a DatagridConfigurator by name.

@param string $name The name of the datagrid configurator

@throws InvalidArgumentException if the configurator can not be retrieved

@return DatagridConfiguratorInterface

Returns a DatagridConfigurator by name .


public function hasConfigurator(string $name): bool
    {
        if (isset($this->configurators[$name])) {
            return true;
        }

        if (isset($this->lazyConfigurators[$name])) {
            return true;
        }

        return class_exists($name) && in_array(DatagridConfiguratorInterface::class, class_implements($name), true);
    }

public function hasConfigurator ( string $ name ) : bool { if ( isset ( $ this -> configurators [ $ name ] ) ) { return true ; } if ( isset ( $ this -> lazyConfigurators [ $ name ] ) ) { return true ; } return class_exists ( $ name ) && in_array ( DatagridConfiguratorInterface :: class , class_implements ( $ name ) , true ) ; }

Returns whether the given DatagridConfigurator is supported.

@param string $name The name of the datagrid configurator

@return bool

Returns whether the given DatagridConfigurator is supported .


public function getWriterClassNameByFormat($format)
    {
        $format = strtolower($format);
        foreach ($this->writers as $writer) {
            $class = get_class($writer);
            $name  = strtolower(substr($class, strrpos($class, '\\') + 1));

            if ($name == $format) {
                return $class;
            }
        }

        return null;
    }

public function getWriterClassNameByFormat ( $ format ) { $ format = strtolower ( $ format ) ; foreach ( $ this -> writers as $ writer ) { $ class = get_class ( $ writer ) ; $ name = strtolower ( substr ( $ class , strrpos ( $ class , '\\' ) + 1 ) ) ; if ( $ name == $ format ) { return $ class ; } } return null ; }

Returns a writer class by the class short name

@param string $format
@return string|null


protected function getWriterFromContentNegotiation(MediaType $contentType, array $supportedWriter = null)
    {
        if (empty($this->contentNegotiation)) {
            return null;
        }

        foreach ($this->contentNegotiation as $acceptedContentType => $writerClass) {
            if ($supportedWriter !== null && !in_array($writerClass, $supportedWriter)) {
                continue;
            }

            $acceptedContentType = new MediaType($acceptedContentType);

            if ($acceptedContentType->match($contentType)) {
                $writer = $this->getWriterByInstance($writerClass);

                if ($writer !== null) {
                    return $writer;
                }
            }
        }

        return null;
    }

protected function getWriterFromContentNegotiation ( MediaType $ contentType , array $ supportedWriter = null ) { if ( empty ( $ this -> contentNegotiation ) ) { return null ; } foreach ( $ this -> contentNegotiation as $ acceptedContentType => $ writerClass ) { if ( $ supportedWriter !== null && ! in_array ( $ writerClass , $ supportedWriter ) ) { continue ; } $ acceptedContentType = new MediaType ( $ acceptedContentType ) ; if ( $ acceptedContentType -> match ( $ contentType ) ) { $ writer = $ this -> getWriterByInstance ( $ writerClass ) ; if ( $ writer !== null ) { return $ writer ; } } } return null ; }

Returns the fitting writer according to the content negotiation. If no
fitting writer could be found null gets returned

@param \PSX\Http\MediaType $contentType
@param array $supportedWriter
@return \PSX\Data\WriterInterface

Returns the fitting writer according to the content negotiation . If no fitting writer could be found null gets returned


public function transform($dateTime)
    {
        if (null === $dateTime) {
            return '';
        }

        if (!$dateTime instanceof \DateTime) {
            throw new TransformationFailedException('Expected a \DateTime.');
        }

        // convert time to UTC before passing it to the formatter
        $dateTime = clone $dateTime;

        if ('UTC' !== $this->inputTimezone) {
            $dateTime->setTimezone(new \DateTimeZone('UTC'));
        }

        $value = $this->getIntlDateFormatter()->format((int) $dateTime->format('U'));

        if (intl_get_error_code() != 0) {
            throw new TransformationFailedException(intl_get_error_message());
        }

        return $value;
    }

Transforms a normalized date into a localized date string.

@param \DateTime $dateTime Normalized date

@throws TransformationFailedException If the given value is not an instance
of \DateTime or if the date could not
be transformed

@return string|array Localized date string/array

Transforms a normalized date into a localized date string .


public function init(DatagridInterface $datagrid)
    {
        if (null === $data = $datagrid->getData()) {
            throw new InvalidArgumentException('No data provided for the view.');
        }

        $columns = $datagrid->getColumns();

        foreach ($columns as $column) {
            $this->columns[$column->getName()] = $column->createHeaderView($this);
        }

        if (!isset($this->vars['row_vars'])) {
            $this->vars['row_vars'] = [];
        }

        foreach ($data as $id => $value) {
            $this->rows[$id] = $row = new DatagridRowView($this, $columns, $value, $id);
            $row->vars = $this->vars['row_vars'];
        }
    }

public
function
init
(
DatagridInterface
$
datagrid
)
{
if
(
===
$
data
=
$
datagrid
->
getData
(
)
)
{
throw
new
InvalidArgumentException
(
'No data provided for the view.'
)
;
}
$
columns
=
$
datagrid
->
getColumns
(
)
;
foreach
(
$
columns
as
$
column
)
{
$
this
->
columns
[
$
column
->
getName
(
)
]
=
$
column
->
createHeaderView
(
$
this
)
;
}
if
(
!
isset
(
$
this
->
vars
[
'row_vars'
]
)
)
{
$
this
->
vars
[
'row_vars'
]
=
[
]
;
}
foreach
(
$
data
as
$
id
=>
$
value
)
{
$
this
->
rows
[
$
id
]
=
$
row
=
new
DatagridRowView
(
$
this
,
$
columns
,
$
value
,
$
id
)
;
$
row
->
vars
=
$
this
->
vars
[
'row_vars'
]
;
}
}


public function read($schema, Payload $payload, SchemaVisitorInterface $visitor = null)
    {
        $data   = $this->parse($payload);
        $schema = $this->getSchema($schema);

        if ($visitor === null) {
            $visitor = new TypeVisitor();
        }

        return $this->traverser->traverse(
            $data,
            $schema,
            $visitor
        );
    }

public function read ( $ schema , Payload $ payload , SchemaVisitorInterface $ visitor = null ) { $ data = $ this -> parse ( $ payload ) ; $ schema = $ this -> getSchema ( $ schema ) ; if ( $ visitor === null ) { $ visitor = new TypeVisitor ( ) ; } return $ this -> traverser -> traverse ( $ data , $ schema , $ visitor ) ; }

Tries to read the provided payload with a fitting reader. The reader
depends on the content type of the payload or on the reader type if
explicit specified. Then we validate the data according to the provided
schema

@param string $schema
@param \PSX\Data\Payload $payload
@param \PSX\Schema\VisitorInterface $visitor
@return mixed
@throws \PSX\Data\InvalidDataException
@throws \PSX\Http\Exception\UnsupportedMediaTypeException

Tries to read the provided payload with a fitting reader . The reader depends on the content type of the payload or on the reader type if explicit specified . Then we validate the data according to the provided schema


public function parse(Payload $payload)
    {
        $reader = $this->getReader($payload->getContentType(), $payload->getRwType(), $payload->getRwSupported());
        $data   = $reader->read($payload->getData());

        $transformer = $payload->getTransformer();

        if ($transformer === null) {
            $transformer = $this->getDefaultTransformer($payload->getContentType());
        }

        if ($transformer instanceof TransformerInterface) {
            $data = $transformer->transform($data);
        }

        return $data;
    }

public function parse ( Payload $ payload ) { $ reader = $ this -> getReader ( $ payload -> getContentType ( ) , $ payload -> getRwType ( ) , $ payload -> getRwSupported ( ) ) ; $ data = $ reader -> read ( $ payload -> getData ( ) ) ; $ transformer = $ payload -> getTransformer ( ) ; if ( $ transformer === null ) { $ transformer = $ this -> getDefaultTransformer ( $ payload -> getContentType ( ) ) ; } if ( $ transformer instanceof TransformerInterface ) { $ data = $ transformer -> transform ( $ data ) ; } return $ data ; }

Parses the payload and returns the data in a normalized format

@param \PSX\Data\Payload $payload
@return \stdClass
@throws StatusCode\UnsupportedMediaTypeException


public function write(Payload $payload)
    {
        $data   = $payload->getData();
        $data   = $this->transform($data);
        $writer = $this->getWriter($payload->getContentType(), $payload->getRwType(), $payload->getRwSupported());

        return $writer->write($data);
    }

public function write ( Payload $ payload ) { $ data = $ payload -> getData ( ) ; $ data = $ this -> transform ( $ data ) ; $ writer = $ this -> getWriter ( $ payload -> getContentType ( ) , $ payload -> getRwType ( ) , $ payload -> getRwSupported ( ) ) ; return $ writer -> write ( $ data ) ; }

Writes the payload with a fitting writer and returns the result as
string. The writer depends on the content type of the payload or on the
writer type if explicit specified

@param \PSX\Data\Payload $payload
@return string
@throws \PSX\Data\InvalidDataException
@throws \PSX\Http\Exception\NotAcceptableException

Writes the payload with a fitting writer and returns the result as string . The writer depends on the content type of the payload or on the writer type if explicit specified


public function getReader($contentType, $readerType = null, array $supportedReader = null)
    {
        if ($readerType === null) {
            $reader = $this->config->getReaderFactory()->getReaderByContentType($contentType, $supportedReader);
        } else {
            $reader = $this->config->getReaderFactory()->getReaderByInstance($readerType);
        }

        if ($reader === null) {
            $reader = $this->config->getReaderFactory()->getDefaultReader($supportedReader);
        }

        if (!$reader instanceof ReaderInterface) {
            throw new StatusCode\UnsupportedMediaTypeException('Could not find fitting data reader');
        }

        return $reader;
    }

public
function
getReader
(
$
contentType
,
$
readerType
=
,
array
$
supportedReader
=
)
{
if
(
$
readerType
===
)
{
$
reader
=
$
this
->
config
->
getReaderFactory
(
)
->
getReaderByContentType
(
$
contentType
,
$
supportedReader
)
;
}
else
{
$
reader
=
$
this
->
config
->
getReaderFactory
(
)
->
getReaderByInstance
(
$
readerType
)
;
}
if
(
$
reader
===
)
{
$
reader
=
$
this
->
config
->
getReaderFactory
(
)
->
getDefaultReader
(
$
supportedReader
)
;
}
if
(
!
$
reader
instanceof
ReaderInterface
)
{
throw
new
StatusCode
\
UnsupportedMediaTypeException
(
'Could not find fitting data reader'
)
;
}
return
$
reader
;
}

Returns a fitting reader for the given content type or throws an
unsupported media exception. It is also possible to explicit select a
reader by providing the class name as reader type.

@param string $contentType
@param string $readerType
@param array $supportedReader
@return \PSX\Data\ReaderInterface

Returns a fitting reader for the given content type or throws an unsupported media exception . It is also possible to explicit select a reader by providing the class name as reader type .


public function getWriter($contentType, $writerType = null, array $supportedWriter = null)
    {
        if ($writerType === null) {
            $writer = $this->config->getWriterFactory()->getWriterByContentType($contentType, $supportedWriter);
        } else {
            $writer = $this->config->getWriterFactory()->getWriterByInstance($writerType);
        }

        if ($writer === null) {
            $writer = $this->config->getWriterFactory()->getDefaultWriter($supportedWriter);
        }

        if (!$writer instanceof WriterInterface) {
            throw new StatusCode\NotAcceptableException('Could not find fitting data writer');
        }

        return $writer;
    }

public
function
getWriter
(
$
contentType
,
$
writerType
=
,
array
$
supportedWriter
=
)
{
if
(
$
writerType
===
)
{
$
writer
=
$
this
->
config
->
getWriterFactory
(
)
->
getWriterByContentType
(
$
contentType
,
$
supportedWriter
)
;
}
else
{
$
writer
=
$
this
->
config
->
getWriterFactory
(
)
->
getWriterByInstance
(
$
writerType
)
;
}
if
(
$
writer
===
)
{
$
writer
=
$
this
->
config
->
getWriterFactory
(
)
->
getDefaultWriter
(
$
supportedWriter
)
;
}
if
(
!
$
writer
instanceof
WriterInterface
)
{
throw
new
StatusCode
\
NotAcceptableException
(
'Could not find fitting data writer'
)
;
}
return
$
writer
;
}

Returns a fitting writer for the given content type or throws an not
acceptable exception. It is also possible to explicit select a writer by
providing the class name as writer type.

@param string $contentType
@param string $writerType
@param array $supportedWriter
@return \PSX\Data\WriterInterface

Returns a fitting writer for the given content type or throws an not acceptable exception . It is also possible to explicit select a writer by providing the class name as writer type .


public function _before(\Codeception\TestCase $test)
    {
        $this->initializeLaravel();

        if ($this->app['db'] && $this->config['cleanup']) {
            $this->app['db']->beginTransaction();
        }
    }

public function _before ( \ Codeception \ TestCase $ test ) { $ this -> initializeLaravel ( ) ; if ( $ this -> app [ 'db' ] && $ this -> config [ 'cleanup' ] ) { $ this -> app [ 'db' ] -> beginTransaction ( ) ; } }

Before hook.

@param \Codeception\TestCase $test
@throws ModuleConfig


public function _after(\Codeception\TestCase $test)
    {
        if ($this->app['db'] && $this->config['cleanup']) {
            $this->app['db']->rollback();
        }

        if ($this->app['auth']) {
            $this->app['auth']->logout();
        }

        if ($this->app['cache']) {
            $this->app['cache']->flush();
        }

        if ($this->app['session']) {
            $this->app['session']->flush();
        }

        // disconnect from DB to prevent "Too many connections" issue
        if ($this->app['db']) {
            $this->app['db']->disconnect();
        }
    }

After hook.

@param \Codeception\TestCase $test


public function _afterStep(\Codeception\Step $step)
    {
        \Illuminate\Support\Facades\Facade::clearResolvedInstances();

        parent::_afterStep($step);
    }

public function _afterStep ( \ Codeception \ Step $ step ) { \ Illuminate \ Support \ Facades \ Facade :: clearResolvedInstances ( ) ; parent :: _afterStep ( $ step ) ; }

After step hook.

@param \Codeception\Step $step


protected function initializeLaravel()
    {
        $this->app = $this->bootApplication();
        $this->app->instance('request', new Request());
        $this->client = new LaravelConnector($this->app);
        $this->client->followRedirects(true);
    }

protected function initializeLaravel ( ) { $ this -> app = $ this -> bootApplication ( ) ; $ this -> app -> instance ( 'request' , new Request ( ) ) ; $ this -> client = new LaravelConnector ( $ this -> app ) ; $ this -> client -> followRedirects ( true ) ; }

Initialize the Laravel framework.

@throws ModuleConfig


protected function bootApplication()
    {
        $projectDir = explode($this->config['packages'], \Codeception\Configuration::projectDir())[0];
        $projectDir .= $this->config['root'];
        require $projectDir . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';

        \Illuminate\Support\ClassLoader::register();

        $bootstrapFile = $projectDir . $this->config['bootstrap'];

        if (! file_exists($bootstrapFile)) {
            throw new ModuleConfig(
                $this, "Laravel bootstrap file not found in $bootstrapFile.\nPlease provide a valid path to it using 'bootstrap' config param. "
            );
        }

        $app = require $bootstrapFile;
        $app->loadEnvironmentFrom($this->config['environment_file']);

        return $app;
    }

Boot the Laravel application object.

@return \Illuminate\Foundation\Application
@throws \Codeception\Exception\ModuleConfig


public function amOnRoute($route, $params = [])
    {
        $domain = $this->app['routes']->getByName($route)->domain();
        $absolute = ! is_null($domain);

        $url = $this->app['url']->route($route, $params, $absolute);
        $this->amOnPage($url);
    }

public function amOnRoute ( $ route , $ params = [ ] ) { $ domain = $ this -> app [ 'routes' ] -> getByName ( $ route ) -> domain ( ) ; $ absolute = ! is_null ( $ domain ) ; $ url = $ this -> app [ 'url' ] -> route ( $ route , $ params , $ absolute ) ; $ this -> amOnPage ( $ url ) ; }

Opens web page using route name and parameters.

```php
<?php
$I->amOnRoute('posts.create');
?>
```

@param $route
@param array $params

Opens web page using route name and parameters .


public function amOnAction($action, $params = [])
    {
        $namespacedAction = $this->actionWithNamespace($action);

        $domain = $this->app['routes']->getByAction($namespacedAction)->domain();
        $absolute = ! is_null($domain);

        $url = $this->app['url']->action($action, $params, $absolute);
        $this->amOnPage($url);
    }

public function amOnAction ( $ action , $ params = [ ] ) { $ namespacedAction = $ this -> actionWithNamespace ( $ action ) ; $ domain = $ this -> app [ 'routes' ] -> getByAction ( $ namespacedAction ) -> domain ( ) ; $ absolute = ! is_null ( $ domain ) ; $ url = $ this -> app [ 'url' ] -> action ( $ action , $ params , $ absolute ) ; $ this -> amOnPage ( $ url ) ; }

Opens web page by action name

```php
<?php
$I->amOnAction('PostsController@index');
?>
```

@param $action
@param array $params


protected function actionWithNamespace($action)
    {
        $rootNamespace = $this->getRootControllerNamespace();

        if ($rootNamespace && ! (strpos($action, '\\') === 0)) {
            return $rootNamespace . '\\' . $action;
        } else {
            return trim($action, '\\');
        }
    }

protected function actionWithNamespace ( $ action ) { $ rootNamespace = $ this -> getRootControllerNamespace ( ) ; if ( $ rootNamespace && ! ( strpos ( $ action , '\\' ) === 0 ) ) { return $ rootNamespace . '\\' . $ action ; } else { return trim ( $ action , '\\' ) ; } }

Normalize an action to full namespaced action.

@param string $action
@return string

Normalize an action to full namespaced action .