protected function getActionsColumn($roleId, $canEditRole, $canDeleteRole)
    {

        return function ($row) use($roleId, $canEditRole, $canDeleteRole) {

            $btns = [];
            $html = app('html');
            if ($canEditRole) {
                array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/edit"), trans('antares/acl::title.edit_details'), ['data-icon' => 'edit'])));
                array_push($btns, $html->create('li', $html->link(handles("antares::acl/index/roles/{$row->id}/acl"), trans('antares/acl::title.acl_rules'), ['data-icon' => 'accounts-alt'])));
            }
            if ($row->id !== $roleId and $canDeleteRole) {

                $url = handles("antares::acl/index/roles/{$row->id}/delete", ['csrf' => true]);

                $class           = 'triggerable confirm';
                $dataTitle       = trans('Are you sure?');
                $dataDescription = trans('antares/acl::global.deleteing_role', ['name' => $row->name]);

                if ($row->users->count()) {
                    publish('acl', ['js/delete-group-denied.js']);
                    $url             = '#';
                    $class           = 'bindable delete-group-denied';
                    $dataTitle       = trans('This action is not allowed');
                    $dataDescription = trans('There are users attached to this group. Only empty groups can be removed.');
                }

                array_push($btns, $html->create('li', $html->link($url, trans('Delete'), [
                                    'class'            => $class,
                                    'data-icon'        => 'delete',
                                    'data-title'       => $dataTitle,
                                    'data-description' => $dataDescription
                ])));
            }
            if (empty($btns)) {
                return '';
            }
            $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $btns)))), ['class' => 'mass-actions-menu'])->get();
            return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get();
        };
    }

prepare datatable row actions

@param mixed $roleId
@param boolean $canEditRole
@param boolean $canDeleteRole
@return callable


public function assignToUser(User $user)
    {
        if ($this->belongsToUser($user)) {
            return true;
        }
        $this->users()->attach($user->id);
        return true;
    }

public function assignToUser ( User $ user ) { if ( $ this -> belongsToUser ( $ user ) ) { return true ; } $ this -> users ( ) -> attach ( $ user -> id ) ; return true ; }

Assign Role to User

@param User $user

@return bool


public static function isSuccessful($code)
    {
        switch($code) {
            case self::HTTP_OK:
            case self::HTTP_CREATED:
            case self::HTTP_ACCEPTED:
            case self::HTTP_NONAUTHORITATIVE_INFORMATION:
            case self::HTTP_NO_CONTENT:
            case self::HTTP_RESET_CONTENT:
            case self::HTTP_PARTIAL_CONTENT:
                return true;
            default:
                return false;
        }
    }

public static function isSuccessful ( $ code ) { switch ( $ code ) { case self :: HTTP_OK : case self :: HTTP_CREATED : case self :: HTTP_ACCEPTED : case self :: HTTP_NONAUTHORITATIVE_INFORMATION : case self :: HTTP_NO_CONTENT : case self :: HTTP_RESET_CONTENT : case self :: HTTP_PARTIAL_CONTENT : return true ; default : return false ; } }

Checks whether a status code can be considered successful.

@param $code
@return bool

Checks whether a status code can be considered successful .


public function getCurrentTemplateName()
    {
        if (!($currentTemplate = basename((string) Registry::getRequest()->getRequestEscapedParameter('tpl')))) {
            // in case template was not defined in request
            $currentTemplate = Registry::getConfig()->getActiveView()->getTemplateName();
        }

        return $currentTemplate;
    }

Returns current controller template name.

@return string

Returns current controller template name .


public function form(Eloquent $model = null)
    {
        $this->breadcrumb->onRoleCreateOREdit($model);
        return new RoleForm($model);
    }

public function form ( Eloquent $ model = null ) { $ this -> breadcrumb -> onRoleCreateOREdit ( $ model ) ; return new RoleForm ( $ model ) ; }

View form generator for Antares\Model\Role.

@param  \Antares\Model\Role  $model

@return \Antares\Contracts\Html\Form\Builder

View form generator for Antares \ Model \ Role .


public function edit(Eloquent $eloquent, array $available = array())
    {
        publish('acl', ['js/control.js']);
        $id         = $eloquent->id;
        $instances  = $this->container->make('antares.acl')->all();
        $form       = $this->form($eloquent);
        $modules    = $this->adapter->modules();
        $collection = $this->container->make('antares.memory')->make('collector')->all();
        foreach ($collection as $item) {
            array_push($available, $item['aid']);
        }
        return compact('eloquent', 'form', 'modules', 'instances', 'available', 'id');
    }

public function edit ( Eloquent $ eloquent , array $ available = array ( ) ) { publish ( 'acl' , [ 'js/control.js' ] ) ; $ id = $ eloquent -> id ; $ instances = $ this -> container -> make ( 'antares.acl' ) -> all ( ) ; $ form = $ this -> form ( $ eloquent ) ; $ modules = $ this -> adapter -> modules ( ) ; $ collection = $ this -> container -> make ( 'antares.memory' ) -> make ( 'collector' ) -> all ( ) ; foreach ( $ collection as $ item ) { array_push ( $ available , $ item [ 'aid' ] ) ; } return compact ( 'eloquent' , 'form' , 'modules' , 'instances' , 'available' , 'id' ) ; }


public function create(UserCreatorListener $listener)
    {
        $eloquent = Foundation::make('antares.user');
        $form     = $this->presenter->form($eloquent, 'create');
        $this->fireEvent('form', [$eloquent, $form]);
        return $listener->showUserCreator(compact('eloquent', 'form'));
    }

public function create ( UserCreatorListener $ listener ) { $ eloquent = Foundation :: make ( 'antares.user' ) ; $ form = $ this -> presenter -> form ( $ eloquent , 'create' ) ; $ this -> fireEvent ( 'form' , [ $ eloquent , $ form ] ) ; return $ listener -> showUserCreator ( compact ( 'eloquent' , 'form' ) ) ; }

View create user page.

@param  \Antares\Contracts\Foundation\Listener\Account\UserCreator  $listener

@return mixed


public function edit(UserUpdaterListener $listener, $id)
    {
        $eloquent = Foundation::make('antares.user');
        if ($id !== auth()->user()->id) {
            $eloquent = $eloquent->where('id', $id)->withoutGlobalScopes()->whereHas('roles', function ($query) {
                        $role    = user()->roles->first();
                        $roles   = $role->getChilds();
                        $roles[] = $role->id;
                        $query->whereIn('role_id', array_values($roles));
                    })->first();
            if (is_null($eloquent)) {
                return $listener->noAccessToEdit();
            }
        } else {
            $eloquent = $eloquent->findOrFail($id);
        }

        $form = $this->presenter->form($eloquent, 'update');
        $this->fireEvent('form', [$eloquent, $form]);

        return $listener->showUserChanger(compact('eloquent', 'form'));
    }

public function edit ( UserUpdaterListener $ listener , $ id ) { $ eloquent = Foundation :: make ( 'antares.user' ) ; if ( $ id !== auth ( ) -> user ( ) -> id ) { $ eloquent = $ eloquent -> where ( 'id' , $ id ) -> withoutGlobalScopes ( ) -> whereHas ( 'roles' , function ( $ query ) { $ role = user ( ) -> roles -> first ( ) ; $ roles = $ role -> getChilds ( ) ; $ roles [ ] = $ role -> id ; $ query -> whereIn ( 'role_id' , array_values ( $ roles ) ) ; } ) -> first ( ) ; if ( is_null ( $ eloquent ) ) { return $ listener -> noAccessToEdit ( ) ; } } else { $ eloquent = $ eloquent -> findOrFail ( $ id ) ; } $ form = $ this -> presenter -> form ( $ eloquent , 'update' ) ; $ this -> fireEvent ( 'form' , [ $ eloquent , $ form ] ) ; return $ listener -> showUserChanger ( compact ( 'eloquent' , 'form' ) ) ; }

View edit user page.

@param  \Antares\Contracts\Foundation\Listener\Account\UserUpdater  $listener
@param  string|int  $id

@return mixed


public function store(UserCreatorListener $listener, array $input)
    {

        $user           = Foundation::make('antares.user');
        $user->status   = Eloquent::UNVERIFIED;
        $user->password = $input['password'];

        $form = $this->presenter->form($user);
        if (!$form->isValid()) {
            return $listener->createUserFailedValidation($form->getMessageBag());
        }

        try {
            $this->saving($user, $input, 'create');
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->createUserFailed(['error' => $e->getMessage()]);
        }

        return $listener->userCreated();
    }

public function store ( UserCreatorListener $ listener , array $ input ) { $ user = Foundation :: make ( 'antares.user' ) ; $ user -> status = Eloquent :: UNVERIFIED ; $ user -> password = $ input [ 'password' ] ; $ form = $ this -> presenter -> form ( $ user ) ; if ( ! $ form -> isValid ( ) ) { return $ listener -> createUserFailedValidation ( $ form -> getMessageBag ( ) ) ; } try { $ this -> saving ( $ user , $ input , 'create' ) ; } catch ( Exception $ e ) { Log :: emergency ( $ e ) ; return $ listener -> createUserFailed ( [ 'error' => $ e -> getMessage ( ) ] ) ; } return $ listener -> userCreated ( ) ; }

Store a user.

@param  \Antares\Contracts\Foundation\Listener\Account\UserCreator  $listener
@param  array   $input

@return mixed


public function update(UserUpdaterListener $listener, $id, array $input)
    {
        if ((string) $id !== $input['id']) {
            return $listener->abortWhenUserMismatched();
        }
        $user           = Foundation::make('antares.user')->withoutGlobalScopes()->findOrFail($id);
        !empty($input['password']) && $user->password = $input['password'];
        try {
            $this->saving($user, $input, 'update');
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->updateUserFailed(['error' => $e->getMessage()]);
        }

        return $listener->userUpdated();
    }

public function update ( UserUpdaterListener $ listener , $ id , array $ input ) { if ( ( string ) $ id !== $ input [ 'id' ] ) { return $ listener -> abortWhenUserMismatched ( ) ; } $ user = Foundation :: make ( 'antares.user' ) -> withoutGlobalScopes ( ) -> findOrFail ( $ id ) ; ! empty ( $ input [ 'password' ] ) && $ user -> password = $ input [ 'password' ] ; try { $ this -> saving ( $ user , $ input , 'update' ) ; } catch ( Exception $ e ) { Log :: emergency ( $ e ) ; return $ listener -> updateUserFailed ( [ 'error' => $ e -> getMessage ( ) ] ) ; } return $ listener -> userUpdated ( ) ; }

Update a user.

@param  \Antares\Contracts\Foundation\Listener\Account\UserUpdater  $listener
@param  string|int  $id
@param  array  $input

@return mixed


public function destroy(UserRemoverListener $listener, $id)
    {
        if (user()->id == $id) {
            return $listener->userDeletionFailed(['error' => trans('antares/acl::messages.unable_to_delete_self')]);
        }
        $user = Foundation::make('antares.user');
        if (app('antares.acl')->make('antares/acl')->can('login-as-user')) {
            $user = $user->withoutGlobalScopes();
        }

        $user = $user->findOrFail($id);
        if ((string) $user->id === (string) Auth::user()->id) {
            return $listener->selfDeletionFailed();
        }

        try {
            $this->fireEvent('deleting', [$user]);

            DB::transaction(function () use ($user) {
                $user->delete();
            });

            $this->fireEvent('deleted', [$user]);
        } catch (Exception $e) {
            Log::emergency($e);
            return $listener->userDeletionFailed(['error' => $e->getMessage()]);
        }

        return $listener->userDeleted();
    }

Destroy a user.

@param  \Antares\Contracts\Foundation\Listener\Account\UserRemover  $listener
@param  string|int  $id

@return mixed


protected function saving(Eloquent $user, $input = [], $type = 'create')
    {
        $beforeEvent = ($type === 'create' ? 'creating' : 'updating');
        $afterEvent  = ($type === 'create' ? 'created' : 'updated');

        $user->firstname = $input['firstname'];
        $user->lastname  = $input['lastname'];
        $user->email     = $input['email'];

        if (isset($input['status'])) {
            $user->status = $input['status'];
        }
        if ($user->exists && !isset($input['status'])) {
            $user->status = 0;
        }

        $this->fireEvent($beforeEvent, [$user]);
        $this->fireEvent('saving', [$user]);

        DB::transaction(function () use ($user, $input) {
            $user->save();
            $user->roles()->sync($input['roles']);
        });

        $this->fireEvent($afterEvent, [$user]);
        $this->fireEvent('saved', [$user]);

        return true;
    }

protected function saving ( Eloquent $ user , $ input = [ ] , $ type = 'create' ) { $ beforeEvent = ( $ type === 'create' ? 'creating' : 'updating' ) ; $ afterEvent = ( $ type === 'create' ? 'created' : 'updated' ) ; $ user -> firstname = $ input [ 'firstname' ] ; $ user -> lastname = $ input [ 'lastname' ] ; $ user -> email = $ input [ 'email' ] ; if ( isset ( $ input [ 'status' ] ) ) { $ user -> status = $ input [ 'status' ] ; } if ( $ user -> exists && ! isset ( $ input [ 'status' ] ) ) { $ user -> status = 0 ; } $ this -> fireEvent ( $ beforeEvent , [ $ user ] ) ; $ this -> fireEvent ( 'saving' , [ $ user ] ) ; DB :: transaction ( function ( ) use ( $ user , $ input ) { $ user -> save ( ) ; $ user -> roles ( ) -> sync ( $ input [ 'roles' ] ) ; } ) ; $ this -> fireEvent ( $ afterEvent , [ $ user ] ) ; $ this -> fireEvent ( 'saved' , [ $ user ] ) ; return true ; }

Save the user.

@param  \Antares\Model\User  $user
@param  array  $input
@param  string  $type

@return bool


public function isWithinPath($path) {
		$path = SiteUrl::normalizePath($path);

		$current_path = $this->getPath() . '/';
		$path = trim($path, '/') . '/';

		if ($path === '/') {
			return true;
		}

		return (0 === strpos($current_path, $path));
	}

public function isWithinPath ( $ path ) { $ path = SiteUrl :: normalizePath ( $ path ) ; $ current_path = $ this -> getPath ( ) . '/' ; $ path = trim ( $ path , '/' ) . '/' ; if ( $ path === '/' ) { return true ; } return ( 0 === strpos ( $ current_path , $ path ) ) ; }

Is this path within the given path?

E.g. if the current path is "blog/view/123", this would return true for "blog",
but false for "bl" or "blog/vi".

@param string $path Path to compare. E.g. "blog/view"

@return bool


protected function getRegisteredType()
    {
        if (empty($this->registered_type)) {
            $this->registered_type = $this->pool->getRegisteredType($this->getType());

            if (empty($this->registered_type)) {
                throw new InvalidArgumentException("Type '" . $this->getType() . "' is not registered");
            }
        }

        return $this->registered_type;
    }

protected
function
getRegisteredType
(
)
{
if
(
empty
(
$
this
->
registered_type
)
)
{
$
this
->
registered_type
=
$
this
->
pool
->
getRegisteredType
(
$
this
->
getType
(
)
)
;
if
(
empty
(
$
this
->
registered_type
)
)
{
throw
new
InvalidArgumentException
(
"Type '"
.
$
this
->
getType
(
)
.
"' is not registered"
)
;
}
}
return
$
this
->
registered_type
;
}


public function getEtag($visitor_identifier, $use_cache = true)
    {
        $timestamp_field = $this->getTimestampField();

        if ($timestamp_field && ($this->tag === false || !$use_cache)) {
            $this->tag = $this->prepareTagFromBits($this->getAdditionalIdentifier(), $visitor_identifier, $this->getTimestampHash($timestamp_field));
        }

        return $this->tag;
    }

public function getEtag ( $ visitor_identifier , $ use_cache = true ) { $ timestamp_field = $ this -> getTimestampField ( ) ; if ( $ timestamp_field && ( $ this -> tag === false || ! $ use_cache ) ) { $ this -> tag = $ this -> prepareTagFromBits ( $ this -> getAdditionalIdentifier ( ) , $ visitor_identifier , $ this -> getTimestampHash ( $ timestamp_field ) ) ; } return $ this -> tag ; }

Return collection etag.

@param  string $visitor_identifier
@param  bool   $use_cache
@return string


public function getTimestampField()
    {
        if ($this->timestamp_field === null) {
            $fields = $this->pool->getTypeFields($this->getRegisteredType());

            if (in_array('updated_at', $fields)) {
                $this->timestamp_field = 'updated_at';
            } elseif (in_array('created_at', $fields)) {
                $this->timestamp_field = 'created_at';
            } else {
                $this->timestamp_field = false;
            }
        }

        return $this->timestamp_field;
    }

public function getTimestampField ( ) { if ( $ this -> timestamp_field === null ) { $ fields = $ this -> pool -> getTypeFields ( $ this -> getRegisteredType ( ) ) ; if ( in_array ( 'updated_at' , $ fields ) ) { $ this -> timestamp_field = 'updated_at' ; } elseif ( in_array ( 'created_at' , $ fields ) ) { $ this -> timestamp_field = 'created_at' ; } else { $ this -> timestamp_field = false ; } } return $ this -> timestamp_field ; }

Return timestamp field name.

@return string|bool


public function getTimestampHash($timestamp_field)
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        $table_name = $this->getTableName();
        $conditions = $this->getConditions() ? " WHERE {$this->getConditions()}" : '';

        if ($this->count() > 0) {
            if ($join_expression = $this->getJoinExpression()) {
                return sha1($this->connection->executeFirstCell("SELECT GROUP_CONCAT($table_name.$timestamp_field ORDER BY $table_name.id SEPARATOR ',') AS 'timestamp_hash' FROM $table_name $join_expression $conditions"));
            } else {
                return sha1($this->connection->executeFirstCell("SELECT GROUP_CONCAT($table_name.$timestamp_field ORDER BY id SEPARATOR ',') AS 'timestamp_hash' FROM $table_name $conditions"));
            }
        }

        return sha1(get_class($this));
    }

Return timestamp hash.

@param  string $timestamp_field
@return string


public function execute()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        if (is_callable($this->pre_execute_callback)) {
            $ids = $this->executeIds();

            if ($ids_count = count($ids)) {
                call_user_func($this->pre_execute_callback, $ids);

                if ($ids_count > 1000) {
                    $sql = $this->getSelectSql(); // Don't escape more than 1000 ID-s using DB::escape(), let MySQL do the dirty work instead of PHP
                } else {
                    $escaped_ids = $this->connection->escapeValue($ids);

                    $sql = "SELECT * FROM {$this->getTableName()} WHERE id IN ($escaped_ids) ORDER BY FIELD (id, $escaped_ids)";
                }

                return $this->pool->findBySql($this->getType(), $sql);
            }

            return null;
        } else {
            return $this->pool->findBySql($this->getType(), $this->getSelectSql());
        }
    }

Run the query and return DB result.

@return ResultInterface|EntityInterface[]


public function executeIds()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        if ($this->ids === false) {
            $this->ids = $this->connection->executeFirstColumn($this->getSelectSql(false));

            if (empty($this->ids)) {
                $this->ids = [];
            }
        }

        return $this->ids;
    }

public
function
executeIds
(
)
{
if
(
!
$
this
->
isReady
(
)
)
{
throw
new
LogicException
(
'Collection is not ready'
)
;
}
if
(
$
this
->
ids
===
false
)
{
$
this
->
ids
=
$
this
->
connection
->
executeFirstColumn
(
$
this
->
getSelectSql
(
false
)
)
;
if
(
empty
(
$
this
->
ids
)
)
{
$
this
->
ids
=
[
]
;
}
}
return
$
this
->
ids
;
}

Return ID-s of matching records.

@return array


public function count()
    {
        if (!$this->isReady()) {
            throw new LogicException('Collection is not ready');
        }

        $table_name = $this->connection->escapeTableName($this->getTableName());
        $conditions = $this->getConditions() ? " WHERE {$this->getConditions()}" : '';

        if ($join_expression = $this->getJoinExpression()) {
            return (int) $this->connection->executeFirstCell("SELECT COUNT($table_name.`id`) FROM $table_name $join_expression $conditions");
        } else {
            return $this->connection->executeFirstCell("SELECT COUNT(`id`) AS 'row_count' FROM $table_name $conditions");
        }
    }

Return number of records that match conditions set by the collection.

@return int

Return number of records that match conditions set by the collection .


public function getTableName()
    {
        if (empty($this->table_name)) {
            $this->table_name = $this->pool->getTypeTable($this->getRegisteredType());
        }

        return $this->table_name;
    }

public function getTableName ( ) { if ( empty ( $ this -> table_name ) ) { $ this -> table_name = $ this -> pool -> getTypeTable ( $ this -> getRegisteredType ( ) ) ; } return $ this -> table_name ; }


public function getOrderBy()
    {
        if ($this->order_by === false) {
            $this->order_by = $this->pool->getEscapedTypeOrderBy($this->getRegisteredType());
        }

        return $this->order_by;
    }

public function getOrderBy ( ) { if ( $ this -> order_by === false ) { $ this -> order_by = $ this -> pool -> getEscapedTypeOrderBy ( $ this -> getRegisteredType ( ) ) ; } return $ this -> order_by ; }


public function &orderBy($value)
    {
        if ($value === null || $value) {
            $this->order_by = $value;
        } else {
            throw new InvalidArgumentException('$value can be NULL or a valid order by value');
        }

        return $this;
    }

Set how system should order records in this collection.

@param  string $value
@return $this

Set how system should order records in this collection .


public function getConditions()
    {
        if ($this->conditions_as_string === false) {
            switch (count($this->conditions)) {
                case 0:
                    $this->conditions_as_string = '';
                    break;
                case 1:
                    $this->conditions_as_string = $this->conditions[0];
                    break;
                default:
                    $this->conditions_as_string = implode(' AND ', array_map(function ($condition) {
                        return "($condition)";
                    }, $this->conditions));
            }
        }

        return $this->conditions_as_string;
    }

public
function
getConditions
(
)
{
if
(
$
this
->
conditions_as_string
===
false
)
{
switch
(
count
(
$
this
->
conditions
)
)
{
case
0
:
$
this
->
conditions_as_string
=
''
;
break
;
case
1
:
$
this
->
conditions_as_string
=
$
this
->
conditions
[
0
]
;
break
;
default
:
$
this
->
conditions_as_string
=
implode
(
' AND '
,
array_map
(
function
(
$
condition
)
{
return
"($condition)"
;
}
,
$
this
->
conditions
)
)
;
}
}
return
$
this
->
conditions_as_string
;
}


public function &where($pattern, ...$arguments)
    {
        if (empty($pattern)) {
            throw new InvalidArgumentException('Pattern argument is required');
        }

        if (is_string($pattern)) {
            $this->conditions[] = $this->connection->prepareConditions(array_merge([$pattern], $arguments));
        } elseif (is_array($pattern)) {
            if (!empty($arguments)) {
                throw new LogicException('When pattern is an array, no extra arguments are allowed');
            }

            $this->conditions[] = $this->connection->prepareConditions($pattern);
        } else {
            throw new InvalidArgumentException('Pattern can be string or an array');
        }

        // Force rebuild of conditions as string on next getConditions() call
        $this->conditions_as_string = false;

        return $this;
    }

Set collection conditions.

@param  string $pattern
@param  array  $arguments
@return $this


public function &setJoinTable($table_name, $join_field = null)
    {
        $this->join_table = $table_name;

        if (empty($this->target_join_field)) {
            if (is_string($join_field) && $join_field) {
                $this->setTargetJoinField($join_field);
            } elseif (is_array($join_field)) {
                if (count($join_field) == 2 && !empty($join_field[0]) && !empty($join_field[1])) {
                    $this->setSourceJoinField($join_field[0]);
                    $this->setTargetJoinField($join_field[1]);
                } else {
                    throw new InvalidArgumentException('Join field should be an array with two elements');
                }
            } else {
                $registered_type = $this->getRegisteredType();

                if (($pos = strrpos($registered_type, '\\')) !== false) {
                    $this->target_join_field = Inflector::singularize(Inflector::tableize(substr($registered_type, $pos + 1))) . '_id';
                } else {
                    $this->target_join_field = Inflector::singularize(Inflector::tableize($registered_type)) . '_id';
                }
            }
        }

        return $this;
    }

Set join table name.

If $join_field is null, join field will be based on model name. There are two ways to specify it:

1. As string, where value is for target field and it will map with ID column of the source table,
2. As array, where first element is ID in the source table and second element is field in target table

@param  string            $table_name
@param  array|string|null $join_field
@return $this


public function edit($listener, $metric)
    {
        publish('acl', ['js/control.js']);
        $collection = [];
        $instances  = $this->acl->all();
        $eloquent   = null;

        foreach ($instances as $name => $instance) {
            $collection[$name] = $this->getAuthorizationName($name);

            $name === $metric && $eloquent = $instance;
        }

        if (is_null($eloquent)) {
            return $listener->aclVerificationFailed();
        }
        $form = $this->formBuilder->create('Antares\Acl\Http\Form\Acl', [
            'method' => 'POST',
            'url'    => route('content/save'),
            'model'  => $eloquent
        ]);

        return $listener->indexSucceed(compact('eloquent', 'collection', 'metric', 'form'));
    }

public function edit ( $ listener , $ metric ) { publish ( 'acl' , [ 'js/control.js' ] ) ; $ collection = [ ] ; $ instances = $ this -> acl -> all ( ) ; $ eloquent = null ; foreach ( $ instances as $ name => $ instance ) { $ collection [ $ name ] = $ this -> getAuthorizationName ( $ name ) ; $ name === $ metric && $ eloquent = $ instance ; } if ( is_null ( $ eloquent ) ) { return $ listener -> aclVerificationFailed ( ) ; } $ form = $ this -> formBuilder -> create ( 'Antares\Acl\Http\Form\Acl' , [ 'method' => 'POST' , 'url' => route ( 'content/save' ) , 'model' => $ eloquent ] ) ; return $ listener -> indexSucceed ( compact ( 'eloquent' , 'collection' , 'metric' , 'form' ) ) ; }

List ACL collection.

@param  object  $listener
@param  string  $metric

@return mixed


public function update($listener, array $input)
    {
        $all = $this->acl->all();
        if (is_null($all)) {
            return $listener->aclVerificationFailed();
        }
        $roleId = key($input['acl']);

        $role     = $this->foundation->make('antares.role')->query()->where('id', $roleId)->firstOrFail();
        $roleName = $role->name;
        $allowed  = array_keys($input['acl'][$roleId]);

        foreach ($all as $component => $details) {
            $acl     = $this->acl->get($component);
            $actions = $details->actions->get();
            foreach ($actions as $actionId => $name) {
                $allow = in_array($actionId, $allowed);
                $acl->allow($roleName, $name, $allow);
            }
            $acl->save();
        }
        return $listener->updateSucceed($roleId);
    }

public function update ( $ listener , array $ input ) { $ all = $ this -> acl -> all ( ) ; if ( is_null ( $ all ) ) { return $ listener -> aclVerificationFailed ( ) ; } $ roleId = key ( $ input [ 'acl' ] ) ; $ role = $ this -> foundation -> make ( 'antares.role' ) -> query ( ) -> where ( 'id' , $ roleId ) -> firstOrFail ( ) ; $ roleName = $ role -> name ; $ allowed = array_keys ( $ input [ 'acl' ] [ $ roleId ] ) ; foreach ( $ all as $ component => $ details ) { $ acl = $ this -> acl -> get ( $ component ) ; $ actions = $ details -> actions -> get ( ) ; foreach ( $ actions as $ actionId => $ name ) { $ allow = in_array ( $ actionId , $ allowed ) ; $ acl -> allow ( $ roleName , $ name , $ allow ) ; } $ acl -> save ( ) ; } return $ listener -> updateSucceed ( $ roleId ) ; }

Update ACL metric.

@param  object  $listener
@param  array   $input

@return mixed


public function setLogger($log = self::SYSLOG)
    {
        if ($log === self::FILES || $log === self::FILES_DEBUG) {
            $log_file = strtr(static::DEFAULT_LOG_FILE, [
                '{name}' => $this->name,
            ]);
            $this->logger = new Loggers\FilesLogger($log_file);
        } else if ($log === self::TERMINAL) {
            $this->logger = new Loggers\TerminalLogger();
        } else
            $this->logger = new Loggers\SyslogLogger();
        return $this;
    }

public function setLogger ( $ log = self :: SYSLOG ) { if ( $ log === self :: FILES || $ log === self :: FILES_DEBUG ) { $ log_file = strtr ( static :: DEFAULT_LOG_FILE , [ '{name}' => $ this -> name , ] ) ; $ this -> logger = new Loggers \ FilesLogger ( $ log_file ) ; } else if ( $ log === self :: TERMINAL ) { $ this -> logger = new Loggers \ TerminalLogger ( ) ; } else $ this -> logger = new Loggers \ SyslogLogger ( ) ; return $ this ; }

Sets logger for daemon.
@param integer $log


public function start()
    {
        $this->ensureNotLocked();
        $pid = $this->fork();

        // return pid
        if ($pid > 0)
            return $pid;

        declare(ticks=1);

        $this->lock();
        $this->registerSignalHandlers();
        if ($this->strategy === self::NORMAL)
            $this->onStart();
        else
            $this->startTicking();
        $this->unlock();
        exit(0);
    }

public
function
start
(
)
{
$
this
->
ensureNotLocked
(
)
;
$
pid
=
$
this
->
fork
(
)
;
// return pid
if
(
$
pid
>
0
)
return
$
pid
;
declare
(
ticks
=
1
)
;
$
this
->
lock
(
)
;
$
this
->
registerSignalHandlers
(
)
;
if
(
$
this
->
strategy
===
self
::
NORMAL
)
$
this
->
onStart
(
)
;
else
$
this
->
startTicking
(
)
;
$
this
->
unlock
(
)
;
exit
(
0
)
;
}

Starts daemon.
@return integer Process ID of daemon.


public function stop()
    {
        $lock_data = $this->getStatus();
        if ($lock_data === false)
            return null;

        return posix_kill($lock_data->pid, SIGTERM);
    }

public function stop ( ) { $ lock_data = $ this -> getStatus ( ) ; if ( $ lock_data === false ) return null ; return posix_kill ( $ lock_data -> pid , SIGTERM ) ; }

Stops daemon.
@return null|boolean True if daemon is stopped. Null if it was not running.


public function kill()
    {
        $lock_data = $this->getStatus();
        if ($lock_data === false)
            return null;

        return posix_kill($lock_data->pid, SIGKILL);
    }

public function kill ( ) { $ lock_data = $ this -> getStatus ( ) ; if ( $ lock_data === false ) return null ; return posix_kill ( $ lock_data -> pid , SIGKILL ) ; }

Kills daemon.
@return null|boolean True if daemon is stopped. Null if it was not running.


public function &where($pattern, ...$arguments)
    {
        if (!is_string($pattern)) {
            throw new InvalidArgumentException('Conditions pattern needs to be string');
        }

        $conditions_to_prepare = [$pattern];

        if (!empty($arguments)) {
            $conditions_to_prepare = array_merge($conditions_to_prepare, $arguments);
        }

        $this->where[] = $this->connection->prepareConditions($conditions_to_prepare);

        return $this;
    }

public
function
&
where
(
$
pattern
,
...
$
arguments
)
{
if
(
!
is_string
(
$
pattern
)
)
{
throw
new
InvalidArgumentException
(
'Conditions pattern needs to be string'
)
;
}
$
conditions_to_prepare
=
[
$
pattern
]
;
if
(
!
empty
(
$
arguments
)
)
{
$
conditions_to_prepare
=
array_merge
(
$
conditions_to_prepare
,
$
arguments
)
;
}
$
this
->
where
[
]
=
$
this
->
connection
->
prepareConditions
(
$
conditions_to_prepare
)
;
return
$
this
;
}

Set finder  .

@param string $pattern
@param  mixed  ...$arguments
@return $this


public function getWhere()
    {
        switch (count($this->where)) {
            case 0:
                return '';
            case 1:
                return $this->where[0];
            default:
                return implode(' AND ', array_map(function ($condition) {
                    return "($condition)";
                }, $this->where));
        }
    }

public
function
getWhere
(
)
{
switch
(
count
(
$
this
->
where
)
)
{
case
0
:
return
''
;
case
1
:
return
$
this
->
where
[
0
]
;
default
:
return
implode
(
' AND '
,
array_map
(
function
(
$
condition
)
{
return
"($condition)"
;
}
,
$
this
->
where
)
)
;
}
}


public function count()
    {
        $table_name = $this->getEscapedTableName();

        $sql = "SELECT COUNT($table_name.`id`) AS 'row_count' FROM $table_name";

        if ($this->join) {
            $sql .= " $this->join";
        }

        if ($where = $this->getWhere()) {
            $sql .= " WHERE $where";
        }

        return $this->connection->executeFirstCell($sql);
    }

Return number of records that match the given criteria.

@return int

Return number of records that match the given criteria .


public function first()
    {
        if ($this->offset === null) {
            $this->offset = 0;
        }

        $this->limit = 1;

        if ($result = $this->execute()) {
            return $result[0];
        }

        return null;
    }

public function first ( ) { if ( $ this -> offset === null ) { $ this -> offset = 0 ; } $ this -> limit = 1 ; if ( $ result = $ this -> execute ( ) ) { return $ result [ 0 ] ; } return null ; }

Return first record that matches the given criteria.

@return object|null

Return first record that matches the given criteria .


public function ids()
    {
        $ids = $this->connection->executeFirstColumn($this->getSelectIdsSql());

        return empty($ids) ? [] : $ids;
    }

public function ids ( ) { $ ids = $ this -> connection -> executeFirstColumn ( $ this -> getSelectIdsSql ( ) ) ; return empty ( $ ids ) ? [ ] : $ ids ; }

Return array of ID-s that match the given criteria.

@return int[]

Return array of ID - s that match the given criteria .


public function execute()
    {
        $select_sql = $this->getSelectSql();

        if ($this->loadByTypeField()) {
            $return_by = ConnectionInterface::RETURN_OBJECT_BY_FIELD;
            $return_by_value = 'type';
        } else {
            $return_by = ConnectionInterface::RETURN_OBJECT_BY_CLASS;
            $return_by_value = $this->type;
        }

        if ($this->hasContainer()) {
            return $this->connection->advancedExecute($select_sql, null, ConnectionInterface::LOAD_ALL_ROWS, $return_by, $return_by_value, [&$this->connection, &$this->pool, &$this->log], $this->getContainer());
        } else {
            return $this->connection->advancedExecute($select_sql, null, ConnectionInterface::LOAD_ALL_ROWS, $return_by, $return_by_value, [&$this->connection, &$this->pool, &$this->log]);
        }
    }

public function execute ( ) { $ select_sql = $ this -> getSelectSql ( ) ; if ( $ this -> loadByTypeField ( ) ) { $ return_by = ConnectionInterface :: RETURN_OBJECT_BY_FIELD ; $ return_by_value = 'type' ; } else { $ return_by = ConnectionInterface :: RETURN_OBJECT_BY_CLASS ; $ return_by_value = $ this -> type ; } if ( $ this -> hasContainer ( ) ) { return $ this -> connection -> advancedExecute ( $ select_sql , null , ConnectionInterface :: LOAD_ALL_ROWS , $ return_by , $ return_by_value , [ & $ this -> connection , & $ this -> pool , & $ this -> log ] , $ this -> getContainer ( ) ) ; } else { return $ this -> connection -> advancedExecute ( $ select_sql , null , ConnectionInterface :: LOAD_ALL_ROWS , $ return_by , $ return_by_value , [ & $ this -> connection , & $ this -> pool , & $ this -> log ] ) ; } }

Prepare SQL and load one or more records.

@return mixed

Prepare SQL and load one or more records .


private function loadByTypeField()
    {
        if ($this->load_by_type_field === null) {
            $this->load_by_type_field = in_array('type', $this->pool->getTypeFields($this->type));
        }

        return $this->load_by_type_field;
    }

private function loadByTypeField ( ) { if ( $ this -> load_by_type_field === null ) { $ this -> load_by_type_field = in_array ( 'type' , $ this -> pool -> getTypeFields ( $ this -> type ) ) ; } return $ this -> load_by_type_field ; }

Check if we should load by type field or by type class.

@return bool

Check if we should load by type field or by type class .


private function getSelectFieldsSql($escaped_field_names)
    {
        $result = "SELECT $escaped_field_names FROM " . $this->getEscapedTableName();

        if ($this->join) {
            $result .= " $this->join";
        }

        if ($where = $this->getWhere()) {
            $result .= " WHERE $where";
        }

        if ($this->order_by) {
            $result .= " ORDER BY $this->order_by";
        }

        if ($this->offset !== null && $this->limit !== null) {
            $result .= " LIMIT $this->offset, $this->limit";
        }

        return $result;
    }

private
function
getSelectFieldsSql
(
$
escaped_field_names
)
{
$
result
=
"SELECT $escaped_field_names FROM "
.
$
this
->
getEscapedTableName
(
)
;
if
(
$
this
->
join
)
{
$
result
.=
" $this->join"
;
}
if
(
$
where
=
$
this
->
getWhere
(
)
)
{
$
result
.=
" WHERE $where"
;
}
if
(
$
this
->
order_by
)
{
$
result
.=
" ORDER BY $this->order_by"
;
}
if
(
$
this
->
offset
!==
&&
$
this
->
limit
!==
)
{
$
result
.=
" LIMIT $this->offset, $this->limit"
;
}
return
$
result
;
}

Construct SELECT query for the given fields based on set criteria.

@param  string $escaped_field_names
@return string

Construct SELECT query for the given fields based on set criteria .


public function modules()
    {

        $memory        = app('antares.memory');
        $configuration = $memory->make('component');
        $extensions    = $configuration->get('extensions.active');
        $coreActions   = $configuration->get('acl_antares.actions');

        $data = [
            [
                'name'        => 'antares',
                'namespace'   => 'antares',
                'full_name'   => 'Core Platform',
                'description' => 'Application engine',
                'actions'     => $coreActions
            ]
        ];

        foreach ($extensions as $extension) {
            $named   = app('antares.extension')->getAvailableExtensions()->findByName($extension['fullname']);
            $name    = str_replace(['component-', 'module-'], '', $extension['name']);
            $actions = $configuration->get("acl_antares/{$name}.actions");
            $data[]  = array_merge([
                'name'        => $name,
                'full_name'   => $named->getFriendlyName(),
                'description' => strip_tags($named->getPackage()->getDescription())], [
                'actions'   => $actions,
                'namespace' => "antares/{$name}"
            ]);
        }

        return $data;
    }

public
function
modules
(
)
{
$
memory
=
app
(
'antares.memory'
)
;
$
configuration
=
$
memory
->
make
(
'component'
)
;
$
extensions
=
$
configuration
->
get
(
'extensions.active'
)
;
$
coreActions
=
$
configuration
->
get
(
'acl_antares.actions'
)
;
$
data
=
[
[
'name'
=>
'antares'
,
'namespace'
=>
'antares'
,
'full_name'
=>
'Core Platform'
,
'description'
=>
'Application engine'
,
'actions'
=>
$
coreActions
]
]
;
foreach
(
$
extensions
as
$
extension
)
{
$
named
=
app
(
'antares.extension'
)
->
getAvailableExtensions
(
)
->
findByName
(
$
extension
[
'fullname'
]
)
;
$
name
=
str_replace
(
[
'component-'
,
'module-'
]
,
''
,
$
extension
[
'name'
]
)
;
$
actions
=
$
configuration
->
get
(
"acl_antares/{$name}.actions"
)
;
$
data
[
]
=
array_merge
(
[
'name'
=>
$
name
,
'full_name'
=>
$
named
->
getFriendlyName
(
)
,
'description'
=>
strip_tags
(
$
named
->
getPackage
(
)
->
getDescription
(
)
)
]
,
[
'actions'
=>
$
actions
,
'namespace'
=>
"antares/{$name}"
]
)
;
}
return
$
data
;
}


protected function smashResource($name, $resource, $item, $controller, &$return)
    {
        $pattern = "{$name}::{$resource}::";
        if (starts_with($item, $pattern)) {
            $id                                               = $this->collector->id($item);
            $actionForm                                       = preg_replace("/{$pattern}/", '', $item);
            $smashed                                          = explode('::', $actionForm);
            return $return[$resource][$controller][$smashed[0]][$id] = $smashed[1];
        }
    }

protected function smashResource ( $ name , $ resource , $ item , $ controller , & $ return ) { $ pattern = "{$name}::{$resource}::" ; if ( starts_with ( $ item , $ pattern ) ) { $ id = $ this -> collector -> id ( $ item ) ; $ actionForm = preg_replace ( "/{$pattern}/" , '' , $ item ) ; $ smashed = explode ( '::' , $ actionForm ) ; return $ return [ $ resource ] [ $ controller ] [ $ smashed [ 0 ] ] [ $ id ] = $ smashed [ 1 ] ; } }

find smashed resource

@param String $name
@param String $resource
@param array $item
@param String $controller
@param array $return
@return array


public function defineAllPermissions()
    {
        foreach ($this->getPermissions() as $permission) {

            Gate::define(
                $permission->name,
                function ($user, ...$arguments) use ($permission) {
                    foreach ($permission->roles as $role) {
                        if ($role->belongsToUser($user)) {
                            if (!empty($permission->class)
                                AND !empty($permission->method)
                                AND class_exists($permission->class)
                            ) {
                                $container = resolve($permission->class);
                                if (method_exists($container, $permission->method)) {
                                    array_unshift($arguments, $user);
                                    return
                                        call_user_func_array(
                                            [$container, $permission->method],
                                            $arguments
                                        );
                                } else {
                                    return false;
                                }
                            }
                            return true;
                        }
                    }
                    return false;
                }
            );
        }
        return false;
    }

public function defineAllPermissions ( ) { foreach ( $ this -> getPermissions ( ) as $ permission ) { Gate :: define ( $ permission -> name , function ( $ user , ... $ arguments ) use ( $ permission ) { foreach ( $ permission -> roles as $ role ) { if ( $ role -> belongsToUser ( $ user ) ) { if ( ! empty ( $ permission -> class ) AND ! empty ( $ permission -> method ) AND class_exists ( $ permission -> class ) ) { $ container = resolve ( $ permission -> class ) ; if ( method_exists ( $ container , $ permission -> method ) ) { array_unshift ( $ arguments , $ user ) ; return call_user_func_array ( [ $ container , $ permission -> method ] , $ arguments ) ; } else { return false ; } } return true ; } } return false ; } ) ; } return false ; }

Define all permission and make usable from laravel application

@return bool


public function assignRole($user, $role)
    {
        if (is_int($user) and !$user = User::where('id', $user)->first()) {
            return false;
        }
        if (is_int($role) and !$role = Roles::where('id', $role)->first()) {
            return false;
        }
        if (is_string($role) and !$role = Roles::where('name', $role)->first()) {
            return false;
        }
        if (!($user instanceof User) or !($role instanceof Roles)) {
            return false;
        }
        return $role->assignToUser($user);
    }

public function assignRole ( $ user , $ role ) { if ( is_int ( $ user ) and ! $ user = User :: where ( 'id' , $ user ) -> first ( ) ) { return false ; } if ( is_int ( $ role ) and ! $ role = Roles :: where ( 'id' , $ role ) -> first ( ) ) { return false ; } if ( is_string ( $ role ) and ! $ role = Roles :: where ( 'name' , $ role ) -> first ( ) ) { return false ; } if ( ! ( $ user instanceof User ) or ! ( $ role instanceof Roles ) ) { return false ; } return $ role -> assignToUser ( $ user ) ; }

Assign Role to user

@param int|User         $user User Instance or user id
@param int|string|Roles $role Role Instance, role name, or role id

@return bool


public function removeRole($user, $role)
    {
        if (is_int($user) and !$user = User::where('id', $user)->first()) {
            return false;
        }
        if (is_int($role) and !$role = Roles::where('id', $role)->first()) {
            return false;
        }
        if (is_string($role) and !$role = Roles::where('name', $role)->first()) {
            return false;
        }
        if (!($user instanceof User) or !($role instanceof Roles)) {
            return false;
        }
        $role->users()->detach($user->id);
        return true;
    }

public function removeRole ( $ user , $ role ) { if ( is_int ( $ user ) and ! $ user = User :: where ( 'id' , $ user ) -> first ( ) ) { return false ; } if ( is_int ( $ role ) and ! $ role = Roles :: where ( 'id' , $ role ) -> first ( ) ) { return false ; } if ( is_string ( $ role ) and ! $ role = Roles :: where ( 'name' , $ role ) -> first ( ) ) { return false ; } if ( ! ( $ user instanceof User ) or ! ( $ role instanceof Roles ) ) { return false ; } $ role -> users ( ) -> detach ( $ user -> id ) ; return true ; }

Remove Role from user

@param int|User         $user User Instance or user id
@param int|string|Roles $role Role Instance, role name, or role id

@return bool


public function create($listener)
    {

        $eloquent = $this->model;
        $form     = $this->presenter->form($eloquent);
        return $listener->createSucceed(compact('eloquent', 'form'));
    }

public function create ( $ listener ) { $ eloquent = $ this -> model ; $ form = $ this -> presenter -> form ( $ eloquent ) ; return $ listener -> createSucceed ( compact ( 'eloquent' , 'form' ) ) ; }

View create a role page.

@param  object  $listener

@return mixed


public function edit($listener, $id)
    {
        $eloquent = $this->model->findOrFail($id);
        $data     = $this->presenter->edit($eloquent);
        return $listener->editSucceed($data);
    }

public function edit ( $ listener , $ id ) { $ eloquent = $ this -> model -> findOrFail ( $ id ) ; $ data = $ this -> presenter -> edit ( $ eloquent ) ; return $ listener -> editSucceed ( $ data ) ; }

View edit a role page.

@param  object  $listener
@param  string|int  $id

@return mixed


public function store($listener, array $input)
    {
        $role = $this->model;
        $form = $this->presenter->form($role);
        if (!$form->isValid()) {
            return $listener->storeValidationFailed($form->getMessageBag());
        }
        try {
            $this->saving($role, $input, 'create');
        } catch (Exception $e) {
            Log::warning($e);
            return $listener->storeFailed(['error' => $e->getMessage()]);
        }
        return $listener->storeSucceed($role);
    }

public function store ( $ listener , array $ input ) { $ role = $ this -> model ; $ form = $ this -> presenter -> form ( $ role ) ; if ( ! $ form -> isValid ( ) ) { return $ listener -> storeValidationFailed ( $ form -> getMessageBag ( ) ) ; } try { $ this -> saving ( $ role , $ input , 'create' ) ; } catch ( Exception $ e ) { Log :: warning ( $ e ) ; return $ listener -> storeFailed ( [ 'error' => $ e -> getMessage ( ) ] ) ; } return $ listener -> storeSucceed ( $ role ) ; }

Store a role.

@param  object  $listener
@param  array   $input

@return mixed


public function update($listener, array $input, $id)
    {

        if ((int) $id !== (int) $input['id']) {
            return $listener->userVerificationFailed();
        }
        $role = $this->model->findOrFail($id);
        $form = $this->presenter->form($role);
        if (!$form->isValid()) {
            return $listener->updateValidationFailed($form->getMessageBag(), $id);
        }

        try {
            $this->saving($role, $input, 'update');
        } catch (Exception $e) {

            Log::warning($e);
            return $listener->updateFailed(['error' => $e->getMessage()]);
        }

        return $listener->updateSucceed();
    }

public function update ( $ listener , array $ input , $ id ) { if ( ( int ) $ id !== ( int ) $ input [ 'id' ] ) { return $ listener -> userVerificationFailed ( ) ; } $ role = $ this -> model -> findOrFail ( $ id ) ; $ form = $ this -> presenter -> form ( $ role ) ; if ( ! $ form -> isValid ( ) ) { return $ listener -> updateValidationFailed ( $ form -> getMessageBag ( ) , $ id ) ; } try { $ this -> saving ( $ role , $ input , 'update' ) ; } catch ( Exception $ e ) { Log :: warning ( $ e ) ; return $ listener -> updateFailed ( [ 'error' => $ e -> getMessage ( ) ] ) ; } return $ listener -> updateSucceed ( ) ; }

Update a role.

@param  object  $listener
@param  array   $input
@param  int     $id

@return mixed


public function destroy($listener, $id)
    {
        $role = $this->model->findOrFail($id);
        try {
            if ($role->users->count() > 0) {
                throw new Exception('Unable to delete group with assigned users.');
            }
            DB::transaction(function () use ($role) {
                $role->delete();
            });
        } catch (Exception $e) {
            Log::warning($e);
            return $listener->destroyFailed(['error' => $e->getMessage()]);
        }

        return $listener->destroySucceed($role);
    }

Delete a role.

@param  object  $listener
@param  string|int  $id

@return mixed


protected function saving(Eloquent $role, $input = [], $type = 'create')
    {
        $beforeEvent = ($type === 'create' ? 'creating' : 'updating');
        $afterEvent  = ($type === 'create' ? 'created' : 'updated');

        $name = $input['name'];
        $role->fill([
            'name'        => snake_case($name, '-'),
            'full_name'   => $name,
            'area'        => array_get($input, 'area'),
            'description' => $input['description']
        ]);
        if (!$role->exists && isset($input['roles'])) {
            $role->parent_id = $input['roles'];
        }
        $this->fireEvent($beforeEvent, [$role]);
        $this->fireEvent('saving', [$role]);
        DB::transaction(function() use($role, $input) {
            $role->save();
            $this->import($input, $role);
        });
        $this->fireEvent($afterEvent, [$role]);
        $this->fireEvent('saved', [$role]);

        return true;
    }

protected function saving ( Eloquent $ role , $ input = [ ] , $ type = 'create' ) { $ beforeEvent = ( $ type === 'create' ? 'creating' : 'updating' ) ; $ afterEvent = ( $ type === 'create' ? 'created' : 'updated' ) ; $ name = $ input [ 'name' ] ; $ role -> fill ( [ 'name' => snake_case ( $ name , '-' ) , 'full_name' => $ name , 'area' => array_get ( $ input , 'area' ) , 'description' => $ input [ 'description' ] ] ) ; if ( ! $ role -> exists && isset ( $ input [ 'roles' ] ) ) { $ role -> parent_id = $ input [ 'roles' ] ; } $ this -> fireEvent ( $ beforeEvent , [ $ role ] ) ; $ this -> fireEvent ( 'saving' , [ $ role ] ) ; DB :: transaction ( function ( ) use ( $ role , $ input ) { $ role -> save ( ) ; $ this -> import ( $ input , $ role ) ; } ) ; $ this -> fireEvent ( $ afterEvent , [ $ role ] ) ; $ this -> fireEvent ( 'saved' , [ $ role ] ) ; return true ; }

Save the role.

@param  \Antares\Model\Role  $role
@param  array  $input
@param  string  $type

@return bool


protected function import(array $input, Model $role)
    {
        if (isset($input['import']) && !is_null($from = $input['roles'])) {
            $permission = $this->foundation->make('antares.auth.permission');

            $permissions = $permission->where('role_id', $from)->get();

            $permissions->each(function(Model $model) use($permission, $role) {
                $attributes = $model->getAttributes();
                $insert     = array_except($attributes, ['id', 'role_id']) + ['role_id' => $role->id];
                $permission->newInstance($insert)->save();
            });
        }
        return true;
    }

protected function import ( array $ input , Model $ role ) { if ( isset ( $ input [ 'import' ] ) && ! is_null ( $ from = $ input [ 'roles' ] ) ) { $ permission = $ this -> foundation -> make ( 'antares.auth.permission' ) ; $ permissions = $ permission -> where ( 'role_id' , $ from ) -> get ( ) ; $ permissions -> each ( function ( Model $ model ) use ( $ permission , $ role ) { $ attributes = $ model -> getAttributes ( ) ; $ insert = array_except ( $ attributes , [ 'id' , 'role_id' ] ) + [ 'role_id' => $ role -> id ] ; $ permission -> newInstance ( $ insert ) -> save ( ) ; } ) ; } return true ; }

import permissions when copy

@param array $input
@param Model $role


public function acl($id)
    {
        $eloquent = $this->model->findOrFail($id);
        return $this->presenter->acl($eloquent);
    }

public function acl ( $ id ) { $ eloquent = $ this -> model -> findOrFail ( $ id ) ; return $ this -> presenter -> acl ( $ eloquent ) ; }

Acl rules form

@param $id
@return \Illuminate\Contracts\View\Factory|\Illuminate\View\View


public function clearAnalyticsData()
    {
        $this->clear(self::ADBACK_ANALYTICS_SCRIPT);
        $this->clear(self::ADBACK_ANALYTICS_URL);
        $this->clear(self::ADBACK_ANALYTICS_CODE);
    }

public function clearAnalyticsData ( ) { $ this -> clear ( self :: ADBACK_ANALYTICS_SCRIPT ) ; $ this -> clear ( self :: ADBACK_ANALYTICS_URL ) ; $ this -> clear ( self :: ADBACK_ANALYTICS_CODE ) ; }


public function clearMessageData()
    {
        $this->clear(self::ADBACK_MESSAGE_SCRIPT);
        $this->clear(self::ADBACK_MESSAGE_URL);
        $this->clear(self::ADBACK_MESSAGE_CODE);
    }

public function clearMessageData ( ) { $ this -> clear ( self :: ADBACK_MESSAGE_SCRIPT ) ; $ this -> clear ( self :: ADBACK_MESSAGE_URL ) ; $ this -> clear ( self :: ADBACK_MESSAGE_CODE ) ; }


public function make()
    {
        $extensions = app('antares.memory')->make('component')->get('extensions.active');
        $data       = [
            [
                'name'      => 'core_platform',
                'full_name' => 'Core Platform',
                'handles'   => handles('antares::acl/acl')
            ]
        ];
        foreach ($extensions as $extension) {
            $name = $extension['name'];
            if ($name == 'control') {
                continue;
            }
            $data[] = array_merge($extension, ['handles' => handles('antares::acl/acl', ['name' => "antares/{$name}"])]);
        }
        $this->widget->make('pane.left')->add('modules')->content(view("antares/acl::partial._modules", ['data' => $data]));
    }

public
function
make
(
)
{
$
extensions
=
app
(
'antares.memory'
)
->
make
(
'component'
)
->
get
(
'extensions.active'
)
;
$
data
=
[
[
'name'
=>
'core_platform'
,
'full_name'
=>
'Core Platform'
,
'handles'
=>
handles
(
'antares::acl/acl'
)
]
]
;
foreach
(
$
extensions
as
$
extension
)
{
$
name
=
$
extension
[
'name'
]
;
if
(
$
name
==
'control'
)
{
continue
;
}
$
data
[
]
=
array_merge
(
$
extension
,
[
'handles'
=>
handles
(
'antares::acl/acl'
,
[
'name'
=>
"antares/{$name}"
]
)
]
)
;
}
$
this
->
widget
->
make
(
'pane.left'
)
->
add
(
'modules'
)
->
content
(
view
(
"antares/acl::partial._modules"
,
[
'data'
=>
$
data
]
)
)
;
}


public function edit(Roles $role)
    {
        $this->authorize('edit_role');

        $valueList = $role->permissions()->get()->pluck('id')->toArray();
        return view(
            'RoleManager::role.edit',
            ['role' => $role, 'permissions' => Permissions::all(),
                'valueList' => $valueList]
        );
    }

public function edit ( Roles $ role ) { $ this -> authorize ( 'edit_role' ) ; $ valueList = $ role -> permissions ( ) -> get ( ) -> pluck ( 'id' ) -> toArray ( ) ; return view ( 'RoleManager::role.edit' , [ 'role' => $ role , 'permissions' => Permissions :: all ( ) , 'valueList' => $ valueList ] ) ; }

Show the form for editing the specified resource.

@param Roles $role

@return \Illuminate\Http\Response

Show the form for editing the specified resource .


protected function scopeRoles(&$builder)
    {
        return (config('antares/acl::allow_register_with_other_roles')) ? $builder->administrators() :
                $builder->with('roles')->whereNotNull('tbl_users.id')->whereHas('roles', function ($query) {
                    $query->whereIn('tbl_roles.id', user()->roles->pluck('id')->toArray());
                });
    }

Scopes roles by configuration

@param \Illuminate\Database\Query\Builder $builder
@return \Illuminate\Database\Query\Builder


protected function statuses()
    {

        $statuses = User::withoutGlobalScopes()
                ->select([DB::raw('count(id) as counter'), 'status'])
                ->whereNull('tbl_users.deleted_at');
        $this->scopeRoles($statuses);
        $result   = $statuses->groupBy('status')->get()->pluck('counter', 'status')->toArray();
        return [
            'all' => trans('antares/foundation::messages.statuses.all'),
            0     => trans('antares/foundation::messages.statuses.disabled', ['count' => array_get($result, 0, 0)]),
            1     => trans('antares/foundation::messages.statuses.active', ['count' => array_get($result, 1, 0)])
        ];
    }

Creates select for statuses

@return String


protected function getActionsColumn($canUpdateUser, $canDeleteUser, $canLoginAsUser)
    {
        return function ($row) use($canUpdateUser, $canDeleteUser, $canLoginAsUser) {
            $html               = app('html');
            $this->tableActions = [];
            $user               = user();

            if ($canUpdateUser) {
                $url = ($user->id === $row->id) ? 'antares/foundation::/account' : "antares::acl/index/users/{$row->id}/edit";
                $this->addTableAction('edit', $row, $html->link(handles($url), trans('antares/foundation::label.edit'), ['data-icon' => 'edit']));
            }
            if (!is_null($user) && $user->id !== $row->id and $canDeleteUser) {
                $this->addTableAction('delete', $row, $html->create('li', $html->link(handles("antares::acl/index/users/{$row->id}/delete", ['csrf' => true]), trans('antares/foundation::label.delete'), [
                                    'class'            => 'triggerable confirm',
                                    'data-icon'        => 'delete',
                                    'data-title'       => trans("antares/acl::messages.users.delete.are_you_sure"),
                                    'data-description' => trans("antares/acl::messages.users.delete.deleteing_description", ["fullname" => $row->fullname])
                ])));
            }
            if (!is_null($user) && $user->id !== $row->id and $canLoginAsUser && $row->roles->pluck('name')->toArray() !== $user->roles->pluck('name')->toArray()) {

                $this->addTableAction('login_as', $row, $html->create('li', $html->link(handles("login/with/{$row->id}"), trans('antares/acl::label.login_as', ['fullname' => $row->fullname]), [
                                    'class'            => 'triggerable confirm',
                                    'data-icon'        => 'odnoklassniki',
                                    'data-title'       => trans("Are you sure?"),
                                    'data-description' => trans('antares/acl::label.login_as', ['fullname' => $row->fullname])
                ])));
            }
            if (empty($this->tableActions)) {
                return '';
            }
            $section = $html->create('div', $html->create('section', $html->create('ul', $html->raw(implode('', $this->tableActions->toArray())))), ['class' => 'mass-actions-menu'])->get();
            return '<i class="zmdi zmdi-more"></i>' . $html->raw($section)->get();
        };
    }

Get actions column for table builder.

@return callable


protected function userRoles($row)
    {
        return function ($row) {

            $roles = $row->roles;
            $value = [];

            foreach ($roles as $role) {
                $value[] = app('html')->create('span', e($role->full_name), [
                    'class' => 'label-basic label-basic--info'
                ]);
            }
            return implode('', [app('html')->create('span', app('html')->raw(implode(' ', $value)), ['class' => 'meta']),]);
        };
    }

protected
function
userRoles
(
$
row
)
{
return
function
(
$
row
)
{
$
roles
=
$
row
->
roles
;
$
value
=
[
]
;
foreach
(
$
roles
as
$
role
)
{
$
value
[
]
=
app
(
'html'
)
->
create
(
'span'
,
e
(
$
role
->
full_name
)
,
[
'class'
=>
'label-basic label-basic--info'
]
)
;
}
return
implode
(
''
,
[
app
(
'html'
)
->
create
(
'span'
,
app
(
'html'
)
->
raw
(
implode
(
' '
,
$
value
)
)
,
[
'class'
=>
'meta'
]
)
,
]
)
;
}
;
}

Get user roles column for table builder.

@return callable

Get user roles column for table builder .


public function &modify(EntityInterface &$instance, array $attributes = null, $save = true)
    {
        if ($instance->isNew()) {
            throw new RuntimeException('Only objects that are saved to database can be modified');
        }

        $registered_type = $this->requireRegisteredType(get_class($instance));

        $instance = $this->getProducerForRegisteredType($registered_type)->modify($instance, $attributes, $save);

        if ($instance instanceof EntityInterface) {
            $this->objects_pool[$registered_type][$instance->getId()] = $instance;
        }

        return $instance;
    }

Update an instance.

@param  EntityInterface $instance
@param  array|null      $attributes
@param  bool            $save
@return EntityInterface


protected function &getProducerForRegisteredType($registered_type)
    {
        if (empty($this->producers[$registered_type])) {
            if (empty($this->default_producer)) {
                $default_producer_class = $this->getDefaultProducerClass();

                $this->default_producer = new $default_producer_class($this->connection, $this);

                if ($this->default_producer instanceof ContainerAccessInterface && $this->hasContainer()) {
                    $this->default_producer->setContainer($this->getContainer());
                }
            }

            return $this->default_producer;
        } else {
            return $this->producers[$registered_type];
        }
    }

protected function & getProducerForRegisteredType ( $ registered_type ) { if ( empty ( $ this -> producers [ $ registered_type ] ) ) { if ( empty ( $ this -> default_producer ) ) { $ default_producer_class = $ this -> getDefaultProducerClass ( ) ; $ this -> default_producer = new $ default_producer_class ( $ this -> connection , $ this ) ; if ( $ this -> default_producer instanceof ContainerAccessInterface && $ this -> hasContainer ( ) ) { $ this -> default_producer -> setContainer ( $ this -> getContainer ( ) ) ; } } return $ this -> default_producer ; } else { return $ this -> producers [ $ registered_type ] ; } }

Return producer for registered type.

@param  string            $registered_type
@return ProducerInterface


public function registerProducer($type, ProducerInterface $producer)
    {
        $registered_type = $this->requireRegisteredType($type);

        if (empty($this->producers[$registered_type])) {
            if ($producer instanceof ContainerAccessInterface && $this->hasContainer()) {
                $producer->setContainer($this->getContainer());
            }

            $this->producers[$registered_type] = $producer;
        } else {
            throw new LogicException("Producer for '$type' is already registered");
        }
    }

Register producer instance for the given type.

@param string            $type
@param ProducerInterface $producer

Register producer instance for the given type .


public function registerProducerByClass($type, $producer_class)
    {
        if (class_exists($producer_class)) {
            $producer_class_reflection = new ReflectionClass($producer_class);

            if ($producer_class_reflection->implementsInterface(ProducerInterface::class)) {
                $this->registerProducer($type, new $producer_class($this->connection, $this));
            } else {
                throw new InvalidArgumentException("Class '$producer_class' does not implement '" . ProducerInterface::class . "' interface");
            }
        }
    }

Register producerby providing a producer class name.

@param string $type
@param string $producer_class

Register producerby providing a producer class name .


public function &getById($type, $id, $use_cache = true)
    {
        $registered_type = $this->requireRegisteredType($type);

        $id = (int) $id;

        if ($id < 1) {
            throw new InvalidArgumentException('ID is expected to be a number larger than 0');
        }

        if (isset($this->objects_pool[$registered_type][$id]) && $use_cache) {
            return $this->objects_pool[$registered_type][$id];
        } else {
            $type_fields = $this->getTypeFields($registered_type);

            if ($row = $this->connection->executeFirstRow($this->getSelectOneByType($registered_type), [$id])) {
                $object_class = in_array('type', $type_fields) ? $row['type'] : $type;

                /** @var object|EntityInterface $object */
                $object = new $object_class($this->connection, $this, $this->log);

                if ($object instanceof ContainerAccessInterface && $this->hasContainer()) {
                    $object->setContainer($this->getContainer());
                }

                $object->loadFromRow($row);

                return $this->addToObjectPool($registered_type, $id, $object);
            } else {
                $object = null;

                return $this->addToObjectPool($registered_type, $id, $object);
            }
        }
    }

Return object from object pool by the given type and ID; if object is not found, return NULL.

@param  string                   $type
@param  int                      $id
@param  bool                     $use_cache
@return object
@throws InvalidArgumentException

Return object from object pool by the given type and ID ; if object is not found return NULL .


public function &mustGetById($type, $id, $use_cache = true)
    {
        $result = $this->getById($type, $id, $use_cache);

        if (empty($result)) {
            throw new ObjectNotFoundException($type, $id);
        }

        return $result;
    }

public function & mustGetById ( $ type , $ id , $ use_cache = true ) { $ result = $ this -> getById ( $ type , $ id , $ use_cache ) ; if ( empty ( $ result ) ) { throw new ObjectNotFoundException ( $ type , $ id ) ; } return $ result ; }

Return object from object pool by the given type and ID; if object is not found, raise an exception.

@param  string                   $type
@param  int                      $id
@param  bool                     $use_cache
@return object
@throws ObjectNotFoundException
@throws InvalidArgumentException

Return object from object pool by the given type and ID ; if object is not found raise an exception .


private function &addToObjectPool($registered_type, $id, &$value_to_store)
    {
        if (empty($this->objects_pool[$registered_type])) {
            $this->objects_pool[$registered_type] = [];
        }

        $this->objects_pool[$registered_type][$id] = $value_to_store;

        return $this->objects_pool[$registered_type][$id];
    }

private function & addToObjectPool ( $ registered_type , $ id , & $ value_to_store ) { if ( empty ( $ this -> objects_pool [ $ registered_type ] ) ) { $ this -> objects_pool [ $ registered_type ] = [ ] ; } $ this -> objects_pool [ $ registered_type ] [ $ id ] = $ value_to_store ; return $ this -> objects_pool [ $ registered_type ] [ $ id ] ; }

Add object to the object pool.

@param  string               $registered_type
@param  int                  $id
@param  EntityInterface|null $value_to_store
@return EntityInterface


public function remember(EntityInterface &$object)
    {
        if ($object->isLoaded()) {
            $this->addToObjectPool($this->requireRegisteredType(get_class($object)), $object->getId(), $object);
        } else {
            throw new InvalidArgumentException('Object needs to be saved in the database to be remembered');
        }
    }

Add object to the pool.

@param EntityInterface $object


public function count($type, $conditions = null)
    {
        $this->requireRegisteredType($type);

        if ($conditions = $this->connection->prepareConditions($conditions)) {
            return $this->connection->executeFirstCell('SELECT COUNT(`id`) AS "row_count" FROM ' . $this->getTypeTable($type, true) . " WHERE $conditions");
        } else {
            return $this->connection->executeFirstCell('SELECT COUNT(`id`) AS "row_count" FROM ' . $this->getTypeTable($type, true));
        }
    }

Return number of records of the given type that match the given conditions.

@param  string            $type
@param  array|string|null $conditions
@return int

Return number of records of the given type that match the given conditions .


public function find($type)
    {
        $registered_type = $this->requireRegisteredType($type);

        $default_finder_class = $this->getDefaultFinderClass();

        /** @var Finder $finder */
        $finder = new $default_finder_class($this->connection, $this, $this->log, $registered_type);

        if ($finder instanceof ContainerAccessInterface && $this->hasContainer()) {
            $finder->setContainer($this->getContainer());
        }

        return $finder;
    }

public
function
find
(
$
type
)
{
$
registered_type
=
$
this
->
requireRegisteredType
(
$
type
)
;
$
default_finder_class
=
$
this
->
getDefaultFinderClass
(
)
;
/** @var Finder $finder */
$
finder
=
new
$
default_finder_class
(
$
this
->
connection
,
$
this
,
$
this
->
log
,
$
registered_type
)
;
if
(
$
finder
instanceof
ContainerAccessInterface
&&
$
this
->
hasContainer
(
)
)
{
$
finder
->
setContainer
(
$
this
->
getContainer
(
)
)
;
}
return
$
finder
;
}

Find records by type.

@param  string $type
@return Finder


private function getSelectOneByType($type)
    {
        if (empty($this->types[$type]['sql_select_by_ids'])) {
            $this->types[$type]['sql_select_by_ids'] = 'SELECT ' . $this->getEscapedTypeFields($type) . ' FROM ' . $this->getTypeTable($type, true) . ' WHERE `id` IN ? ORDER BY `id`';
        }

        return $this->types[$type]['sql_select_by_ids'];
    }

private
function
getSelectOneByType
(
$
type
)
{
if
(
empty
(
$
this
->
types
[
$
type
]
[
'sql_select_by_ids'
]
)
)
{
$
this
->
types
[
$
type
]
[
'sql_select_by_ids'
]
=
'SELECT '
.
$
this
->
getEscapedTypeFields
(
$
type
)
.
' FROM '
.
$
this
->
getTypeTable
(
$
type
,
true
)
.
' WHERE `id` IN ? ORDER BY `id`'
;
}
return
$
this
->
types
[
$
type
]
[
'sql_select_by_ids'
]
;
}

Return select by ID-s query for the given type.

@param  string $type
@return string

Return select by ID - s query for the given type .


public function getEscapedTypeFields($type)
    {
        return $this->getTypeProperty($type, 'escaped_fields', function () use ($type) {
            $table_name = $this->getTypeTable($type, true);

            $escaped_field_names = [];

            foreach ($this->getTypeFields($type) as $field_name) {
                $escaped_field_names[] = $table_name . '.' . $this->connection->escapeFieldName($field_name);
            }

            foreach ($this->getGeneratedTypeFields($type) as $field_name) {
                $escaped_field_names[] = $table_name . '.' . $this->connection->escapeFieldName($field_name);
            }

            return implode(',', $escaped_field_names);
        });
    }

public function getEscapedTypeFields ( $ type ) { return $ this -> getTypeProperty ( $ type , 'escaped_fields' , function ( ) use ( $ type ) { $ table_name = $ this -> getTypeTable ( $ type , true ) ; $ escaped_field_names = [ ] ; foreach ( $ this -> getTypeFields ( $ type ) as $ field_name ) { $ escaped_field_names [ ] = $ table_name . '.' . $ this -> connection -> escapeFieldName ( $ field_name ) ; } foreach ( $ this -> getGeneratedTypeFields ( $ type ) as $ field_name ) { $ escaped_field_names [ ] = $ table_name . '.' . $ this -> connection -> escapeFieldName ( $ field_name ) ; } return implode ( ',' , $ escaped_field_names ) ; } ) ; }

Return a list of escaped field names for the given type.

@param  string $type
@return string

Return a list of escaped field names for the given type .


public function getEscapedTypeOrderBy($type)
    {
        return $this->getTypeProperty($type, 'escaped_order_by', function () use ($type) {
            $table_name = $this->getTypeTable($type, true);

            return implode(',', array_map(function ($field_name) use ($table_name) {
                if (substr($field_name, 0, 1) == '!') {
                    return $table_name . '.' . $this->connection->escapeFieldName(substr($field_name, 1)) . ' DESC';
                } else {
                    return $table_name . '.' . $this->connection->escapeFieldName($field_name);
                }
            }, $this->getTypeOrderBy($type)));
        });
    }

public
function
getEscapedTypeOrderBy
(
$
type
)
{
return
$
this
->
getTypeProperty
(
$
type
,
'escaped_order_by'
,
function
(
)
use
(
$
type
)
{
$
table_name
=
$
this
->
getTypeTable
(
$
type
,
true
)
;
return
implode
(
','
,
array_map
(
function
(
$
field_name
)
use
(
$
table_name
)
{
if
(
substr
(
$
field_name
,
0
,
1
)
==
'!'
)
{
return
$
table_name
.
'.'
.
$
this
->
connection
->
escapeFieldName
(
substr
(
$
field_name
,
1
)
)
.
' DESC'
;
}
else
{
return
$
table_name
.
'.'
.
$
this
->
connection
->
escapeFieldName
(
$
field_name
)
;
}
}
,
$
this
->
getTypeOrderBy
(
$
type
)
)
)
;
}
)
;
}

Return escaped list of fields that we can order by.

@param  string $type
@return string

Return escaped list of fields that we can order by .


public function getTraitNamesByType($type)
    {
        if (empty($this->types[$type]['traits'])) {
            $this->types[$type]['traits'] = [];

            $this->recursiveGetTraitNames(new ReflectionClass($type), $this->types[ $type ]['traits']);
        }

        return $this->types[$type]['traits'];
    }

public function getTraitNamesByType ( $ type ) { if ( empty ( $ this -> types [ $ type ] [ 'traits' ] ) ) { $ this -> types [ $ type ] [ 'traits' ] = [ ] ; $ this -> recursiveGetTraitNames ( new ReflectionClass ( $ type ) , $ this -> types [ $ type ] [ 'traits' ] ) ; } return $ this -> types [ $ type ] [ 'traits' ] ; }

Return trait names by object.

Note: $type does not need to be directly registered, because we need to support subclasses, which call can have
different traits impelemnted!

@param  string $type
@return array


private function recursiveGetTraitNames(ReflectionClass $class, array &$trait_names)
    {
        $trait_names = array_merge($trait_names, $class->getTraitNames());

        if ($class->getParentClass()) {
            $this->recursiveGetTraitNames($class->getParentClass(), $trait_names);
        }
    }

private function recursiveGetTraitNames ( ReflectionClass $ class , array & $ trait_names ) { $ trait_names = array_merge ( $ trait_names , $ class -> getTraitNames ( ) ) ; if ( $ class -> getParentClass ( ) ) { $ this -> recursiveGetTraitNames ( $ class -> getParentClass ( ) , $ trait_names ) ; } }

Recursively get trait names for the given class.

@param ReflectionClass $class
@param array           $trait_names

Recursively get trait names for the given class .


public function adaptee(Grid &$grid, array $controls = array(), Fluent $model)
    {
        if (empty($controls)) {
            return false;
        }
        $grid->fieldset(function (Fieldset $fieldset) use($controls, $model) {
            $editable    = $model->get('editable', []);
            $displayable = $model->get('displayable', []);

            foreach ($controls as $control) {
                $name = $control['name'];

                $fieldset->control($control['type'], $name)
                        ->label($control['label'])
                        ->value($control['value'])
                        ->attributes(['disabled' => 'disabled', 'readonly' => 'readonly']);

                $fieldset->control('input:checkbox', 'editable[' . $name . ']')
                        ->value($control['value'])
                        ->label(trans('editable'))
                        ->attributes($this->checked($control, $editable));

                $fieldset->control('input:checkbox', 'displayable[' . $name . ']')
                        ->value($control['value'])
                        ->label(trans('displayable'))
                        ->attributes($this->checked($control, $displayable));
            }
        });
    }

public function adaptee ( Grid & $ grid , array $ controls = array ( ) , Fluent $ model ) { if ( empty ( $ controls ) ) { return false ; } $ grid -> fieldset ( function ( Fieldset $ fieldset ) use ( $ controls , $ model ) { $ editable = $ model -> get ( 'editable' , [ ] ) ; $ displayable = $ model -> get ( 'displayable' , [ ] ) ; foreach ( $ controls as $ control ) { $ name = $ control [ 'name' ] ; $ fieldset -> control ( $ control [ 'type' ] , $ name ) -> label ( $ control [ 'label' ] ) -> value ( $ control [ 'value' ] ) -> attributes ( [ 'disabled' => 'disabled' , 'readonly' => 'readonly' ] ) ; $ fieldset -> control ( 'input:checkbox' , 'editable[' . $ name . ']' ) -> value ( $ control [ 'value' ] ) -> label ( trans ( 'editable' ) ) -> attributes ( $ this -> checked ( $ control , $ editable ) ) ; $ fieldset -> control ( 'input:checkbox' , 'displayable[' . $ name . ']' ) -> value ( $ control [ 'value' ] ) -> label ( trans ( 'displayable' ) ) -> attributes ( $ this -> checked ( $ control , $ displayable ) ) ; } } ) ; }

adaptee controls on form instance

@param FormFactory $form
@param array $controls
@param Fluent $model
@return boolean


protected function checked(array $control, array $displayable)
    {
        if (empty($displayable)) {
            return ['checked' => 'checked'];
        }
        foreach ($displayable as $item) {
            if ($control['name'] == $item['name']) {
                return ['checked' => 'checked'];
            }
        }
        return [];
    }

protected function checked ( array $ control , array $ displayable ) { if ( empty ( $ displayable ) ) { return [ 'checked' => 'checked' ] ; } foreach ( $ displayable as $ item ) { if ( $ control [ 'name' ] == $ item [ 'name' ] ) { return [ 'checked' => 'checked' ] ; } } return [ ] ; }

verify whether checkbox should be checked

@param array $control
@param array $displayable
@return string


public function prepareEntity($parameters)
    {
        $this->activePageEntity->setPageid($this->getPageIdentifiers()->getPageId());
        $this->activePageEntity->setLangid(Registry::getLang()->getBaseLanguage());
        $domain = str_ireplace('www.', '', parse_url(Registry::getConfig()->getShopUrl(), PHP_URL_HOST));
        $this->activePageEntity->setSiteid($domain);

        $this->setControllerInfo($parameters);

        $this->setLoginsTracking();
        $this->setEmailTracking();

        $this->activePageEntity = $this->getEntityModifierByCurrentBasketAction()->modifyEntity($this->activePageEntity);

        return $this->activePageEntity;
    }

public function prepareEntity ( $ parameters ) { $ this -> activePageEntity -> setPageid ( $ this -> getPageIdentifiers ( ) -> getPageId ( ) ) ; $ this -> activePageEntity -> setLangid ( Registry :: getLang ( ) -> getBaseLanguage ( ) ) ; $ domain = str_ireplace ( 'www.' , '' , parse_url ( Registry :: getConfig ( ) -> getShopUrl ( ) , PHP_URL_HOST ) ) ; $ this -> activePageEntity -> setSiteid ( $ domain ) ; $ this -> setControllerInfo ( $ parameters ) ; $ this -> setLoginsTracking ( ) ; $ this -> setEmailTracking ( ) ; $ this -> activePageEntity = $ this -> getEntityModifierByCurrentBasketAction ( ) -> modifyEntity ( $ this -> activePageEntity ) ; return $ this -> activePageEntity ; }

Makes OXID eShop page entity.

@param array $parameters Plugin parameters.

@return ActivePageEntityInterface


private function setLoginsTracking()
    {
        $currentView = Registry::getConfig()->getActiveView();
        $functionName = $currentView->getFncName();
        if ('login_noredirect' == $functionName) {
            $this->activePageEntity->setLoginUserId($this->activeUserDataProvider->getActiveUserHashedId());
            $this->activePageEntity->setLoginResult($this->activeUserDataProvider->isLoaded() ? '0' : '1');
        }
    }

private function setLoginsTracking ( ) { $ currentView = Registry :: getConfig ( ) -> getActiveView ( ) ; $ functionName = $ currentView -> getFncName ( ) ; if ( 'login_noredirect' == $ functionName ) { $ this -> activePageEntity -> setLoginUserId ( $ this -> activeUserDataProvider -> getActiveUserHashedId ( ) ) ; $ this -> activePageEntity -> setLoginResult ( $ this -> activeUserDataProvider -> isLoaded ( ) ? '0' : '1' ) ; } }


private function setEmailTracking()
    {
        $hashedEmail = $this->activeUserDataProvider->getActiveUserHashedEmail();
        if (!is_null($hashedEmail)) {
            $this->activePageEntity->setEmail($hashedEmail);
        }
    }

private function setEmailTracking ( ) { $ hashedEmail = $ this -> activeUserDataProvider -> getActiveUserHashedEmail ( ) ; if ( ! is_null ( $ hashedEmail ) ) { $ this -> activePageEntity -> setEmail ( $ hashedEmail ) ; } }


public function getSitePath($url, $match_scheme = true) {
		$ret = $this->analyzeUrl($url);

		if (!$ret || !$ret['path_within_site'] || ($ret['site_host'] !== $ret['host'])) {
			return false;
		}

		if ($match_scheme && ($ret['scheme'] !== $ret['site_scheme'])) {
			return false;
		}

		return new SitePath(implode('/', $ret['url_segments_within_site']));
	}

public function getSitePath ( $ url , $ match_scheme = true ) { $ ret = $ this -> analyzeUrl ( $ url ) ; if ( ! $ ret || ! $ ret [ 'path_within_site' ] || ( $ ret [ 'site_host' ] !== $ ret [ 'host' ] ) ) { return false ; } if ( $ match_scheme && ( $ ret [ 'scheme' ] !== $ ret [ 'site_scheme' ] ) ) { return false ; } return new SitePath ( implode ( '/' , $ ret [ 'url_segments_within_site' ] ) ) ; }

Get a site path object if the URL is within the Elgg site, or false if not.

@param string $url          URL, possibly within the site
@param bool   $match_scheme Require the URL scheme to match, e.g. http: won't match https:
@return SitePath|bool

Get a site path object if the URL is within the Elgg site or false if not .


public function analyzeUrl($url) {
		$url = trim($url);

		if (!preg_match('~^(https?)\\://([^/]+)(/.*|$)~', $url, $m)) {
			return false;
		}

		list (, $scheme, $host, $path) = $m;

		$path = self::normalizePath($path);

		$segments = ($path === '') ? array() : explode('/', $path);

		$ret = [
			'site_scheme' => $this->scheme,
			'site_host' => $this->host,
			'site_url_segments' => $this->url_segments,
			'host' => $host,
			'scheme' => $scheme,
			'path_within_site' => false,
			'url_segments' => $segments,
			'url_segments_within_site' => [],
		];

		$site_segments = $this->url_segments;
		while (count($site_segments)) {
			$site_segment = array_shift($site_segments);
			$segment = array_shift($segments);

			if ($segment !== $site_segment) {
				// not in site
				return $ret;
			}
		}

		$ret['path_within_site'] = true;
		$ret['url_segments_within_site'] = $segments;

		return $ret;
	}

public
function
analyzeUrl
(
$
url
)
{
$
url
=
trim
(
$
url
)
;
if
(
!
preg_match
(
'~^(https?)\\://([^/]+)(/.*|$)~'
,
$
url
,
$
m
)
)
{
return
false
;
}
list
(
,
$
scheme
,
$
host
,
$
path
)
=
$
m
;
$
path
=
self
::
normalizePath
(
$
path
)
;
$
segments
=
(
$
path
===
''
)
array
(
)
:
explode
(
'/'
,
$
path
)
;
$
ret
=
[
'site_scheme'
=>
$
this
->
scheme
,
'site_host'
=>
$
this
->
host
,
'site_url_segments'
=>
$
this
->
url_segments
,
'host'
=>
$
host
,
'scheme'
=>
$
scheme
,
'path_within_site'
=>
false
,
'url_segments'
=>
$
segments
,
'url_segments_within_site'
=>
[
]
,
]
;
$
site_segments
=
$
this
->
url_segments
;
while
(
count
(
$
site_segments
)
)
{
$
site_segment
=
array_shift
(
$
site_segments
)
;
$
segment
=
array_shift
(
$
segments
)
;
if
(
$
segment
!==
$
site_segment
)
{
// not in site
return
$
ret
;
}
}
$
ret
[
'path_within_site'
]
=
true
;
$
ret
[
'url_segments_within_site'
]
=
$
segments
;
return
$
ret
;
}

Analyze a URL.

@param string $url URL
@return array|false


public function getBasketProductCategoryPath($product)
    {
        $categoryPath = '';
        if ($category = $product->getCategory()) {
            $table = $category->getViewName();
            $database = \OxidEsales\Eshop\Core\DatabaseProvider::getDb(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC);
            $query = "select {$table}.oxtitle as oxtitle from {$table}
                       where {$table}.oxleft <= " . $database->quote($category->oxcategories__oxleft->value) . " and
                             {$table}.oxright >= " . $database->quote($category->oxcategories__oxright->value) . " and
                             {$table}.oxrootid = " . $database->quote($category->oxcategories__oxrootid->value) . "
                       order by {$table}.oxleft";

            $result = $database->select($query);
            if ($result != false && $result->count() > 0) {
                while (!$result->EOF) {
                    if ($categoryPath) {
                        $categoryPath .= '/';
                    }
                    $categoryPath .= strip_tags($result->fields['oxtitle']);
                    $result->fetchRow();
                }
            }
        }

        return $categoryPath;
    }

" and
                             {$table}.oxright >= "

" and
                             {$table}.oxrootid = "

"
                       order by {$table}.oxleft"

Builds basket product category path.

@param \OxidEsales\Eshop\Application\Model\Article $product Article to build category id.

@return string


private function areFieldValuesSame($value_1, $value_2)
    {
        if (($value_1 instanceof DateValueInterface && $value_2 instanceof DateValueInterface) || ($value_1 instanceof DateTimeValueInterface && $value_2 instanceof DateTimeValueInterface)) {
            return $value_1->getTimestamp() == $value_2->getTimestamp();
        } else {
            return $value_1 === $value_2;
        }
    }

private function areFieldValuesSame ( $ value_1 , $ value_2 ) { if ( ( $ value_1 instanceof DateValueInterface && $ value_2 instanceof DateValueInterface ) || ( $ value_1 instanceof DateTimeValueInterface && $ value_2 instanceof DateTimeValueInterface ) ) { return $ value_1 -> getTimestamp ( ) == $ value_2 -> getTimestamp ( ) ; } else { return $ value_1 === $ value_2 ; } }

Return true if field values match.

@param  mixed $value_1
@param  mixed $value_2
@return bool


public function loadFromRow(array $row)
    {
        if (empty($row)) {
            throw new InvalidArgumentException('Database row expected');
        }

        $this->startLoading();

        $found_generated_fields = [];

        foreach ($row as $k => $v) {
            if ($this->isGeneratedField($k)) {
                $found_generated_fields[] = $k;
            } elseif ($this->fieldExists($k)) {
                $this->setFieldValue($k, $v);
            }
        }

        if (!empty($found_generated_fields)) {
            $generated_field_values = [];

            $value_caster = $this->getGeneratedFieldsValueCaster();

            if ($value_caster instanceof ValueCasterInterface) {
                $generated_field_values = array_intersect_key($row, array_flip($found_generated_fields));

                $value_caster->castRowValues($generated_field_values);
            }

            foreach ($generated_field_values as $k => $v) {
                $this->setFieldValue($k, $v);
            }
        }

        $this->doneLoading();
    }

public
function
loadFromRow
(
array
$
row
)
{
if
(
empty
(
$
row
)
)
{
throw
new
InvalidArgumentException
(
'Database row expected'
)
;
}
$
this
->
startLoading
(
)
;
$
found_generated_fields
=
[
]
;
foreach
(
$
row
as
$
k
=>
$
v
)
{
if
(
$
this
->
isGeneratedField
(
$
k
)
)
{
$
found_generated_fields
[
]
=
$
k
;
}
elseif
(
$
this
->
fieldExists
(
$
k
)
)
{
$
this
->
setFieldValue
(
$
k
,
$
v
)
;
}
}
if
(
!
empty
(
$
found_generated_fields
)
)
{
$
generated_field_values
=
[
]
;
$
value_caster
=
$
this
->
getGeneratedFieldsValueCaster
(
)
;
if
(
$
value_caster
instanceof
ValueCasterInterface
)
{
$
generated_field_values
=
array_intersect_key
(
$
row
,
array_flip
(
$
found_generated_fields
)
)
;
$
value_caster
->
castRowValues
(
$
generated_field_values
)
;
}
foreach
(
$
generated_field_values
as
$
k
=>
$
v
)
{
$
this
->
setFieldValue
(
$
k
,
$
v
)
;
}
}
$
this
->
doneLoading
(
)
;
}

Load data from database row.

If $cache_row is set to true row data will be added to cache

@param  array                    $row
@throws InvalidArgumentException


public function copy($save = false)
    {
        $object_class = get_class($this);

        /** @var EntityInterface $copy */
        $copy = new $object_class($this->connection, $this->pool, $this->log);

        foreach ($this->getFields() as $field) {
            if ($this->isPrimaryKey($field)) {
                continue;
            }

            $copy->setFieldValue($field, $this->getFieldValue($field));
        }

        if ($save) {
            $copy->save();
        }

        return $copy;
    }

public
function
copy
(
$
save
=
false
)
{
$
object_class
=
get_class
(
$
this
)
;
/** @var EntityInterface $copy */
$
copy
=
new
$
object_class
(
$
this
->
connection
,
$
this
->
pool
,
$
this
->
log
)
;
foreach
(
$
this
->
getFields
(
)
as
$
field
)
{
if
(
$
this
->
isPrimaryKey
(
$
field
)
)
{
continue
;
}
$
copy
->
setFieldValue
(
$
field
,
$
this
->
getFieldValue
(
$
field
)
)
;
}
if
(
$
save
)
{
$
copy
->
save
(
)
;
}
return
$
copy
;
}

Create a copy of this object and optionally save it.

@param  bool   $save
@return object

Create a copy of this object and optionally save it .


public function revertField($field)
    {
        if ($this->isModifiedField($field)) {
            $this->setFieldValue($field, $this->getOldFieldValue($field)); // revert field value

            if (($key = array_search($field, $this->modified_fields)) !== false) {
                unset($this->modified_fields[$field]); // remove modified flag
            }
        }
    }

public
function
revertField
(
$
field
)
{
if
(
$
this
->
isModifiedField
(
$
field
)
)
{
$
this
->
setFieldValue
(
$
field
,
$
this
->
getOldFieldValue
(
$
field
)
)
;
// revert field value
if
(
(
$
key
=
array_search
(
$
field
,
$
this
->
modified_fields
)
)
!==
false
)
{
unset
(
$
this
->
modified_fields
[
$
field
]
)
;
// remove modified flag
}
}
}

Revert field to old value.

@param $field


public function getOldFieldValue($field)
    {
        return isset($this->old_values[$field]) ? $this->old_values[$field] : null;
    }

public function getOldFieldValue ( $ field ) { return isset ( $ this -> old_values [ $ field ] ) ? $ this -> old_values [ $ field ] : null ; }

Return all field value.

@param  string $field
@return mixed


public function &setFieldValue($field, $value)
    {
        if ($this->fieldExists($field)) {
            if ($field === 'id') {
                $value = $value === null ? null : (int) $value;
            }

            if ($value === null && array_key_exists($field, $this->default_field_values)) {
                throw new InvalidArgumentException("Value of '$field' can't be null");
            }

            if (!$this->isLoading()) {
                $this->triggerEvent('on_prepare_field_value_before_set', [$field, &$value]);
            }

            if (!array_key_exists($field, $this->values) || ($this->values[$field] !== $value)) {

                // If we are loading object there is no need to remember if this field
                // was modified, if PK has been updated and old value. We just skip that
                if (!$this->isLoading()) {
                    if (isset($this->values[$field])) {
                        $old_value = $this->values[$field]; // Remember old value
                    }

                    // Save primary key value. Also make sure that only the first PK value is
                    // saved as old. Not to save second value on third modification ;)
                    if ($this->isPrimaryKey($field) && !$this->primary_key_modified) {
                        $this->primary_key_modified = true;
                    }

                    // Save old value if we haven't done that already
                    if (isset($old_value) && !isset($this->old_values[$field])) {
                        $this->old_values[$field] = $old_value;
                    }

                    // Remember that this field is modified
                    if (!in_array($field, $this->modified_fields)) {
                        $this->modified_fields[] = $field;
                    }
                }

                $this->values[$field] = $value;
            }
        } else {
            throw new InvalidArgumentException("Field '$field' does not exist");
        }

        return $this;
    }

Set specific field value.

Set value of the $field. This function will make sure that everything
runs fine - modifications are saved, in case of primary key old value
will be remembered in case we need to update the row and so on

@param  string                   $field
@param  mixed                    $value
@return $this
@throws InvalidArgumentException


private function insert()
    {
        $last_insert_id = $this->connection->insert($this->table_name, $this->values);

        if (empty($this->values[$this->auto_increment])) {
            $this->values[$this->auto_increment] = $last_insert_id;
        }

        $this->values = array_merge($this->values, $this->refreshGeneratedFieldValues($last_insert_id));
        $this->setAsLoaded();
    }

private function insert ( ) { $ last_insert_id = $ this -> connection -> insert ( $ this -> table_name , $ this -> values ) ; if ( empty ( $ this -> values [ $ this -> auto_increment ] ) ) { $ this -> values [ $ this -> auto_increment ] = $ last_insert_id ; } $ this -> values = array_merge ( $ this -> values , $ this -> refreshGeneratedFieldValues ( $ last_insert_id ) ) ; $ this -> setAsLoaded ( ) ; }


private function update()
    {
        if (count($this->modified_fields)) {
            $updates = [];

            foreach ($this->modified_fields as $modified_field) {
                $updates[$modified_field] = $this->values[$modified_field];
            }

            if ($this->primary_key_modified) {
                $old_id = isset($this->old_values['id']) ? $this->old_values['id'] : $this->getId();

                if ($this->pool->exists(get_class($this), $this->getId())) {
                    throw new LogicException('Object #' . $this->getId() . " can't be overwritten");
                } else {
                    $this->connection->update($this->table_name, $updates, $this->getWherePartById($old_id));
                }
            } else {
                $this->connection->update($this->table_name, $updates, $this->getWherePartById($this->getId()));
            }

            $this->values = array_merge($this->values, $this->refreshGeneratedFieldValues($this->getId()));
            $this->setAsLoaded();
        }
    }

private
function
update
(
)
{
if
(
count
(
$
this
->
modified_fields
)
)
{
$
updates
=
[
]
;
foreach
(
$
this
->
modified_fields
as
$
modified_field
)
{
$
updates
[
$
modified_field
]
=
$
this
->
values
[
$
modified_field
]
;
}
if
(
$
this
->
primary_key_modified
)
{
$
old_id
=
isset
(
$
this
->
old_values
[
'id'
]
)
$
this
->
old_values
[
'id'
]
:
$
this
->
getId
(
)
;
if
(
$
this
->
pool
->
exists
(
get_class
(
$
this
)
,
$
this
->
getId
(
)
)
)
{
throw
new
LogicException
(
'Object #'
.
$
this
->
getId
(
)
.
" can't be overwritten"
)
;
}
else
{
$
this
->
connection
->
update
(
$
this
->
table_name
,
$
updates
,
$
this
->
getWherePartById
(
$
old_id
)
)
;
}
}
else
{
$
this
->
connection
->
update
(
$
this
->
table_name
,
$
updates
,
$
this
->
getWherePartById
(
$
this
->
getId
(
)
)
)
;
}
$
this
->
values
=
array_merge
(
$
this
->
values
,
$
this
->
refreshGeneratedFieldValues
(
$
this
->
getId
(
)
)
)
;
$
this
->
setAsLoaded
(
)
;
}
}


private function refreshGeneratedFieldValues($id)
    {
        $result = [];

        if (!empty($this->generated_fields)) {
            $result = $this->connection->selectFirstRow($this->getTableName(), $this->generated_fields, $this->getWherePartById($id));

            if (empty($result)) {
                $result = [];
            }
        }

        $value_caster = $this->getGeneratedFieldsValueCaster();

        if ($value_caster instanceof ValueCasterInterface) {
            $value_caster->castRowValues($result);
        }

        return $result;
    }

private function refreshGeneratedFieldValues ( $ id ) { $ result = [ ] ; if ( ! empty ( $ this -> generated_fields ) ) { $ result = $ this -> connection -> selectFirstRow ( $ this -> getTableName ( ) , $ this -> generated_fields , $ this -> getWherePartById ( $ id ) ) ; if ( empty ( $ result ) ) { $ result = [ ] ; } } $ value_caster = $ this -> getGeneratedFieldsValueCaster ( ) ; if ( $ value_caster instanceof ValueCasterInterface ) { $ value_caster -> castRowValues ( $ result ) ; } return $ result ; }

Return an array with potentially refreshed values of generated fields.

@param  int   $id
@return array

Return an array with potentially refreshed values of generated fields .