Add group gambit to support search user by group name (#1073)

Add group gambit to support search user by group name

/api/users?filter[q]=group:admin
/api/users?filter[q]=group:admin,mod

refer to #256
This commit is contained in:
Li Ji 2017-01-04 04:13:58 +08:00 committed by Franz Liedke
parent 1361ff3bf6
commit 204f63fa29
3 changed files with 76 additions and 1 deletions

View File

@ -44,6 +44,19 @@ class GroupRepository
return $this->scopeVisibleTo($query, $actor)->firstOrFail();
}
/**
* Find a group by name.
*
* @param string $name
* @return User|null
*/
public function findByName($name, User $actor = null)
{
$query = Group::where('name_singular', $name)->orWhere('name_plural', $name);
return $this->scopeVisibleTo($query, $actor)->first();
}
/**
* Scope a query to only include records that are visible to a user.
*

View File

@ -44,7 +44,7 @@ class SearchServiceProvider extends AbstractServiceProvider
$gambits->setFulltextGambit('Flarum\Core\Search\User\Gambit\FulltextGambit');
$gambits->add('Flarum\Core\Search\User\Gambit\EmailGambit');
$gambits->add('Flarum\Core\Search\User\Gambit\GroupGambit');
$app->make('events')->fire(
new ConfigureUserGambits($gambits)
);

View File

@ -0,0 +1,62 @@
<?php
/*
* This file is part of Flarum.
*
* (c) Toby Zerner <toby.zerner@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Flarum\Core\Search\User\Gambit;
use Flarum\Core\Repository\GroupRepository;
use Flarum\Core\Search\AbstractRegexGambit;
use Flarum\Core\Search\AbstractSearch;
use Flarum\Core\Search\User\UserSearch;
use LogicException;
class GroupGambit extends AbstractRegexGambit
{
/**
* {@inheritdoc}
*/
protected $pattern = 'group:(.+)';
/**
* @var GroupRepository
*/
protected $groups;
/**
* @param \Flarum\Core\Repository\GroupRepository $groups
*/
public function __construct(GroupRepository $groups)
{
$this->groups = $groups;
}
/**
* {@inheritdoc}
*/
protected function conditions(AbstractSearch $search, array $matches, $negate)
{
if (! $search instanceof UserSearch) {
throw new LogicException('This gambit can only be applied on a UserSearch');
}
$groupName = trim($matches[1], '"');
$groupName = explode(',', $groupName);
$ids = [];
foreach ($groupName as $name) {
$group = $this->groups->findByName($name);
if ($group && count($group->users)) {
$ids = array_merge($ids, $group->users->pluck('id')->all());
}
}
$search->getQuery()->whereIn('id', $ids, 'and', $negate);
}
}