/** * Get the callback to constrain an abilities query to the given ability. * * @param string $ability * @param \Illuminate\Database\Eloquent\Model|string|null $model * @return \Closure */ protected function getAbilityConstraint($ability, $model) { return function ($query) use($ability, $model) { $table = Models::ability()->getTable(); $query->where("{$table}.name", $ability); if (!is_null($model)) { $query->forModel($model); } }; }
/** * Create abilities whose name is not in the given list. * * @param \Illuminate\Database\Eloquent\Collection $models * @param array $abilities * @return \Illuminate\Database\Eloquent\Collection */ protected function createMissingAbilities(Collection $models, array $abilities) { $missing = array_diff($abilities, $models->pluck('name')->all()); $created = []; foreach ($missing as $ability) { $created[] = Models::ability()->create(['name' => $ability]); } return $created; }
/** * Get a list of the user's abilities. * * @param \Illuminate\Database\Eloquent\Model $user * @return \Illuminate\Database\Eloquent\Collection */ public function getAbilities(Model $user) { $query = Models::ability()->whereHas('roles', $this->getRoleUsersConstraint($user)); return $query->orWhereHas('users', $this->getUserConstraint($user))->get(); }
/** * Get the table name for the ability model. * * @return string */ protected function abilities() { return Models::ability()->getTable(); }
/** * Get the ability IDs from the names present in the given array. * * @param array $abilities * @return array */ protected function getAbilityIdsFromStrings(array $abilities) { $names = array_filter($abilities, 'is_string'); if (!count($names)) { return []; } return Models::ability()->whereIn('name', $names)->get(['id'])->pluck('id')->all(); }
/** * Get an instance of the ability model. * * @param array $attributes * @return \Silber\Bouncer\Database\Ability */ public function ability(array $attributes = []) { return Models::ability($attributes); }
/** * Deserialize an array of abilities into a collection of models. * * @param array $abilities * @return \Illuminate\Database\Eloquent\Collection */ protected function deserializeAbilities(array $abilities) { return Models::ability()->hydrate($abilities); }
/** * Get a list of the authority's abilities. * * @param \Illuminate\Database\Eloquent\Model $authority * @param bool $allowed * @return \Illuminate\Database\Eloquent\Collection */ public function getForAuthority(Model $authority, $allowed = true) { return Models::ability()->whereExists($this->getRoleConstraint($authority, $allowed))->orWhereExists($this->getAuthorityConstraint($authority, $allowed))->get(); }