Files
speedBB/api/src/State/ForumPositionProcessor.php
2025-12-24 18:30:18 +01:00

48 lines
1.6 KiB
PHP

<?php
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Forum;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class ForumPositionProcessor implements ProcessorInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
private ProcessorInterface $persistProcessor
) {
}
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{
if (!$data instanceof Forum) {
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
$previous = $context['previous_data'] ?? null;
$parentChanged = $previous instanceof Forum && $previous->getParent()?->getId() !== $data->getParent()?->getId();
if ($data->getPosition() === 0 || $parentChanged) {
$qb = $this->entityManager->createQueryBuilder();
$qb->select('COALESCE(MAX(f.position), 0)')
->from(Forum::class, 'f');
if ($data->getParent()) {
$qb->andWhere('f.parent = :parent')
->setParameter('parent', $data->getParent());
} else {
$qb->andWhere('f.parent IS NULL');
}
$maxPosition = (int) $qb->getQuery()->getSingleScalarResult();
$data->setPosition($maxPosition + 1);
}
return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
}
}