mirror of
https://github.com/openvk/openvk
synced 2025-02-03 05:25:28 +03:00
Alexander Minkin
6ec54a379d
* feat(lint): add php-cs-fixer for linting Removing previous CODE_STYLE as it was not enforced anyway and using PER-CS 2.0. This is not the reformatting commit. * style: format code according to PER-CS 2.0 with php-cs-fixer * ci(actions): add lint action Resolves #1132.
62 lines
1.6 KiB
PHP
62 lines
1.6 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace openvk\Web\Models\Repositories\Util;
|
|
|
|
use Nette\Database\Table\ActiveRow;
|
|
|
|
class EntityStream implements \IteratorAggregate
|
|
{
|
|
private $dbStream;
|
|
private $entityClass;
|
|
|
|
public function __construct(string $class, \Traversable $dbStream)
|
|
{
|
|
$this->dbStream = $dbStream;
|
|
$this->entityClass = $class[0] === "\\" ? $class : "openvk\\Web\\Models\\Entities\\$class";
|
|
}
|
|
|
|
/**
|
|
* 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);
|
|
}
|
|
|
|
private function getEntity(ActiveRow $result)
|
|
{
|
|
return new $this->entityClass($result);
|
|
}
|
|
|
|
private function stream(\Traversable $iterator): \Traversable
|
|
{
|
|
foreach ($iterator as $result) {
|
|
yield $this->getEntity($result);
|
|
}
|
|
}
|
|
|
|
public 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->dbs());
|
|
}
|
|
|
|
public function page(int $page, ?int $perPage = null): \Traversable
|
|
{
|
|
return $this->stream($this->dbs()->page($page, $perPage ?? OPENVK_DEFAULT_PER_PAGE));
|
|
}
|
|
|
|
public function offsetLimit(int $offset = 0, ?int $limit = null): \Traversable
|
|
{
|
|
return $this->stream($this->dbs()->limit($limit ?? OPENVK_DEFAULT_PER_PAGE, $offset));
|
|
}
|
|
|
|
public function size(): int
|
|
{
|
|
return sizeof($this->dbs());
|
|
}
|
|
}
|