openvk/ServiceAPI/Polls.php

75 lines
2 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
2022-10-11 19:04:43 +03:00
namespace openvk\ServiceAPI;
2022-10-11 19:04:43 +03:00
use Chandler\MVC\Routing\Router;
use openvk\Web\Models\Entities\User;
use openvk\Web\Models\Exceptions\{AlreadyVotedException, InvalidOptionException, PollLockedException};
use openvk\Web\Models\Repositories\Polls as PollRepo;
use UnexpectedValueException;
class Polls implements Handler
{
protected $user;
protected $polls;
public function __construct(?User $user)
2022-10-11 19:04:43 +03:00
{
$this->user = $user;
$this->polls = new PollRepo();
2022-10-11 19:04:43 +03:00
}
2022-10-11 19:04:43 +03:00
private function getPollHtml(int $poll): string
{
return Router::i()->execute("/poll$poll", "SAPI");
}
public function vote(int $pollId, string $options, callable $resolve, callable $reject): void
2022-10-11 19:04:43 +03:00
{
$poll = $this->polls->get($pollId);
if (!$poll) {
2022-10-11 19:04:43 +03:00
$reject("Poll not found");
return;
}
2022-10-11 19:04:43 +03:00
try {
$options = explode(",", $options);
$poll->vote($this->user, $options);
} catch (AlreadyVotedException $ex) {
2022-10-11 19:04:43 +03:00
$reject("Poll state changed: user has already voted.");
return;
} catch (PollLockedException $ex) {
2022-10-11 19:04:43 +03:00
$reject("Poll state changed: poll has ended.");
return;
} catch (InvalidOptionException $ex) {
2022-10-11 19:04:43 +03:00
$reject("Foreign options passed.");
return;
} catch (UnexpectedValueException $ex) {
2022-10-11 19:04:43 +03:00
$reject("Too much options passed.");
return;
}
2022-10-11 19:04:43 +03:00
$resolve(["html" => $this->getPollHtml($pollId)]);
}
public function unvote(int $pollId, callable $resolve, callable $reject): void
2022-10-11 19:04:43 +03:00
{
$poll = $this->polls->get($pollId);
if (!$poll) {
2022-10-11 19:04:43 +03:00
$reject("Poll not found");
return;
}
2022-10-11 19:04:43 +03:00
try {
$poll->revokeVote($this->user);
} catch (PollLockedException $ex) {
2022-10-11 19:04:43 +03:00
$reject("Votes can't be revoked from this poll.");
return;
}
2022-10-11 19:04:43 +03:00
$resolve(["html" => $this->getPollHtml($pollId)]);
}
}