. */ declare(strict_types=1); namespace FireflyIII\Support\Repositories\UserGroup; use FireflyIII\Exceptions\FireflyException; use FireflyIII\Models\GroupMembership; use FireflyIII\Models\UserGroup; use FireflyIII\User; use Illuminate\Contracts\Auth\Authenticatable; /** * Trait UserGroupTrait */ trait UserGroupTrait { protected User $user; protected UserGroup $userGroup; public function getUserGroup(): UserGroup { return $this->userGroup; } /** * TODO This method does not check if the user has access to this particular user group. */ public function setUserGroup(UserGroup $userGroup): void { $this->userGroup = $userGroup; } /** * @throws FireflyException */ public function setUser(null|Authenticatable|User $user): void { if ($user instanceof User) { $this->user = $user; if (null === $user->userGroup) { throw new FireflyException(sprintf('User #%d has no user group.', $user->id)); } $this->userGroup = $user->userGroup; } } /** * @throws FireflyException */ public function setUserGroupById(int $userGroupId): void { $memberships = GroupMembership::where('user_id', $this->user->id) ->where('user_group_id', $userGroupId) ->count() ; if (0 === $memberships) { throw new FireflyException(sprintf('User #%d has no access to administration #%d', $this->user->id, $userGroupId)); } /** @var null|UserGroup $userGroup */ $userGroup = UserGroup::find($userGroupId); if (null === $userGroup) { throw new FireflyException(sprintf('Cannot find administration for user #%d', $this->user->id)); } $this->userGroup = $userGroup; } }