From fd36a45eef99bae2af53f9470afb1497e9f9bdff Mon Sep 17 00:00:00 2001 From: Nikolay Nesov Date: Tue, 11 Oct 2016 14:05:22 +0000 Subject: [PATCH] Add method to get groups for a specific friend --- README.md | 5 +++++ src/Traits/Friendable.php | 24 ++++++++++++++++++++++++ tests/FriendshipsGroupsTest.php | 30 ++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+) diff --git a/README.md b/README.md index bcf45ff..92529c4 100644 --- a/README.md +++ b/README.md @@ -217,6 +217,11 @@ $user->ungroupFriend($friend, 'family'); $user->ungroupFriend($friend); ``` +#### Get groups for specific friend +```php +$user->getGroupsFor($friend); +``` + #### Get the number of Friends in specific group ```php $user->getFriendsCount($group_name); diff --git a/src/Traits/Friendable.php b/src/Traits/Friendable.php index 8770415..aa8ed5b 100644 --- a/src/Traits/Friendable.php +++ b/src/Traits/Friendable.php @@ -353,6 +353,30 @@ public function getFriendsCount($group = '') return $friendsCount; } + + /** + * Get groups for Friend + * + * @param Model $model + * @return array + */ + public function getGroupsFor(Model $model) { + + $result = []; + $friendship = $this->getFriendship($model); + if(!empty($friendship)) { + $groups = $friendship->groups() + ->where('friend_id', $model->getKey()) + ->where('friend_type', $model->getMorphClass()) + ->get(); + if(false === $groups->isEmpty()) + $result = $groups->pluck('group_slug')->all(); + } + + return $result; + + } + /** * @param Model $recipient * diff --git a/tests/FriendshipsGroupsTest.php b/tests/FriendshipsGroupsTest.php index b41f12a..26658be 100644 --- a/tests/FriendshipsGroupsTest.php +++ b/tests/FriendshipsGroupsTest.php @@ -241,5 +241,35 @@ public function it_returns_user_friends_by_group_per_page() $this->containsOnlyInstancesOf(\App\User::class, $sender->getFriends(0, 'acquaintances')); } + /** @test */ + public function returns_groups_for_specific_friend() { + + $sender = createUser(); + $recipients = createUser([], 2); + $groupsAvailable = config('friendships.groups', []); + + foreach ($recipients as $recipient) { + $sender->befriend($recipient); + $recipient->acceptFriendRequest($sender); + } + + $sender->groupFriend($recipients[0], 'acquaintances'); + $sender->groupFriend($recipients[0], 'close_friends'); + + $sender->groupFriend($recipients[1], 'family'); + + $recipients[0]->groupFriend($sender, 'close_friends'); + + $rec1 = $sender->getGroupsFor($recipients[1]); + + $this->assertCount(2, $sender->getGroupsFor($recipients[0])); + $this->assertCount(1, $recipients[0]->getGroupsFor($sender)); + $this->assertCount(0, $recipients[1]->getGroupsFor($sender)); + + $this->assertInternalType('array', $rec1); + $this->assertContains($rec1[0], $groupsAvailable); + + } + } \ No newline at end of file