Modify search to use EntityStream

This commit is contained in:
Alma Armas 2020-08-01 14:27:10 +00:00
parent 82af3a27cc
commit 9303dd6562
3 changed files with 54 additions and 5 deletions

View file

@ -36,12 +36,13 @@ class Users
return $this->toUser($this->users->where("user", $user->getId())->fetch()); return $this->toUser($this->users->where("user", $user->getId())->fetch());
} }
function find(string $query, int $page = 1, ?int $perPage = NULL): \Traversable function find(string $query): \Traversable
{ {
$query = "%$query%"; $query = "%$query%";
$perPage = $perPage ?? OPENVK_DEFAULT_PER_PAGE; $perPage = $perPage ?? OPENVK_DEFAULT_PER_PAGE;
foreach($this->users->where("CONCAT_WS(' ', first_name, last_name) LIKE ?", $query)->page($page, $perPage) as $result) $result = $this->users->where("CONCAT_WS(' ', first_name, last_name) LIKE ?", $query);
yield new User($result);
return new Util\EntityStream("User", $result);
} }
function getFoundCount(string $query): int function getFoundCount(string $query): int

View file

@ -0,0 +1,48 @@
<?php declare(strict_types=1);
namespace openvk\Web\Models\Repositories\Util;
use Nette\Database\Table\ActiveRow;
class EntityStream implements \IteratorAggregate
{
private $dbStream;
private $entityClass;
function __construct(string $class, \Traversable $dbStream)
{
$this->dbStream = $dbStream;
$this->entityClass = "openvk\\Web\\Models\\Entities\\$class";
}
private function getEntity(ActiveRow $result)
{
return new $this->entityClass($result);
}
private function stream(\Traversable $iterator): \Traversable
{
foreach($iterator as $result)
yield $this->getEntity($result);
}
function getIterator(): \Traversable
{
trigger_error("Trying to use EntityStream as iterator directly. Are you sure this is what you want?", E_USER_WARNING);
return $this->stream($this->dbStream);
}
function page(int $page, ?int $perPage = NULL): \Traversable
{
return $this->stream($this->dbStream->page($page, $perPage ?? OPENVK_DEFAULT_PER_PAGE));
}
function offsetLimit(int $offset = 0, ?int $limit = NULL): \Traversable
{
return $this->stream($this->dbStream->limit($limit ?? OPENVK_DEFAULT_PER_PAGE, $offset));
}
function size(): int
{
return sizeof(clone $this->dbStream);
}
}

View file

@ -33,8 +33,8 @@ final class SearchPresenter extends OpenVKPresenter
$count = $this->clubs->getFoundCount($query); $count = $this->clubs->getFoundCount($query);
break; break;
case "users": case "users":
$iterator = $this->users->find($query, $page); $iterator = $this->users->find($query)->page($page);
$count = $this->users->getFoundCount($query); $count = $this->users->find($query)->size();
break; break;
} }