Code cleanup.

This commit is contained in:
James Cole
2023-12-20 19:35:52 +01:00
parent c4f6366642
commit 64ec0cf62e
997 changed files with 12908 additions and 28136 deletions

View File

@@ -1,6 +1,5 @@
<?php
/*
* UserGroupRepository.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -34,7 +33,6 @@ use FireflyIII\Models\UserRole;
use FireflyIII\User;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Collection;
use ValueError;
/**
* Class UserGroupRepository
@@ -43,16 +41,14 @@ class UserGroupRepository implements UserGroupRepositoryInterface
{
private User $user;
/**
* @inheritDoc
*/
public function destroy(UserGroup $userGroup): void
{
app('log')->debug(sprintf('Going to destroy user group #%d ("%s").', $userGroup->id, $userGroup->title));
$memberships = $userGroup->groupMemberships()->get();
/** @var GroupMembership $membership */
foreach ($memberships as $membership) {
/** @var User|null $user */
/** @var null|User $user */
$user = $membership->user()->first();
if (null === $user) {
continue;
@@ -70,6 +66,7 @@ class UserGroupRepository implements UserGroupRepositoryInterface
// user has other memberships, select one at random and assign it to the user.
if ($count > 0) {
app('log')->debug('User has other memberships and will be assigned a new administration.');
/** @var GroupMembership $first */
$first = $user->groupMemberships()->where('user_group_id', '!=', $userGroup->id)->inRandomOrder()->first();
$user->user_group_id = $first->id;
@@ -82,10 +79,10 @@ class UserGroupRepository implements UserGroupRepositoryInterface
// time to DESTROY all objects.
// we have to do this one by one to trigger the necessary observers :(
$objects = ['availableBudgets', 'bills', 'budgets', 'categories', 'currencyExchangeRates', 'objectGroups',
'recurrences', 'rules', 'ruleGroups', 'tags', 'transactionGroups', 'transactionJournals', 'piggyBanks', 'accounts', 'webhooks',
'recurrences', 'rules', 'ruleGroups', 'tags', 'transactionGroups', 'transactionJournals', 'piggyBanks', 'accounts', 'webhooks',
];
foreach ($objects as $object) {
foreach ($userGroup->$object()->get() as $item) { // @phpstan-ignore-line
foreach ($userGroup->{$object}()->get() as $item) { // @phpstan-ignore-line
$item->delete();
}
}
@@ -96,91 +93,54 @@ class UserGroupRepository implements UserGroupRepositoryInterface
/**
* Returns all groups the user is member in.
*
* @inheritDoc
* {@inheritDoc}
*/
public function get(): Collection
{
$collection = new Collection();
$memberships = $this->user->groupMemberships()->get();
/** @var GroupMembership $membership */
foreach ($memberships as $membership) {
/** @var UserGroup|null $group */
/** @var null|UserGroup $group */
$group = $membership->userGroup()->first();
if (null !== $group) {
$collection->push($group);
}
}
return $collection;
}
/**
* Because there is the chance that a group with this name already exists,
* Firefly III runs a little loop of combinations to make sure the group name is unique.
*
* @param User $user
*
* @return UserGroup
*/
private function createNewUserGroup(User $user): UserGroup
{
$loop = 0;
$groupName = $user->email;
$exists = true;
$existingGroup = null;
while ($exists && $loop < 10) {
$existingGroup = $this->findByName($groupName);
if (null === $existingGroup) {
$exists = false;
/** @var UserGroup|null $existingGroup */
$existingGroup = $this->store(['user' => $user, 'title' => $groupName]);
}
if (null !== $existingGroup) {
// group already exists
$groupName = sprintf('%s-%s', $user->email, substr(sha1((rand(1000, 9999) . microtime())), 0, 4));
}
$loop++;
}
return $existingGroup;
}
/**
* @param string $title
*
* @return UserGroup|null
*/
public function findByName(string $title): ?UserGroup
{
return UserGroup::whereTitle($title)->first();
}
/**
* @param array $data
*
* @return UserGroup
* @throws FireflyException
*/
public function store(array $data): UserGroup
{
$data['user'] = $this->user;
/** @var UserGroupFactory $factory */
$factory = app(UserGroupFactory::class);
return $factory->create($data);
}
/**
* Returns all groups.
*
* @inheritDoc
* {@inheritDoc}
*/
public function getAll(): Collection
{
return UserGroup::all();
}
/**
* @inheritDoc
*/
public function setUser(Authenticatable | User | null $user): void
public function setUser(null|Authenticatable|User $user): void
{
app('log')->debug(sprintf('Now in %s', __METHOD__));
if ($user instanceof User) {
@@ -188,39 +148,38 @@ class UserGroupRepository implements UserGroupRepositoryInterface
}
}
/**
* @inheritDoc
*/
public function update(UserGroup $userGroup, array $data): UserGroup
{
$userGroup->title = $data['title'];
$userGroup->save();
return $userGroup;
}
/**
* @inheritDoc
* @throws FireflyException
*/
public function updateMembership(UserGroup $userGroup, array $data): UserGroup
{
$owner = UserRole::whereTitle(UserRoleEnum::OWNER)->first();
app('log')->debug('in update membership');
/** @var User|null $user */
/** @var null|User $user */
$user = null;
if (array_key_exists('id', $data)) {
/** @var User|null $user */
/** @var null|User $user */
$user = User::find($data['id']);
app('log')->debug('Found user by ID');
}
if (array_key_exists('email', $data) && '' !== (string)$data['email']) {
/** @var User|null $user */
/** @var null|User $user */
$user = User::whereEmail($data['email'])->first();
app('log')->debug('Found user by email');
}
if (null === $user) {
// should throw error, but validator already catches this.
app('log')->debug('No user found');
return $userGroup;
}
// count the number of members in the group right now:
@@ -232,26 +191,30 @@ class UserGroupRepository implements UserGroupRepositoryInterface
// if this is also the user we're editing right now, and we remove all of their roles:
if ($lastUserId === (int)$user->id && 0 === count($data['roles'])) {
app('log')->debug('User is last in this group, refuse to act');
throw new FireflyException('You cannot remove the last member from this user group. Delete the user group instead.');
}
// if this is also the user we're editing right now, and do not grant them the owner role:
if ($lastUserId === (int)$user->id && count($data['roles']) > 0 && !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)) {
app('log')->debug('User needs to have owner role in this group, refuse to act');
throw new FireflyException('The last member in this user group must get or keep the "owner" role.');
}
}
if ($membershipCount > 1) {
// group has multiple members. How many are owner, except the user we're editing now?
$ownerCount = $userGroup->groupMemberships()
->where('user_role_id', $owner->id)
->where('user_id', '!=', $user->id)->count();
->where('user_role_id', $owner->id)
->where('user_id', '!=', $user->id)->count()
;
// if there are no other owners and the current users does not get or keep the owner role, refuse.
if (
0 === $ownerCount &&
(0 === count($data['roles']) ||
(count($data['roles']) > 0 && // @phpstan-ignore-line
!in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) {
0 === $ownerCount
&& (0 === count($data['roles'])
|| (count($data['roles']) > 0 // @phpstan-ignore-line
&& !in_array(UserRoleEnum::OWNER->value, $data['roles'], true)))) {
app('log')->debug('User needs to keep owner role in this group, refuse to act');
throw new FireflyException('The last owner in this user group must keep the "owner" role.');
}
}
@@ -263,31 +226,58 @@ class UserGroupRepository implements UserGroupRepositoryInterface
foreach ($rolesSimplified as $role) {
try {
$enum = UserRoleEnum::from($role);
} catch (ValueError $e) {
} catch (\ValueError $e) {
// TODO error message
continue;
}
$userRole = UserRole::whereTitle($enum->value)->first();
$user->groupMemberships()->create(['user_group_id' => $userGroup->id, 'user_role_id' => $userRole->id]);
}
return $userGroup;
}
/**
* @param array $roles
*
* @return array
* Because there is the chance that a group with this name already exists,
* Firefly III runs a little loop of combinations to make sure the group name is unique.
*/
private function createNewUserGroup(User $user): UserGroup
{
$loop = 0;
$groupName = $user->email;
$exists = true;
$existingGroup = null;
while ($exists && $loop < 10) {
$existingGroup = $this->findByName($groupName);
if (null === $existingGroup) {
$exists = false;
/** @var null|UserGroup $existingGroup */
$existingGroup = $this->store(['user' => $user, 'title' => $groupName]);
}
if (null !== $existingGroup) {
// group already exists
$groupName = sprintf('%s-%s', $user->email, substr(sha1(rand(1000, 9999).microtime()), 0, 4));
}
++$loop;
}
return $existingGroup;
}
private function simplifyListByName(array $roles): array
{
if (in_array(UserRoleEnum::OWNER->value, $roles, true)) {
app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::OWNER->value));
return [UserRoleEnum::OWNER->value];
}
if (in_array(UserRoleEnum::FULL->value, $roles, true)) {
app('log')->debug(sprintf('List of roles is [%1$s] but this includes "%2$s", so return [%2$s]', implode(',', $roles), UserRoleEnum::FULL->value));
return [UserRoleEnum::FULL->value];
}
return $roles;
}
}

View File

@@ -1,6 +1,5 @@
<?php
/*
* UserGroupRepositoryInterface.php
* Copyright (c) 2023 james@firefly-iii.org
@@ -35,50 +34,17 @@ use Illuminate\Support\Collection;
*/
interface UserGroupRepositoryInterface
{
/**
* @param UserGroup $userGroup
*
* @return void
*/
public function destroy(UserGroup $userGroup): void;
/**
* @return Collection
*/
public function get(): Collection;
/**
* @return Collection
*/
public function getAll(): Collection;
/**
* @param User|Authenticatable|null $user
*
* @return void
*/
public function setUser(User | Authenticatable | null $user): void;
public function setUser(null|Authenticatable|User $user): void;
/**
* @param array $data
*
* @return UserGroup
*/
public function store(array $data): UserGroup;
/**
* @param UserGroup $userGroup
* @param array $data
*
* @return UserGroup
*/
public function update(UserGroup $userGroup, array $data): UserGroup;
/**
* @param UserGroup $userGroup
* @param array $data
*
* @return UserGroup
*/
public function updateMembership(UserGroup $userGroup, array $data): UserGroup;
}