2020-08-01 17:27:10 +03:00
|
|
|
<?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;
|
2021-01-27 21:01:18 +03:00
|
|
|
$this->entityClass = $class[0] === "\\" ? $class : "openvk\\Web\\Models\\Entities\\$class";
|
2020-08-01 17:27:10 +03:00
|
|
|
}
|
|
|
|
|
2020-08-17 17:23:16 +03:00
|
|
|
/**
|
|
|
|
* Almost shorthand for (clone $this->dbStream)
|
|
|
|
* Needed because it's used often in this class. And it's used often to prevent changing mutable dbStream.
|
|
|
|
*/
|
|
|
|
private function dbs(): \Traversable
|
|
|
|
{
|
|
|
|
return (clone $this->dbStream);
|
|
|
|
}
|
|
|
|
|
2020-08-01 17:27:10 +03:00
|
|
|
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);
|
|
|
|
|
2020-08-17 17:23:16 +03:00
|
|
|
return $this->stream($this->dbs());
|
2020-08-01 17:27:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function page(int $page, ?int $perPage = NULL): \Traversable
|
|
|
|
{
|
2020-08-17 17:23:16 +03:00
|
|
|
return $this->stream($this->dbs()->page($page, $perPage ?? OPENVK_DEFAULT_PER_PAGE));
|
2020-08-01 17:27:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function offsetLimit(int $offset = 0, ?int $limit = NULL): \Traversable
|
|
|
|
{
|
2020-08-17 17:23:16 +03:00
|
|
|
return $this->stream($this->dbs()->limit($limit ?? OPENVK_DEFAULT_PER_PAGE, $offset));
|
2020-08-01 17:27:10 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
function size(): int
|
|
|
|
{
|
2020-08-17 17:23:16 +03:00
|
|
|
return sizeof($this->dbs());
|
2020-08-01 17:27:10 +03:00
|
|
|
}
|
|
|
|
}
|