Add initial Plenario live polling app
CI / Deploy / test (push) Successful in 49s
CI / Deploy / deploy (push) Failing after 5s

CakePHP 5.4 app for live polls: create via email without login, manage
via secret admin link, join via code. Includes slide types (choice,
wordcloud, open, scale, content), presenter mode, CSV export, captcha,
throttling, tests and Gitea CI/deploy workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
gnilebeinandClaude Opus 5.5 committed 2026-11-07 13:24:29 +01:00
commit eb319f8c1e
120 files changed
+15572

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Model\Entity\Slide;
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;
/**
* @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['max_words'] = max(0, min(50, (int)($input['max_words'] ?? 0)));
$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;
}
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);
}
/**
* 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
* @return void
*/
public function syncOptions(Slide $slide, array $labels): void
{
$existing = $this->SlideOptions->find()
->where(['slide_id' => $slide->id])
->all()
->indexBy('label')
->toArray();
$this->getConnection()->transactional(function () use ($slide, $labels, $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);
$this->SlideOptions->saveOrFail($option);
unset($existing[$label]);
}
foreach ($existing as $obsolete) {
$this->SlideOptions->deleteOrFail($obsolete);
}
});
}
/**
* Swaps the slide with its neighbour.
*
* @param \App\Model\Entity\Slide $slide Slide to move
* @param string $direction 'up' or 'down'
* @return bool Whether something changed
*/
public function move(Slide $slide, string $direction): bool
{
$this->normalizePositions($slide->poll_id);
$slide = $this->get($slide->id);
$neighbour = $this->find()
->where([
'poll_id' => $slide->poll_id,
'position' . ($direction === 'up' ? ' <' : ' >') => $slide->position,
])
->orderBy(['position' => $direction === 'up' ? 'DESC' : 'ASC'])
->first();
if ($neighbour === null) {
return false;
}
return (bool)$this->getConnection()->transactional(function () use ($slide, $neighbour): bool {
$position = $slide->position;
$slide->position = $neighbour->position;
$neighbour->position = $position;
return $this->save($slide) && $this->save($neighbour);
});
}
/**
* 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;
}
}