discord-php / DiscordPHP

An API to interact with the popular messaging app Discord
MIT License
992 stars 236 forks source link

Enhancement to addRole and removeRole methods for Member class #1237

Open valzargaming opened 3 months ago

valzargaming commented 3 months ago

This improvement aims to optimize the Member class methods, specifically addRole and removeRole, making them more versatile and aligned with expected behavior, thereby enhancing the overall usability of the library. This change would allow these functions to return a resolved Member part while preserving their original functionality. Currently, due to their use of PUT and DELETE endpoints, these methods do not return an updated member part. The proposed change introduces the ability to pass true as the third parameter, enabling the use of array_merge or array_diff operations and facilitating the return of an updated member part by calling the PATCH endpoint instead.

This enhancement grants additional functionality by allowing the methods to return a resolved member, thereby enhancing the library’s capabilities without compromising its existing structure. Doing so would also add better support for chaining of promises in this context.

It's important to note that chaining multiple addRole or removeRole promises together will always be slower and result in additional API calls where it would otherwise be better to make a single call to setRoles. This change is not intended to replace or undermine the intended usage of setRole, but reduce the amount of code required for a user of the library to effectively utilize these functions.

valzargaming commented 3 months ago

I've been looking for a flexible userland solution that could effectively be used instead which would obtain the same result without this PR being merged. This is what I've come up so far:

Example userland change: https://github.com/Valgorithms/Civilizationbot/commit/484658b100b5ada49f0fe73dbb535f55ef3fb004#diff-9dd715a3e3306afab65ec3cbe9264a6f8a0fd46df31e0c942eedbc1c94b07787

/**
 * Removes specified roles from a member.
 *
 * @param Member $member The member object from which the roles will be removed.
 * @param Collection<Role>|array<Role|string|int>|Role|string|int $roles An array of role IDs to be removed.
 * @param bool $patch Determines whether to use patch mode or not. If true, the member's roles will be updated using setRoles method. If false, the member's roles will be updated using removeRole method.
 * @return PromiseInterface<Member> A promise that resolves to the updated member object.
 */
public function removeRoles(Member $member, Collection|array|Role|string|int $roles, bool $patch = true): PromiseInterface
{
    if (! $roles) return \React\Promise\resolve($member);
    $role_ids = [];
    switch (true) {
        case ($roles instanceof Collection && $roles->first() instanceof Role):
            $role_ids = $roles->map(fn($role) => $role->id)->toArray();
            break;
        case (! $roles instanceof Collection && is_array($roles) && $roles[0] instanceof Role):
            $role_ids = array_map(fn($role) => $role->id, $roles);
            break;
        case (is_array($roles)):
            $role_ids = array_map('strval', $roles);
            break;
        case ($roles instanceof Role):
            $role_ids[] = $roles->id;
            break;
        case (is_string($roles) || is_int($roles)):
            $role_ids[] = "$roles";
            break;
        default:
            $this->logger->warning('Roles not found for removeRoles: ' . json_encode($roles));
            return \React\Promise\resolve($member);
    }
    foreach ($role_ids as &$role_id) if (! $member->roles->has($role_id)) unset($role_id);
    if (! $role_ids) {
        $this->logger->warning('No roles to remove for removeRoles');
        return \React\Promise\resolve($member);
    }

    return $patch
        ? ((($new_roles = $member->roles->filter(function (Role $role) use ($role_ids) { return ! in_array($role->id, $role_ids); })->toArray()) !== $member->roles) ? $member->setRoles($new_roles) : \React\Promise\resolve($member))
        : \React\Promise\all(array_map(fn($role) => $member->removeRole($role->id), $role_ids))
            ->then(function() use ($member) {
                return $member->guild->members->get('id', $member->id);
            });
}
/**
 * Adds specified roles to a member.
 *
 * @param Member $member The member object to which the roles will be added.
 * @param Collection<Role>|array<Role|string|int>|Role|string|int $roles An array of role IDs to be added.
 * @param bool $patch Determines whether to use patch mode or not. If true, the member's roles will be updated using setRoles method. If false, the member's roles will be updated using addRole method.
 * @return PromiseInterface<Member> A promise that resolves to the updated member object.
 */
public function addRoles(Member $member, Collection|array|Role|string|int $roles, bool $patch = true): PromiseInterface
{
    if (! $roles) return \React\Promise\resolve($member);
    $role_ids = [];
    switch (true) {
        case ($roles instanceof Collection && $roles->first() instanceof Role):
            $role_ids = $roles->map(fn($role) => $role->id)->toArray();
            break;
        case (! $roles instanceof Collection && is_array($roles) && $roles[0] instanceof Role):
            $role_ids = array_map(fn($role) => $role->id, $roles);
            break;
        case (is_array($roles)):
            $role_ids = array_map('strval', $roles);
            break;
        case ($roles instanceof Role):
            $role_ids[] = $roles->id;
            break;
        case (is_string($roles) || is_int($roles)):
            $role_ids[] = "$roles";
            break;
        default:
            $this->logger->warning('Roles not found for addRoles: ' . json_encode($roles));
            return \React\Promise\resolve($member);
    }
    foreach ($role_ids as &$role_id) if ($member->roles->has($role_id)) unset($role_id);
    if (! $role_ids) {
        $this->logger->warning('No roles to add for addRoles');
        return \React\Promise\resolve($member);
    }

    return $patch
        ? $member->setRoles(array_merge(array_values($member->roles->map(fn($role) => $role->id)->toArray()), $role_ids))
        : \React\Promise\all(array_map(fn($role) => $member->addRole($role->id), $role_ids))
            ->then(function() use ($member) {
                return $member->guild->members->get('id', $member->id);
            });
}