Files
Plenario/src/Model/Table/SlidesTable.php
T
gnilebeinandClaude Opus 5.5 f0c6687100
CI / Deploy / test (push) Successful in 48s
CI / Deploy / deploy (push) Skipped
Add Q&A slide type
Participants submit questions, upvote them and the presenter discusses
them one by one, most upvoted first.

- Stages collect -> vote -> discuss, switched manually by the presenter
  (V key or stepper, going back is possible)
- Configurable upvote budget per participant, freely distributable
  (several upvotes on one question are allowed), votes can be withdrawn
- Participants see all questions while collecting to avoid duplicates;
  no counts before the discussion
- While discussing, next/prev step through the questions before
  moving to the next slide
- Migration: slides.stage, slides.focus_response_id, responses.parent_id

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

357 lines
13 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\Model\Table;
use App\Model\Entity\Slide;
use App\Service\YouTubeService;
use ArrayObject;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* @property \App\Model\Table\PollsTable&\Cake\ORM\Association\BelongsTo $Polls
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\HasMany $SlideOptions
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
* @method \App\Model\Entity\Slide newEmptyEntity()
* @method \App\Model\Entity\Slide get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
*/
class SlidesTable extends Table
{
public const MAX_OPTIONS = 20;
public const MAX_QUIZ_OPTIONS = 10;
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('slides');
$this->setDisplayField('question');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->getSchema()->setColumnType('settings', 'json');
$this->belongsTo('Polls', ['foreignKey' => 'poll_id', 'joinType' => 'INNER']);
$this->hasMany('SlideOptions', [
'foreignKey' => 'slide_id',
'sort' => ['SlideOptions.position' => 'ASC', 'SlideOptions.id' => 'ASC'],
'dependent' => true,
]);
$this->hasMany('Responses', [
'foreignKey' => 'slide_id',
'dependent' => true,
]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->inList('type', array_keys(Slide::typeLabels()))
->requirePresence('type', 'create')
->notEmptyString('type');
$validator
->scalar('question')
->maxLength('question', 500, __('Die Frage darf maximal 500 Zeichen lang sein.'))
->requirePresence('question', 'create')
->notEmptyString('question', __('Bitte gib eine Frage bzw. Überschrift ein.'));
$validator
->scalar('description')
->maxLength('description', 5000)
->allowEmptyString('description');
$validator->boolean('is_voting_open');
return $validator;
}
/**
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules): RulesChecker
{
$rules->add($rules->existsIn(['poll_id'], 'Polls'), ['errorField' => 'poll_id']);
return $rules;
}
/**
* Normalise settings before they are marshalled into the entity.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
* @param \ArrayObject<string, mixed> $data Request data
* @param \ArrayObject<string, mixed> $options Options
* @return void
*/
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options): void
{
if (isset($data['question']) && is_string($data['question'])) {
$data['question'] = trim($data['question']);
}
if (isset($data['settings']) && is_array($data['settings']) && isset($data['type'])) {
$data['settings'] = static::sanitizeSettings((string)$data['type'], $data['settings']);
}
}
/**
* Assign the next free position for new slides.
*
* @param \Cake\Event\EventInterface<\Cake\ORM\Table> $event Event
* @param \Cake\Datasource\EntityInterface $entity Slide
* @param \ArrayObject<string, mixed> $options Options
* @return void
*/
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options): void
{
if ($entity->isNew() && !$entity->has('position')) {
$max = $this->find()
->where(['poll_id' => $entity->get('poll_id')])
->select(['max' => $this->find()->func()->max('position')])
->disableHydration()
->first();
$entity->set('position', (int)($max['max'] ?? 0) + 1);
}
}
/**
* Reduces raw settings input to the known keys of the type, with proper types.
*
* @param string $type Slide type
* @param array<string, mixed> $input Raw settings
* @return array<string, mixed>
*/
public static function sanitizeSettings(string $type, array $input): array
{
$settings = Slide::DEFAULT_SETTINGS[$type] ?? [];
switch ($type) {
case Slide::TYPE_CHOICE:
$settings['multiple'] = filter_var($input['multiple'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_WORDCLOUD:
$settings['allow_upvotes'] = filter_var($input['allow_upvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
$settings['allow_downvotes'] = filter_var($input['allow_downvotes'] ?? true, FILTER_VALIDATE_BOOLEAN);
break;
case Slide::TYPE_SCALE:
$min = max(0, min(1, (int)($input['scale_min'] ?? 1)));
$max = max(2, min(10, (int)($input['scale_max'] ?? 5)));
$settings['scale_min'] = $min;
$settings['scale_max'] = $max;
$settings['min_label'] = mb_substr(trim((string)($input['min_label'] ?? '')), 0, 60);
$settings['max_label'] = mb_substr(trim((string)($input['max_label'] ?? '')), 0, 60);
break;
case Slide::TYPE_QUIZ:
$limit = (int)($input['time_limit'] ?? $settings['time_limit']);
if (in_array($limit, Slide::QUIZ_TIME_LIMITS, true)) {
$settings['time_limit'] = $limit;
}
break;
case Slide::TYPE_QA:
$max = (int)($input['max_upvotes'] ?? $settings['max_upvotes']);
$settings['max_upvotes'] = max(1, min(Slide::QA_MAX_UPVOTES, $max));
break;
case Slide::TYPE_YOUTUBE:
$url = mb_substr(trim((string)($input['url'] ?? '')), 0, 500);
$parsed = YouTubeService::parseUrl($url);
$settings['url'] = $url;
$settings['video_id'] = $parsed['videoId'] ?? '';
// Form input "1:30" / "2" (minutes); an int is already seconds. Empty = timecode of the link.
$start = $input['start'] ?? '';
if (!is_int($start)) {
$start = trim((string)$start) === '' ? null : YouTubeService::parseStartInput((string)$start);
}
$settings['start'] = max(0, min($start ?? $parsed['start'] ?? 0, YouTubeService::MAX_START));
$settings['autoplay'] = filter_var($input['autoplay'] ?? false, FILTER_VALIDATE_BOOLEAN);
break;
}
return $settings;
}
/**
* Parses a textarea (one option per line) into a clean list of labels.
*
* @param string $raw Textarea content
* @return list<string>
*/
public static function parseOptionLines(string $raw): array
{
$labels = [];
foreach (preg_split('/\R/', $raw) ?: [] as $line) {
$line = mb_substr(trim($line), 0, 255);
if ($line !== '' && !in_array($line, $labels, true)) {
$labels[] = $line;
}
}
return array_slice($labels, 0, self::MAX_OPTIONS);
}
/**
* Parses the quiz option rows of the slide form (`quiz_options[i][label|correct]`).
* Empty rows are skipped, duplicate labels are merged.
*
* @param array<mixed> $rows Raw form rows
* @return array{labels: list<string>, correct: list<string>}
*/
public static function parseQuizOptions(array $rows): array
{
$labels = [];
$correct = [];
foreach ($rows as $row) {
if (!is_array($row)) {
continue;
}
$label = mb_substr(trim((string)($row['label'] ?? '')), 0, 255);
if ($label === '' || count($labels) >= self::MAX_QUIZ_OPTIONS) {
continue;
}
if (!in_array($label, $labels, true)) {
$labels[] = $label;
}
if (filter_var($row['correct'] ?? false, FILTER_VALIDATE_BOOLEAN) && !in_array($label, $correct, true)) {
$correct[] = $label;
}
}
return ['labels' => $labels, 'correct' => $correct];
}
/**
* Persists the end of a timed quiz once its deadline has passed. Safe to
* call repeatedly (no-op unless the slide is still flagged open).
*
* @param \App\Model\Entity\Slide $slide Slide
* @return \App\Model\Entity\Slide
*/
public function closeIfExpired(Slide $slide): Slide
{
if ($slide->isExpired()) {
$slide->is_voting_open = false;
$this->saveOrFail($slide);
}
return $slide;
}
/**
* Synchronises the answer options of a slide with the given labels.
* Options whose label is unchanged keep their id (and therefore their votes);
* removed options are deleted together with their votes.
*
* @param \App\Model\Entity\Slide $slide Saved slide
* @param list<string> $labels New labels in display order
* @param list<string> $correct Labels of the correct options (quiz)
* @return void
*/
public function syncOptions(Slide $slide, array $labels, array $correct = []): void
{
$existing = $this->SlideOptions->find()
->where(['slide_id' => $slide->id])
->all()
->indexBy('label')
->toArray();
$this->getConnection()->transactional(function () use ($slide, $labels, $correct, $existing): void {
foreach ($labels as $index => $label) {
$option = $existing[$label] ?? $this->SlideOptions->newEntity(['label' => $label]);
$option->set('slide_id', $slide->id);
$option->set('position', $index + 1);
$option->set('is_correct', in_array($label, $correct, true));
$this->SlideOptions->saveOrFail($option);
unset($existing[$label]);
}
foreach ($existing as $obsolete) {
$this->SlideOptions->deleteOrFail($obsolete);
}
});
}
/**
* Applies a complete new order (e.g. from drag & drop).
*
* The ids must be exactly the slides of the poll, each once – otherwise
* (stale page, foreign ids) nothing is changed. Repeating the same order is a no-op.
*
* @param int $pollId Poll id
* @param list<int> $slideIds Slide ids in their new order
* @return bool Whether the order was valid and is now applied
*/
public function reorder(int $pollId, array $slideIds): bool
{
$current = $this->find('list', valueField: 'position')
->where(['poll_id' => $pollId])
->toArray();
$given = $slideIds;
$existing = array_map('intval', array_keys($current));
sort($given);
sort($existing);
if ($given !== $existing) {
return false;
}
return (bool)$this->getConnection()->transactional(function () use ($slideIds, $current): bool {
foreach ($slideIds as $index => $id) {
if ($current[$id] !== $index + 1) {
$this->updateAll(['position' => $index + 1], ['id' => $id]);
}
}
return true;
});
}
/**
* Renumbers positions 1..n (closes gaps after deletions).
*
* @param int $pollId Poll id
* @return void
*/
public function normalizePositions(int $pollId): void
{
$slides = $this->find()
->where(['poll_id' => $pollId])
->orderBy(['position' => 'ASC', 'id' => 'ASC'])
->all();
$position = 1;
foreach ($slides as $slide) {
if ($slide->position !== $position) {
$this->updateAll(['position' => $position], ['id' => $slide->id]);
}
$position++;
}
}
/**
* Ordered slides of a poll including options.
*
* @param int $pollId Poll id
* @return list<\App\Model\Entity\Slide>
*/
public function listForPoll(int $pollId): array
{
/** @var list<\App\Model\Entity\Slide> $slides */
$slides = $this->find()
->where(['Slides.poll_id' => $pollId])
->contain(['SlideOptions'])
->orderBy(['Slides.position' => 'ASC', 'Slides.id' => 'ASC'])
->all()
->toList();
return $slides;
}
}