Commit 1baf8b12 authored by Dominique Merle's avatar Dominique Merle 💬
Browse files

Implement the actual feature about tallying.

parent b347238d
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Repository\LimajuPollRepository;
use App\Tally\Bot\TallyBotInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
* @Route("/api/limaju_poll_tally/{id}", name="api_limaju_poll_tally_get", methods={"GET"})
*/
final class GetTallyController
{
/**
* @var ContainerInterface
*/
private $container;
/**
* GetTallyController constructor.
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function __invoke(
string $id,
Request $request,
MessageBusInterface $bus,
LimajuPollRepository $pollRepository,
EntityManagerInterface $em
): Response {
$poll = $pollRepository->find($id);
$tally = "standard";
$tallyBot = $this->getTallyBot($tally);
$tallyOutput = $tallyBot->tallyVotesOnLimajuPoll($poll);
$votesCount = $tallyOutput->countVotes();
if (0 == $votesCount) {
$error = "api.tallying.failure.generic";
return new JsonResponse(['error' => $error], Response::HTTP_BAD_REQUEST);
}
return new JsonResponse($tallyOutput, Response::HTTP_OK);
}
/**
* @param string $tallyName
* @return TallyBotInterface
*/
protected function getTallyBot(string $tallyName) : TallyBotInterface
{
$tallyFileName = ucwords($tallyName);
return $this->container->get("App\\Tally\\Bot\\${tallyFileName}TallyBot");
}
}
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Tally\Output\LimajuPollTally as TallyOutput;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* A tally of a liquid majority judgment poll.
* There may (will!) be additional tallies in the future,
* and we'd love to make adding new tally algorithms easy.
*
* @ApiResource(
* shortName="LimajuPollTally",
* itemOperations={
* "get"={
* "controller"="App\Controller\GetTallyController",
* },
* },
* collectionOperations={},
* )
*/
class LimajuPollTally
{
/**
* @var TallyOutput Standard tally output.
* @Groups({ "read" })
*/
public $standard;
}
\ No newline at end of file
......@@ -24,4 +24,14 @@ class LimajuPollTally
{
$this->options = $options;
}
public function countVotes()
{
$count = 0;
foreach ($this->options as $option) {
$count += $option->countVotes();
}
return $count;
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment