123 lines
2.8 KiB
PHP

<?php
namespace Chill\PersonBundle\Export\Aggregator;
use Chill\MainBundle\Export\AggregatorInterface;
use Chill\MainBundle\Repository\ScopeRepository;
use Chill\MainBundle\Templating\TranslatableStringHelper;
use Chill\PersonBundle\Export\Declarations;
use Doctrine\ORM\Query\Expr\From;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\Form\FormBuilderInterface;
final class ScopeAggregator implements AggregatorInterface
{
private ScopeRepository $scopeRepository;
private TranslatableStringHelper $translatableStringHelper;
public function __construct(
ScopeRepository $scopeRepository,
TranslatableStringHelper $translatableStringHelper
) {
$this->scopeRepository = $scopeRepository;
$this->translatableStringHelper = $translatableStringHelper;
}
/**
* @inheritDoc
*/
public function getLabels($key, array $values, $data)
{
return function ($value): string {
if ($value === '_header') {
return 'Scope';
}
$s = $this->scopeRepository->find($value);
return $this->translatableStringHelper->localize(
$s->getName()
);
};
}
/**
* @inheritDoc
*/
public function getQueryKeys($data): array
{
return ['scope_aggregator'];
}
/**
* @inheritDoc
*/
public function buildForm(FormBuilderInterface $builder)
{
// no form
}
/**
* @inheritDoc
*/
public function getTitle(): string
{
return 'Group by user scope';
}
/**
* @inheritDoc
*/
public function addRole()
{
return null;
}
/**
* @inheritDoc
*/
public function alterQuery(QueryBuilder $qb, $data)
{
switch ($this->getBaseEntityAppliedOn($qb)) {
case 'acp':
$qb->join('acp.scopes', 's');
$qb->addSelect('s.id as scope_aggregator');
break;
case 'acpw':
$qb->join('acpw.referrers', 'r');
$qb->addSelect('IDENTITY(r.mainScope) as scope_aggregator');
break;
default:
throw new \Exception("Does not apply on that base entity");
}
$groupBy = $qb->getDQLPart('groupBy');
if (!empty($groupBy)) {
$qb->addGroupBy('scope_aggregator');
} else {
$qb->groupBy('scope_aggregator');
}
}
/**
* @inheritDoc
*/
public function applyOn(): string
{
return Declarations::ACP_SHARED;
}
private function getBaseEntityAppliedOn(QueryBuilder $qb): string
{
/** @var From $from */
$from = $qb->getDQLPart('from');
return $from[0]->getAlias();
}
}