Files
Plenario/src/Service/VoteService.php
T
gnilebeinandClaude Opus 5.5 918e077734
CI / Deploy / test (push) Successful in 50s
CI / Deploy / deploy (push) Skipped
Add ordering slide type
Participants bring shuffled items into the correct order and submit it
once. The admin enters the items in the correct order and can reorder
them by drag & drop or arrow keys. Closing the voting reveals the
solution: how many got it completely right and how often each item was
placed correctly; participants see whether their order was right.

The drag & drop mechanics of the slide list are extracted into a
reusable makeSortable() helper.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 16:47:37 +01:00

429 lines
17 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Service;
use App\Model\Entity\Poll;
use App\Model\Entity\Slide;
use App\Model\Table\ResponsesTable;
use Cake\ORM\Locator\LocatorAwareTrait;
use Cake\Utility\Security;
/**
* Validates and stores participant answers.
*
* Rules:
* - the poll must be active and the slide must be the poll's current slide
* - voting on the slide must be open
* - every participant can answer a slide exactly once, except word clouds:
* there words are submitted one by one (each word once per participant,
* any number of words). Submitting a word that already
* exists in the cloud is an upvote – both are stored as the same row.
* `vote=down` stores a downvote (numeric_value = DOWNVOTE) for an existing
* word of someone else. Each participant rates a word only once (up or down).
* - quiz: exactly one option, only while the quiz runs (Slide::isVotingOpen()
* includes the deadline of a timed quiz).
* - Q&A (see QaService for the stages): `question` (text) only while collecting,
* at most MAX_QA_QUESTIONS per participant, the same question (case-insensitive)
* only once per slide. `vote=up|remove` + `question_id` only while voting: upvote
* questions of others, at most `max_upvotes` in total, freely distributed (several
* on one question are allowed); `remove` withdraws one own upvote of the question.
* - ordering: `order` = all option ids, each exactly once, in the participant's order.
* Stored as one row with the ids comma separated in `text_value` (see parseOrder()).
*/
class VoteService
{
use LocatorAwareTrait;
public const MAX_WORD_LENGTH = 40;
public const MAX_TEXT_LENGTH = 500;
public const MAX_QA_QUESTIONS = 10;
/**
* `responses.numeric_value` of a word cloud downvote (upvotes/words: null).
*/
public const DOWNVOTE = -1;
protected ResponsesTable $Responses;
/**
* Constructor
*/
public function __construct()
{
/** @var \App\Model\Table\ResponsesTable $responses */
$responses = $this->fetchTable('Responses');
$this->Responses = $responses;
}
/**
* Derives the anonymous participant hash from the cookie id. The poll id is
* part of the HMAC key so participants cannot be correlated across polls.
*
* @param string $participantId Random id from the participant cookie
* @param int $pollId Poll id
* @return string
*/
public static function participantHash(string $participantId, int $pollId): string
{
return hash_hmac('sha256', $participantId, Security::getSalt() . '|poll|' . $pollId);
}
/**
* @param \App\Model\Entity\Poll $poll Poll
* @param \App\Model\Entity\Slide $slide Slide (with slide_options for choice slides)
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return void
* @throws \App\Service\VoteException
*/
public function submit(Poll $poll, Slide $slide, string $participantHash, array $data): void
{
if (!$poll->is_active) {
throw new VoteException(__('Diese Umfrage ist derzeit geschlossen.'));
}
if ($slide->poll_id !== $poll->id || $poll->current_slide_id !== $slide->id) {
throw new VoteException(__('Diese Frage ist nicht mehr aktiv.'));
}
if (!$slide->isInteractive()) {
throw new VoteException(__('Auf dieser Folie kann nicht abgestimmt werden.'));
}
if (!$slide->isVotingOpen()) {
throw new VoteException(match (true) {
$slide->isQuiz() && $slide->voting_started_at === null => __('Das Quiz hat noch nicht begonnen.'),
$slide->isQuiz() => __('Die Zeit für dieses Quiz ist abgelaufen.'),
$slide->isQa() => __('Die Fragerunde läuft – Fragen und Stimmen sind nicht mehr möglich.'),
default => __('Die Abstimmung zu dieser Frage ist geschlossen.'),
});
}
if (!$slide->allowsMultipleResponses() && $this->Responses->hasResponded($slide->id, $participantHash)) {
throw new VoteException(__('Du hast bereits abgestimmt.'));
}
$rows = match ($slide->type) {
Slide::TYPE_CHOICE => $this->choiceRows($slide, $data),
Slide::TYPE_WORDCLOUD => $this->wordRows($slide, $participantHash, $data),
Slide::TYPE_OPEN => $this->openRows($data),
Slide::TYPE_SCALE => $this->scaleRows($slide, $data),
Slide::TYPE_QUIZ => $this->quizRows($slide, $data),
Slide::TYPE_QA => $this->qaRows($slide, $participantHash, $data),
Slide::TYPE_ORDER => $this->orderRows($slide, $data),
default => throw new VoteException(__('Unbekannter Folientyp.')),
};
$entities = [];
foreach ($rows as $row) {
$entities[] = $this->Responses->newEntity($row + [
'slide_id' => $slide->id,
'participant_hash' => $participantHash,
]);
}
if ($entities !== []) {
$this->Responses->saveManyOrFail($entities);
}
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function choiceRows(Slide $slide, array $data): array
{
$selected = $data['option_ids'] ?? $data['option_id'] ?? [];
$selected = array_values(array_unique(array_map('intval', (array)$selected)));
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
$selected = array_values(array_intersect($selected, $validIds));
if ($selected === []) {
throw new VoteException(__('Bitte wähle eine Antwort aus.'));
}
if (!$slide->setting('multiple') && count($selected) > 1) {
throw new VoteException(__('Bitte wähle nur eine Antwort aus.'));
}
return array_map(fn(int $id) => ['slide_option_id' => $id], $selected);
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function quizRows(Slide $slide, array $data): array
{
$selected = $data['option_id'] ?? null;
$id = is_scalar($selected) ? filter_var($selected, FILTER_VALIDATE_INT) : false;
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
if ($id === false || !in_array($id, $validIds, true)) {
throw new VoteException(__('Bitte wähle eine Antwort aus.'));
}
return [['slide_option_id' => $id]];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function orderRows(Slide $slide, array $data): array
{
$given = [];
foreach ((array)($data['order'] ?? []) as $id) {
$id = is_scalar($id) ? filter_var($id, FILTER_VALIDATE_INT) : false;
if ($id === false) {
$given = [];
break;
}
$given[] = $id;
}
$validIds = array_map(fn($option) => $option->id, $slide->slide_options ?? []);
$sortedGiven = $given;
sort($sortedGiven);
sort($validIds);
if ($validIds === [] || $sortedGiven !== $validIds) {
throw new VoteException(__('Bitte bring alle Einträge in eine Reihenfolge und sende sie erneut.'));
}
return [['text_value' => implode(',', $given)]];
}
/**
* Option ids of a stored ordering answer (`responses.text_value`), in the participant's order.
*
* @param string|null $text Stored answer
* @return list<int>
*/
public static function parseOrder(?string $text): array
{
$ids = [];
foreach (explode(',', (string)$text) as $id) {
if (ctype_digit(trim($id))) {
$ids[] = (int)$id;
}
}
return $ids;
}
/**
* Q&A: a new question while collecting, an upvote (or its withdrawal) while voting.
* Withdrawing deletes one upvote row and returns no new rows.
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function qaRows(Slide $slide, string $participantHash, array $data): array
{
$stage = $slide->qaStage();
$vote = $data['vote'] ?? null;
$own = $this->Responses->qaVotesOf($slide->id, $participantHash);
if ($vote === null) {
if ($stage !== Slide::QA_COLLECT) {
throw new VoteException(__('Es können keine neuen Fragen mehr eingereicht werden.'));
}
$text = trim((string)preg_replace('/\s+/u', ' ', (string)($data['question'] ?? '')));
if ($text === '') {
throw new VoteException(__('Bitte gib eine Frage ein.'));
}
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Die Frage darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
$key = mb_strtolower($text);
foreach ($this->Responses->questionsOf($slide->id)->select(['text_value'])->disableHydration() as $row) {
if (mb_strtolower((string)$row['text_value']) === $key) {
throw new VoteException(__('Diese Frage wurde schon gestellt. Du kannst sie gleich beim Abstimmen unterstützen.'));
}
}
if (count($own['questions']) >= self::MAX_QA_QUESTIONS) {
throw new VoteException(__('Du kannst höchstens {0} Fragen stellen.', self::MAX_QA_QUESTIONS));
}
return [['text_value' => $text]];
}
if ($stage !== Slide::QA_VOTE) {
throw new VoteException(__('Die Abstimmung über die Fragen hat noch nicht begonnen.'));
}
$id = is_scalar($data['question_id'] ?? null) ? filter_var($data['question_id'], FILTER_VALIDATE_INT) : false;
if ($id === false || !$this->Responses->questionsOf($slide->id)->where(['Responses.id' => $id])->count()) {
throw new VoteException(__('Diese Frage gibt es nicht.'));
}
if ($vote === 'remove') {
// Withdraws one of possibly several own upvotes on the question.
$upvote = $this->Responses->find()
->where(['slide_id' => $slide->id, 'participant_hash' => $participantHash, 'parent_id' => $id])
->orderBy(['id' => 'DESC'])
->first();
if ($upvote === null) {
throw new VoteException(__('Du hast diese Frage nicht unterstützt.'));
}
$this->Responses->deleteOrFail($upvote);
return [];
}
if ($vote !== 'up') {
throw new VoteException(__('Ungültige Stimme.'));
}
if (in_array($id, $own['questions'], true)) {
throw new VoteException(__('Deine eigene Frage kannst du nicht unterstützen.'));
}
// Several upvotes on the same question are allowed (push important questions).
$max = (int)$slide->setting('max_upvotes');
if (count($own['upvotes']) >= $max) {
throw new VoteException(__n(
'Du hast deine Stimme schon vergeben. Nimm sie zurück, um eine andere Frage zu unterstützen.',
'Du hast alle {0} Stimmen vergeben. Nimm eine zurück, um eine andere Frage zu unterstützen.',
$max,
$max,
));
}
return [['parent_id' => $id]];
}
/**
* Normalized key of a word cloud term: whitespace collapsed, trimmed, cut to
* MAX_WORD_LENGTH. Use wordKey() for case-insensitive comparison.
*
* @param string $word Raw input
* @return string
*/
public static function cleanWord(string $word): string
{
$word = trim((string)preg_replace('/\s+/u', ' ', $word));
return mb_substr($word, 0, self::MAX_WORD_LENGTH);
}
/**
* Case-insensitive grouping key of a word cloud term.
*
* @param string $word Word
* @return string
*/
public static function wordKey(string $word): string
{
return mb_strtolower(self::cleanWord($word));
}
/**
* Accepts `word` (string) or `words` (list). Words the participant already
* submitted are skipped.
*
* @param \App\Model\Entity\Slide $slide Slide
* @param string $participantHash Participant hash
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function wordRows(Slide $slide, string $participantHash, array $data): array
{
$votes = $this->Responses->wordVotesOf($slide->id, $participantHash);
$existing = array_values(array_unique(array_map(self::wordKey(...), $votes['up'])));
$downvoted = array_fill_keys(array_map(self::wordKey(...), $votes['down']), true);
if (($data['vote'] ?? null) === 'down') {
return $this->downvoteRows($slide, (string)($data['word'] ?? ''), $existing, $downvoted);
}
$input = array_merge((array)($data['words'] ?? []), (array)($data['word'] ?? []));
$seen = array_fill_keys($existing, true);
$words = [];
$duplicate = false;
$rejected = false;
foreach ($input as $word) {
$word = self::cleanWord((string)$word);
$key = mb_strtolower($word);
if ($word === '') {
continue;
}
if (isset($downvoted[$key])) {
$rejected = true;
continue;
}
if (isset($seen[$key])) {
$duplicate = true;
continue;
}
$seen[$key] = true;
$words[] = $word;
}
if ($words === []) {
throw new VoteException(match (true) {
$duplicate => __('Diesen Begriff hast du schon genannt.'),
$rejected => __('Diesen Begriff hast du bereits abgelehnt.'),
default => __('Bitte gib einen Begriff ein.'),
});
}
return array_map(fn(string $word) => ['text_value' => $word], $words);
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param string $word Word to downvote
* @param list<string> $own Keys the participant named/upvoted
* @param array<string, true> $downvoted Keys the participant downvoted
* @return list<array<string, mixed>>
*/
protected function downvoteRows(Slide $slide, string $word, array $own, array $downvoted): array
{
if (!$slide->setting('allow_upvotes') || !$slide->setting('allow_downvotes')) {
throw new VoteException(__('Downvotes sind bei dieser Frage nicht möglich.'));
}
$word = self::cleanWord($word);
$key = mb_strtolower($word);
if ($word === '' || !$this->Responses->wordExists($slide->id, $key)) {
throw new VoteException(__('Diesen Begriff gibt es nicht in der Wortwolke.'));
}
if (in_array($key, $own, true)) {
throw new VoteException(__('Du hast diesen Begriff selbst genannt.'));
}
if (isset($downvoted[$key])) {
throw new VoteException(__('Diesen Begriff hast du bereits abgelehnt.'));
}
return [['text_value' => $word, 'numeric_value' => self::DOWNVOTE]];
}
/**
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function openRows(array $data): array
{
$text = trim((string)($data['text'] ?? ''));
if ($text === '') {
throw new VoteException(__('Bitte gib eine Antwort ein.'));
}
if (mb_strlen($text) > self::MAX_TEXT_LENGTH) {
throw new VoteException(__('Die Antwort darf maximal {0} Zeichen lang sein.', self::MAX_TEXT_LENGTH));
}
return [['text_value' => $text]];
}
/**
* @param \App\Model\Entity\Slide $slide Slide
* @param array<string, mixed> $data Request data
* @return list<array<string, mixed>>
*/
protected function scaleRows(Slide $slide, array $data): array
{
$value = filter_var($data['value'] ?? null, FILTER_VALIDATE_INT);
$min = (int)$slide->setting('scale_min');
$max = (int)$slide->setting('scale_max');
if ($value === false || $value < $min || $value > $max) {
throw new VoteException(__('Bitte wähle einen Wert zwischen {0} und {1}.', $min, $max));
}
return [['numeric_value' => $value]];
}
}