87 lines
2.7 KiB
PHP
87 lines
2.7 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace KupShop\GraphQLBundle\ApiAdmin\Util;
|
|
|
|
use KupShop\GraphQLBundle\ApiAdmin\Types\Charge;
|
|
use KupShop\GraphQLBundle\ApiAdmin\Types\Collection\ChargeCollection;
|
|
use KupShop\GraphQLBundle\ApiAdmin\Types\Parameters;
|
|
use KupShop\GraphQLBundle\ApiShared\ApiUtil;
|
|
use KupShop\GraphQLBundle\ApiShared\Util\ParametersAssembler;
|
|
use KupShop\GraphQLBundle\Exception\GraphQLNotFoundException;
|
|
use Query\Operator;
|
|
use Query\QueryBuilder;
|
|
|
|
class ChargesUtil
|
|
{
|
|
public function __construct(private readonly ParametersAssembler $parametersAssembler)
|
|
{
|
|
}
|
|
|
|
public function getChargeCollection(int $offset, int $limit, ?Parameters $chargeSort, ?Parameters $chargeFilter): ChargeCollection
|
|
{
|
|
$filterSpec = $this->createChargeCollectionFilter($offset, $limit, $chargeSort, $chargeFilter);
|
|
|
|
$charges = $this->getCharges($filterSpec, $totalCount);
|
|
|
|
return new ChargeCollection($charges)
|
|
->setItemsTotalCount($totalCount)
|
|
->setLimit($limit)
|
|
->setOffset($offset);
|
|
}
|
|
|
|
public function getCharge(int $id): ?Charge
|
|
{
|
|
$charges = $this->getCharges(filterSpec: Operator::equals(['c.id' => $id]));
|
|
|
|
if (!($charge = reset($charges))) {
|
|
throw new GraphQLNotFoundException('Charge not found!');
|
|
}
|
|
|
|
return $charge;
|
|
}
|
|
|
|
/** @return Charge[] */
|
|
public function getCharges(callable $filterSpec, ?int &$totalCount = null): array
|
|
{
|
|
$useTotalCount = count(func_get_args()) > 1;
|
|
|
|
$qb = sqlQueryBuilder()
|
|
->addCalcRows()
|
|
->select('c.*')
|
|
->from('charges', 'c')
|
|
->andWhere($filterSpec)
|
|
->groupBy('c.id');
|
|
|
|
$charges = $qb->execute()->fetchAllAssociative();
|
|
|
|
if ($useTotalCount) {
|
|
$totalCount = (int) sqlFetchAssoc(sqlQuery('SELECT FOUND_ROWS() as total_count'))['total_count'];
|
|
}
|
|
|
|
return ApiUtil::wrapItems($charges, Charge::class);
|
|
}
|
|
|
|
protected function createChargeCollectionFilter(int $offset, int $limit, ?Parameters $sort, ?Parameters $filter): callable
|
|
{
|
|
$ids = $filter?->get('id');
|
|
if (!empty($ids)) {
|
|
$filter->set('id', Operator::inIntArray($ids, 'c.id'));
|
|
} else {
|
|
$filter?->remove('id');
|
|
}
|
|
|
|
$active = $filter?->get('active');
|
|
if (!empty($active)) {
|
|
$filter->set('active', Operator::equals(['c.figure' => $active]));
|
|
} else {
|
|
$filter?->remove('active');
|
|
}
|
|
|
|
return function (QueryBuilder $qb) use ($offset, $limit, $sort, $filter) {
|
|
$this->parametersAssembler->assemblyInput($filter, $sort, $offset, $limit, $qb);
|
|
};
|
|
}
|
|
}
|