Files
kupshop/bundles/KupShop/KupShopBundle/CollectionList.php
2025-08-02 16:30:27 +02:00

93 lines
2.1 KiB
PHP

<?php
declare(strict_types=1);
namespace KupShop\KupShopBundle;
use Doctrine\Common\Collections\ArrayCollection;
use Query\Operator;
use Query\QueryBuilder;
/**
* Base class for collection lists.
*/
abstract class CollectionList
{
protected static string $collectionClass;
private array $resultModifiers = [];
private array $specs = [];
public function getCollection(?int &$totalCount = null): ArrayCollection
{
$useTotalCount = count(func_get_args());
$qb = $this->createQueryBuilder()
->andWhere(Operator::andX($this->specs));
if ($useTotalCount) {
$qb->addCalcRows();
}
$result = $qb->execute();
if ($useTotalCount) {
$totalCount = (int) sqlFetchAssoc(sqlQuery('SELECT FOUND_ROWS() as total_count'))['total_count'];
}
$items = [];
foreach ($result as $item) {
$items[$item['id']] = $this->createItem($item);
}
$collection = new static::$collectionClass($items);
foreach ($this->resultModifiers as $callback) {
$callback($collection);
}
return $collection;
}
public function orderBy(string $sort, ?string $order = null): self
{
$this->andSpec(function (QueryBuilder $qb) use ($sort, $order) {
$qb->orderBy($sort, $order);
});
return $this;
}
public function limit(int $count, ?int $offset = null): self
{
$this->andSpec(function (QueryBuilder $qb) use ($count, $offset) {
if (isset($offset)) {
$qb->setFirstResult($offset);
}
$qb->setMaxResults($count);
});
return $this;
}
public function addResultModifiers(callable $resultModifier): self
{
$this->resultModifiers[] = $resultModifier;
return $this;
}
public function andSpec(?callable $spec): self
{
if ($spec) {
$this->specs[] = $spec;
}
return $this;
}
abstract protected function createItem(array $item): mixed;
abstract protected function createQueryBuilder(): QueryBuilder;
}