Implement user searching & minor search refactor

This commit is contained in:
Toby Zerner 2015-03-12 10:37:02 +10:30
parent 96ce220c8d
commit 2900467678
18 changed files with 291 additions and 69 deletions

View File

@ -12,14 +12,14 @@ class IndexAction extends BaseAction
/**
* The discussion searcher.
*
* @var DiscussionSearcher
* @var \Flarum\Core\Search\Discussions\DiscussionSearcher
*/
protected $searcher;
/**
* Instantiate the action.
*
* @param DiscussionSearcher $searcher
* @param \Flarum\Core\Search\Discussions\DiscussionSearcher $searcher
*/
public function __construct(Actor $actor, DiscussionSearcher $searcher)
{
@ -30,8 +30,7 @@ class IndexAction extends BaseAction
/**
* Show a list of discussions.
*
* @todo custom rate limit for this function? determined by if $key was valid?
* @return Response
* @return \Illuminate\Http\Response
*/
protected function run(ApiParams $params)
{
@ -43,7 +42,7 @@ class IndexAction extends BaseAction
$relations = array_merge(['startUser', 'lastUser'], $include);
// Set up the discussion finder with our search criteria, and get the
// Set up the discussion searcher with our search criteria, and get the
// requested range of results with the necessary relations loaded.
$criteria = new DiscussionSearchCriteria($this->actor->getUser(), $query, $sort['field'], $sort['order']);
$load = array_merge($relations, ['state']);

View File

@ -1,83 +1,79 @@
<?php namespace Flarum\Api\Actions\Users;
use Flarum\Core\Users\User;
use Flarum\Core\Users\UserFinder;
use Flarum\Api\Actions\Base;
use Flarum\Core\Search\Users\UserSearchCriteria;
use Flarum\Core\Search\Users\UserSearcher;
use Flarum\Core\Support\Actor;
use Flarum\Api\Actions\BaseAction;
use Flarum\Api\Actions\ApiParams;
use Flarum\Api\Serializers\UserSerializer;
class IndexAction extends BaseAction
{
/**
* The user finder.
* The user searcher.
*
* @var UserFinder
* @var \Flarum\Core\Search\Discussions\UserSearcher
*/
protected $finder;
protected $searcher;
/**
* Instantiate the action.
*
* @param UserFinder $finder
* @param \Flarum\Core\Search\Discussions\UserSearcher $searcher
*/
public function __construct(UserFinder $finder)
public function __construct(Actor $actor, UserSearcher $searcher)
{
$this->finder = $finder;
$this->actor = $actor;
$this->searcher = $searcher;
}
/**
* Show a list of users.
*
* @todo custom rate limit for this function? determined by if $key was valid?
* @return Response
* @return \Illuminate\Http\Response
*/
protected function run()
protected function run(ApiParams $params)
{
$query = $this->input('q');
$key = $this->input('key');
$sort = $this->sort(['', 'username', 'posts', 'discussions', 'lastActive', 'created']);
$start = $this->start();
$count = $this->count(50, 100);
$include = $this->included(['groups']);
$query = $params->get('q');
$start = $params->start();
$include = $params->included(['groups']);
$count = $params->count(20, 50);
$sort = $params->sort(['', 'username', 'posts', 'discussions', 'lastActive', 'created']);
$relations = array_merge(['groups'], $include);
// Set up the user finder with our search criteria, and get the
// Set up the user searcher with our search criteria, and get the
// requested range of results with the necessary relations loaded.
$this->finder->setUser(User::current());
$this->finder->setQuery($query);
$this->finder->setSort($sort['by']);
$this->finder->setOrder($sort['order']);
$this->finder->setKey($key);
$criteria = new UserSearchCriteria($this->actor->getUser(), $query, $sort['field'], $sort['order']);
$users = $this->finder->results($count, $start);
$users->load($relations);
$results = $this->searcher->search($criteria, $count, $start, $relations);
if (($total = $this->finder->getCount()) !== null) {
$this->document->addMeta('total', $total);
}
if (($key = $this->finder->getKey()) !== null) {
$this->document->addMeta('key', $key);
$document = $this->document();
if (($total = $results->getTotal()) !== null) {
$document->addMeta('total', $total);
}
// If there are more results, then we need to construct a URL to the
// next results page and add that to the metadata. We do this by
// compacting all of the valid query parameters which have been
// specified.
if ($this->finder->areMoreResults()) {
if ($results->areMoreResults()) {
$start += $count;
$include = implode(',', $include);
$sort = $sort['string'];
$input = array_filter(compact('query', 'key', 'sort', 'start', 'count', 'include'));
$input = array_filter(compact('query', 'sort', 'start', 'count', 'include'));
$moreUrl = $this->buildUrl('users.index', [], $input);
} else {
$moreUrl = '';
}
$this->document->addMeta('moreUrl', $moreUrl);
$document->addMeta('moreUrl', $moreUrl);
// Finally, we can set up the user serializer and use it to create
// a collection of user results.
// Finally, we can set up the discussion serializer and use it to create
// a collection of discussion results.
$serializer = new UserSerializer($relations);
$this->document->setPrimaryElement($serializer->collection($users));
$document->setPrimaryElement($serializer->collection($results->getUsers()));
return $this->respondWithDocument();
return $this->respondWithDocument($document);
}
}

View File

@ -25,7 +25,13 @@ class ShowAction extends BaseAction
*/
public function run(ApiParams $params)
{
$user = $this->users->findOrFail($params->get('id'), $this->actor->getUser());
$id = $params->get('id');
if (! is_numeric($id)) {
$id = $this->users->getIdForUsername($id);
}
$user = $this->users->findOrFail($id, $this->actor->getUser());
// Set up the user serializer, which we will use to create the
// document's primary resource. We will specify that we want the

View File

@ -77,13 +77,23 @@ class CoreServiceProvider extends ServiceProvider
public function registerGambits()
{
$this->app->bind('Flarum\Core\Search\GambitManager', function () {
$gambits = new GambitManager($this->app);
$gambits->add('Flarum\Core\Search\Discussions\Gambits\AuthorGambit');
$gambits->add('Flarum\Core\Search\Discussions\Gambits\UnreadGambit');
$gambits->setFulltextGambit('Flarum\Core\Search\Discussions\Gambits\FulltextGambit');
return $gambits;
});
$this->app->when('Flarum\Core\Search\Discussions\DiscussionSearcher')
->needs('Flarum\Core\Search\GambitManager')
->give(function () {
$gambits = new GambitManager($this->app);
$gambits->add('Flarum\Core\Search\Discussions\Gambits\AuthorGambit');
$gambits->add('Flarum\Core\Search\Discussions\Gambits\UnreadGambit');
$gambits->setFulltextGambit('Flarum\Core\Search\Discussions\Gambits\FulltextGambit');
return $gambits;
});
$this->app->when('Flarum\Core\Search\Users\UserSearcher')
->needs('Flarum\Core\Search\GambitManager')
->give(function () {
$gambits = new GambitManager($this->app);
$gambits->setFulltextGambit('Flarum\Core\Search\Users\Gambits\FulltextGambit');
return $gambits;
});
}
public function registerPostTypes()

View File

@ -5,7 +5,7 @@ use Flarum\Core\Models\User;
interface DiscussionRepositoryInterface
{
/**
* Get a new query builder for ths discussions table.
* Get a new query builder for the discussions table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/

View File

@ -7,7 +7,7 @@ use Flarum\Core\Models\User;
class EloquentDiscussionRepository implements DiscussionRepositoryInterface
{
/**
* Get a new query builder for ths discussions table.
* Get a new query builder for the discussions table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/

View File

@ -5,6 +5,16 @@ use Flarum\Core\Models\User;
class EloquentUserRepository implements UserRepositoryInterface
{
/**
* Get a new query builder for the users table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function query()
{
return User::query();
}
/**
* Find a user by ID, optionally making sure it is visible to a certain
* user, or throw an exception.
@ -49,6 +59,24 @@ class EloquentUserRepository implements UserRepositoryInterface
return $this->scopeVisibleForUser($query, $user)->pluck('id');
}
/**
* Find users by matching a string of words against their username,
* optionally making sure they are visible to a certain user.
*
* @param string $string
* @param \Flarum\Core\Models\User|null $user
* @return array
*/
public function getIdsForUsername($string, User $user = null)
{
$query = User::select('id')
->where('username', 'like', '%'.$string.'%')
->orderByRaw('username = ? desc', [$string])
->orderByRaw('username like ? desc', [$string.'%']);
return $this->scopeVisibleForUser($query, $user)->lists('id');
}
/**
* Scope a query to only include records that are visible to a user.
*

View File

@ -4,6 +4,13 @@ use Flarum\Core\Models\User;
interface UserRepositoryInterface
{
/**
* Get a new query builder for the users table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function query();
/**
* Find a user by ID, optionally making sure it is visible to a certain
* user, or throw an exception.
@ -32,4 +39,14 @@ interface UserRepositoryInterface
* @return integer|null
*/
public function getIdForUsername($username, User $user = null);
/**
* Find users by matching a string of words against their username,
* optionally making sure they are visible to a certain user.
*
* @param string $string
* @param \Flarum\Core\Models\User|null $user
* @return array
*/
public function getIdsForUsername($string, User $user = null);
}

View File

@ -1,18 +1,19 @@
<?php namespace Flarum\Core\Search\Discussions;
use Flarum\Core\Models\Discussion;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitManager;
use Flarum\Core\Repositories\DiscussionRepositoryInterface;
use Flarum\Core\Repositories\PostRepositoryInterface;
class DiscussionSearcher
class DiscussionSearcher implements SearcherInterface
{
public $query;
protected $sortMap = [
'lastPost' => ['last_time', 'desc'],
'replies' => ['comments_count', 'desc'],
'created' => ['start_time', 'desc']
'created' => ['start_time', 'asc']
];
protected $defaultSort = 'lastPost';
@ -43,6 +44,11 @@ class DiscussionSearcher
$this->defaultSort = $defaultSort;
}
public function query()
{
return $this->query;
}
public function search(DiscussionSearchCriteria $criteria, $count = null, $start = 0, $load = [])
{
$this->user = $criteria->user;
@ -56,7 +62,6 @@ class DiscussionSearcher
if (empty($sort)) {
$sort = $this->defaultSort;
}
// dd($sort);
if (is_array($sort)) {
foreach ($sort as $id) {
$this->query->orderByRaw('id != '.(int) $id);

View File

@ -1,7 +1,7 @@
<?php namespace Flarum\Core\Search\Discussions\Gambits;
use Flarum\Core\Repositories\UserRepositoryInterface as UserRepository;
use Flarum\Core\Search\Discussions\DiscussionSearcher;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitAbstract;
class AuthorGambit extends GambitAbstract
@ -19,12 +19,12 @@ class AuthorGambit extends GambitAbstract
$this->users = $users;
}
public function conditions($matches, DiscussionSearcher $searcher)
public function conditions($matches, SearcherInterface $searcher)
{
$username = trim($matches[1], '"');
$id = $this->users->getIdForUsername($username);
$searcher->query->where('start_user_id', $id);
$searcher->query()->where('start_user_id', $id);
}
}

View File

@ -1,7 +1,7 @@
<?php namespace Flarum\Core\Search\Discussions\Gambits;
use Flarum\Core\Repositories\PostRepositoryInterface;
use Flarum\Core\Search\Discussions\DiscussionSearcher;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitAbstract;
class FulltextGambit extends GambitAbstract
@ -13,7 +13,7 @@ class FulltextGambit extends GambitAbstract
$this->posts = $posts;
}
public function apply($string, DiscussionSearcher $searcher)
public function apply($string, SearcherInterface $searcher)
{
$posts = $this->posts->findByContent($string, $searcher->user);
@ -24,7 +24,7 @@ class FulltextGambit extends GambitAbstract
}
$discussions = array_unique($discussions);
$searcher->query->whereIn('id', $discussions);
$searcher->query()->whereIn('id', $discussions);
$searcher->setDefaultSort($discussions);
}

View File

@ -1,7 +1,7 @@
<?php namespace Flarum\Core\Search\Discussions\Gambits;
use Flarum\Core\Repositories\DiscussionRepositoryInterface as DiscussionRepository;
use Flarum\Core\Search\Discussions\DiscussionSearcher;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitAbstract;
class UnreadGambit extends GambitAbstract
@ -19,7 +19,7 @@ class UnreadGambit extends GambitAbstract
$this->discussions = $discussions;
}
protected function conditions($matches, DiscussionSearcher $searcher)
protected function conditions($matches, SearcherInterface $searcher)
{
$user = $searcher->user;
@ -27,9 +27,9 @@ class UnreadGambit extends GambitAbstract
$readIds = $this->discussions->getReadIds($user);
if ($matches[1] === 'true') {
$searcher->query->whereNotIn('id', $readIds)->where('last_time', '>', $user->read_time ?: 0);
$searcher->query()->whereNotIn('id', $readIds)->where('last_time', '>', $user->read_time ?: 0);
} else {
$searcher->query->whereIn('id', $readIds)->orWhere('last_time', '<=', $user->read_time ?: 0);
$searcher->query()->whereIn('id', $readIds)->orWhere('last_time', '<=', $user->read_time ?: 0);
}
}
}

View File

@ -1,12 +1,10 @@
<?php namespace Flarum\Core\Search;
use Flarum\Core\Search\Discussions\DiscussionSearcher;
abstract class GambitAbstract
{
protected $pattern;
public function apply($bit, DiscussionSearcher $searcher)
public function apply($bit, SearcherInterface $searcher)
{
if ($matches = $this->match($bit)) {
$this->conditions($matches, $searcher);

View File

@ -0,0 +1,8 @@
<?php namespace Flarum\Core\Search;
interface SearcherInterface
{
public function query();
public function setDefaultSort($defaultSort);
}

View File

@ -0,0 +1,24 @@
<?php namespace Flarum\Core\Search\Users\Gambits;
use Flarum\Core\Repositories\UserRepositoryInterface;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitAbstract;
class FulltextGambit extends GambitAbstract
{
protected $users;
public function __construct(UserRepositoryInterface $users)
{
$this->users = $users;
}
public function apply($string, SearcherInterface $searcher)
{
$users = $this->users->getIdsForUsername($string, $searcher->user);
$searcher->query()->whereIn('id', $users);
$searcher->setDefaultSort($users);
}
}

View File

@ -0,0 +1,20 @@
<?php namespace Flarum\Core\Search\Users;
class UserSearchCriteria
{
public $user;
public $query;
public $sort;
public $order;
public function __construct($user, $query, $sort, $order)
{
$this->user = $user;
$this->query = $query;
$this->sort = $sort;
$this->order = $order;
}
}

View File

@ -0,0 +1,32 @@
<?php namespace Flarum\Core\Search\Users;
class UserSearchResults
{
protected $users;
protected $areMoreResults;
protected $total;
public function __construct($users, $areMoreResults, $total)
{
$this->users = $users;
$this->areMoreResults = $areMoreResults;
$this->total = $total;
}
public function getUsers()
{
return $this->users;
}
public function getTotal()
{
return $this->total;
}
public function areMoreResults()
{
return $this->areMoreResults;
}
}

View File

@ -0,0 +1,79 @@
<?php namespace Flarum\Core\Search\Users;
use Flarum\Core\Models\User;
use Flarum\Core\Search\SearcherInterface;
use Flarum\Core\Search\GambitManager;
use Flarum\Core\Repositories\UserRepositoryInterface;
class UserSearcher implements SearcherInterface
{
public $query;
protected $sortMap = [
'username' => ['username', 'asc'],
'posts' => ['comments_count', 'desc'],
'discussions' => ['discussions_count', 'desc'],
'lastActive' => ['last_seen_time', 'desc'],
'created' => ['join_time', 'asc']
];
protected $defaultSort = 'username';
protected $users;
public function __construct(GambitManager $gambits, UserRepositoryInterface $users)
{
$this->gambits = $gambits;
$this->users = $users;
}
public function setDefaultSort($defaultSort)
{
$this->defaultSort = $defaultSort;
}
public function query()
{
return $this->query;
}
public function search(UserSearchCriteria $criteria, $count = null, $start = 0, $load = [])
{
$this->user = $criteria->user;
$this->query = $this->users->query()->whereCan($criteria->user, 'view');
$this->gambits->apply($criteria->query, $this);
$total = $this->query->count();
$sort = $criteria->sort;
if (empty($sort)) {
$sort = $this->defaultSort;
}
if (is_array($sort)) {
foreach ($sort as $id) {
$this->query->orderByRaw('id != '.(int) $id);
}
} else {
list($column, $order) = $this->sortMap[$sort];
$this->query->orderBy($column, $criteria->order ?: $order);
}
if ($start > 0) {
$this->query->skip($start);
}
if ($count > 0) {
$this->query->take($count + 1);
}
$users = $this->query->get();
if ($count > 0 && $areMoreResults = $users->count() > $count) {
$users->pop();
}
$users->load($load);
return new UserSearchResults($users, $areMoreResults, $total);
}
}