Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release 2.8.0: Add query filtering on role to members.listMembers #96

Merged
merged 11 commits into from
Jun 19, 2024
44 changes: 35 additions & 9 deletions SilMock/Google/Service/Directory/Resource/Members.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,20 +69,20 @@ public function listMembers($groupKey, $optParams = [])
$this->validateGroupExists($groupKey);
$pageSize = $optParams['pageSize'] ?? 10;
$pageToken = $optParams['pageToken'] ?? 0;
$query = $optParams['query'] ?? null;
$expectedRoles = $this->extractRoles($query);
$members = new GoogleDirectory_Members();
$directoryMemberRecords = $this->getRecords();
$memberCounter = 0;
foreach ($directoryMemberRecords as $memberRecord) {
$memberData = json_decode($memberRecord['data'], true);
if ($memberData['groupKey'] === $groupKey) {
$memberCounter = $memberCounter + 1;
if ($memberCounter >= ($pageToken * $pageSize)) {
$currentMembers = $members->getMembers();
$currentMember = new GoogleDirectory_Member();
ObjectUtils::initialize($currentMember, $memberData['member']);
$currentMembers[] = $currentMember;
$members->setMembers($currentMembers);
}
if (
$memberData['groupKey'] === $groupKey // Matches the expected group
&& $memberCounter >= ($pageToken * $pageSize) // Matches the subsection of all the members
&& (empty($expectedRoles) || in_array($memberData['member']['role'], $expectedRoles)) // Matches role
) {
$memberCounter = $memberCounter + 1;
$this->addToMembers($memberData, $members);
}
$currentMembers = $members->getMembers();
$currentResultSize = count($currentMembers);
Expand All @@ -98,6 +98,32 @@ public function listMembers($groupKey, $optParams = [])
return $members;
}

protected function extractRoles(?string $query): array
{
if (! empty($query) && str_contains($query, 'roles')) {
$roleSegmentStart = substr($query, strpos($query, 'roles'));
$roleSegmentEnd = strrpos($roleSegmentStart, ' ');
if ($roleSegmentEnd === false) {
$roleSegmentEnd = strlen($roleSegmentStart);
}
$roleSegment = trim(substr($roleSegmentStart, 0, $roleSegmentEnd));
$roleValue = substr($roleSegment, 6); // roles= is 0-5
$expectedRoles = explode(',', $roleValue);
} else {
$expectedRoles = [];
}
return $expectedRoles;
}

protected function addToMembers(array $memberData, GoogleDirectory_Members $members): void
{
$currentMembers = $members->getMembers();
$currentMember = new GoogleDirectory_Member();
ObjectUtils::initialize($currentMember, $memberData['member']);
$currentMembers[] = $currentMember;
$members->setMembers($currentMembers);
}

protected function validateGroupExists(string $groupKey): void
{
$mockGroupsObject = new Groups($this->dbFile);
Expand Down
2 changes: 1 addition & 1 deletion SilMock/Google/Service/Directory/Tokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ protected function assertIsValidUserKey(string $userId)
*/
protected function isValidEmailAddress(string $email): bool
{
return (filter_var($email, FILTER_VALIDATE_EMAIL) !== false);
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

protected function listTokensFor(string $userId): array
Expand Down
8 changes: 5 additions & 3 deletions SilMock/Google/Service/Directory/UsersAliasesResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

class UsersAliasesResource extends DbClass
{
public const ACCOUNT_DOESNT_EXIST = "Account doesn't exist: ";

public function __construct(?string $dbFile = null)
{
parent::__construct($dbFile, 'directory', 'users_alias');
Expand All @@ -37,7 +39,7 @@ public function delete($userKey, $alias)
$matchingUsers = $dir->users->get($userKey);

if ($matchingUsers === null) {
throw new Exception("Account doesn't exist: " . $userKey, 201407101645);
throw new Exception(self::ACCOUNT_DOESNT_EXIST . $userKey, 201407101645);
}

// Get all the aliases for that user
Expand Down Expand Up @@ -87,7 +89,7 @@ public function insert($userKey, $postBody)
$matchingUsers = $dir->users->get($userKey);

if ($matchingUsers === null) {
throw new Exception("Account doesn't exist: " . $userKey, 201407110830);
throw new Exception(self::ACCOUNT_DOESNT_EXIST . $userKey, 201407110830);
}

if ($postBody->$key === null) {
Expand Down Expand Up @@ -145,7 +147,7 @@ public function listUsersAliases($userKey): ?Google_Service_Directory_Aliases
$matchingUsers = $dir->users->get($userKey);

if ($matchingUsers === null) {
throw new Exception("Account doesn't exist: " . $userKey, 201407101420);
throw new Exception(self::ACCOUNT_DOESNT_EXIST . $userKey, 201407101420);
}

$foundAliases = $this->fetchAliasesByUser($key, $userKey);
Expand Down
17 changes: 10 additions & 7 deletions SilMock/Google/Service/Directory/UsersResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,18 +112,20 @@ protected function getDbUserByAlias($userKey)
}

$allUsers = $this->getAllDbUsers();

foreach ($allUsers as $aUser) {
if (! isset($aUser['data'])) {
continue;
$usersWithData = array_filter(
$allUsers,
function ($user) {
return isset($user['data']);
}

);

foreach ($usersWithData as $aUser) {
$userData = json_decode($aUser['data'], true);
if ($userData === null) {
continue;
}

$primaryEmail = isset($userData['primaryEmail']) ? $userData['primaryEmail'] : null;
$primaryEmail = $userData['primaryEmail'] ?? null;

$aliasesResource = $this->getAliasesForUser($primaryEmail);
if ($aliasesResource) {
Expand Down Expand Up @@ -408,7 +410,8 @@ private function doesUserMatch($entry, $query = '')
}
} elseif (is_array($checkValue)) {
throw new \Exception(
"Did not expect something other than name as an array. Got VALUE: " . var_dump($checkValue)
"Did not expect something other than name as an array. Got VALUE: "
. var_export($checkValue, true)
);
}
} elseif (isset($entry['name'][$field])) {
Expand Down
64 changes: 56 additions & 8 deletions SilMock/tests/Google/Service/Directory/Resource/MembersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ public function testInsert()

$member = new GoogleDirectory_Member();
$member->setEmail($emailAddress);
$member->setRole('MEMBER');

$mockGoogleServiceDirectory = new GoogleMock_Directory('anyclient', $this->dataFile);
try {
Expand Down Expand Up @@ -72,24 +73,71 @@ public function testHasMember()
self::assertTrue($hasMember);
}

public function testListMembers()
public function testListMembersAll()
{
$groupEmailAddress = '[email protected]';
$mockGoogleServiceDirectory = new GoogleMock_Directory('anyclient', $this->dataFile);
$members = [];
try {
$members = $mockGoogleServiceDirectory->members->listMembers($groupEmailAddress);
} catch (Exception $exception) {
self::fail(
sprintf(
'Was expecting the members.list method to function, but got: %s',
$exception->getMessage()
)
$this->failure($exception);
}
self::assertNotEmpty(
$members->getMembers(),
'Was expecting the members.list method to have at least one member entry.'
);
}

public function testListMembersOnlyMember()
{
$groupEmailAddress = '[email protected]';
$mockGoogleServiceDirectory = new GoogleMock_Directory('anyclient', $this->dataFile);
$members = [];
try {
$members = $mockGoogleServiceDirectory->members->listMembers(
$groupEmailAddress,
[
'query' => 'roles=MEMBER'
]
);
} catch (Exception $exception) {
$this->failure($exception);
}
self::assertNotEmpty(
$members,
'Was expecting the members.list method to have at least one member.'
$members->getMembers(),
'Was expecting the members.list method to have at least one member type entry.'
);
}

public function testListMembersOnlyOwner()
{
$groupEmailAddress = '[email protected]';
$mockGoogleServiceDirectory = new GoogleMock_Directory('anyclient', $this->dataFile);
$members = [];
try {
$members = $mockGoogleServiceDirectory->members->listMembers(
$groupEmailAddress,
[
'query' => 'roles=OWNER'
]
);
} catch (Exception $exception) {
$this->failure($exception);
}
self::assertEmpty(
$members->getMembers(),
'Was expecting the members.list method to have no owner types.'
);
}

protected function failure(Exception $exception): void
{
self::fail(
sprintf(
'Was expecting the members.insert method to function, but got: %s',
$exception->getMessage()
)
);
}
}