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

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+58
View File
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* @property int $id
* @property string $title
* @property string $email
* @property string $admin_token_hash
* @property string $admin_token_encrypted
* @property string $join_code
* @property int|null $current_slide_id
* @property bool $is_active
* @property bool $show_results_to_participants
* @property \Cake\I18n\DateTime|null $last_admin_access
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime $modified
* @property array<\App\Model\Entity\Slide> $slides
*/
class Poll extends Entity
{
/**
* Only harmless fields are mass assignable. Tokens, join code and the
* current slide are always set explicitly in code.
*
* @var array<string, bool>
*/
protected array $_accessible = [
'title' => true,
'email' => true,
'is_active' => true,
'show_results_to_participants' => true,
];
/**
* Never leak secrets when an entity is serialised (JSON, debug output).
*
* @var list<string>
*/
protected array $_hidden = [
'admin_token_hash',
'admin_token_encrypted',
'email',
];
/**
* "K7P2QX" -> "K7P 2QX" for nicer display.
*
* @return string
*/
public function formattedJoinCode(): string
{
return trim(chunk_split($this->join_code, 3, ' '));
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* One answer row of a participant. A multi-select vote or a word cloud entry
* with several words results in several rows with the same participant_hash.
*
* @property int $id
* @property int $slide_id
* @property string $participant_hash
* @property int|null $slide_option_id
* @property string|null $text_value
* @property int|null $numeric_value
* @property \Cake\I18n\DateTime $created
*/
class Response extends Entity
{
/**
* Responses are only created by VoteService, never mass assigned from requests.
*
* @var array<string, bool>
*/
protected array $_accessible = [
'slide_id' => true,
'participant_hash' => true,
'slide_option_id' => true,
'text_value' => true,
'numeric_value' => true,
];
/**
* @var list<string>
*/
protected array $_hidden = ['participant_hash'];
}
+126
View File
@@ -0,0 +1,126 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* A slide of a poll. `type` decides how participants answer and how results
* are aggregated (see \App\Service\ResultsService and \App\Service\VoteService).
*
* @property int $id
* @property int $poll_id
* @property string $type
* @property string $question
* @property string|null $description
* @property int $position
* @property array<string, mixed>|null $settings
* @property bool $is_voting_open
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime $modified
* @property \App\Model\Entity\Poll $poll
* @property array<\App\Model\Entity\SlideOption> $slide_options
* @property array<\App\Model\Entity\Response> $responses
*/
class Slide extends Entity
{
public const TYPE_CHOICE = 'choice';
public const TYPE_WORDCLOUD = 'wordcloud';
public const TYPE_OPEN = 'open';
public const TYPE_SCALE = 'scale';
public const TYPE_CONTENT = 'content';
/**
* Default settings per type. Unknown keys are dropped on save.
*
* @var array<string, array<string, mixed>>
*/
public const DEFAULT_SETTINGS = [
self::TYPE_CHOICE => ['multiple' => false],
// max_words: words per participant incl. upvotes (not downvotes), 0 = unlimited;
// allow_downvotes only takes effect together with allow_upvotes
self::TYPE_WORDCLOUD => ['max_words' => 0, 'allow_upvotes' => true, 'allow_downvotes' => true],
self::TYPE_OPEN => [],
self::TYPE_SCALE => ['scale_min' => 1, 'scale_max' => 5, 'min_label' => '', 'max_label' => ''],
self::TYPE_CONTENT => [],
];
/**
* @var array<string, bool>
*/
protected array $_accessible = [
'type' => true,
'question' => true,
'description' => true,
'settings' => true,
'is_voting_open' => true,
];
/**
* @return array<string, string> type => human readable label
*/
public static function typeLabels(): array
{
return [
self::TYPE_CHOICE => __('Multiple Choice'),
self::TYPE_WORDCLOUD => __('Wortwolke'),
self::TYPE_OPEN => __('Offene Frage'),
self::TYPE_SCALE => __('Skala'),
self::TYPE_CONTENT => __('Inhaltsfolie'),
];
}
/**
* @return array<string, string> type => short description
*/
public static function typeDescriptions(): array
{
return [
self::TYPE_CHOICE => __('Antwortoptionen vorgeben, Ergebnis als Balkendiagramm.'),
self::TYPE_WORDCLOUD => __('Teilnehmende geben Begriffe ein oder unterstützen vorhandene, häufige werden größer.'),
self::TYPE_OPEN => __('Freitext-Antworten, live als Liste.'),
self::TYPE_SCALE => __('Bewertung auf einer Skala, z. B. 1 bis 5.'),
self::TYPE_CONTENT => __('Nur Text anzeigen, ohne Abstimmung.'),
];
}
/**
* @return string
*/
public function typeLabel(): string
{
return static::typeLabels()[$this->type] ?? $this->type;
}
/**
* Whether participants can answer this slide at all.
*
* @return bool
*/
public function isInteractive(): bool
{
return $this->type !== self::TYPE_CONTENT;
}
/**
* Settings merged with the type defaults.
*
* @return array<string, mixed>
*/
public function getSettings(): array
{
$defaults = self::DEFAULT_SETTINGS[$this->type] ?? [];
return array_intersect_key(array_merge($defaults, (array)($this->settings ?? [])), $defaults);
}
/**
* @param string $key Setting name
* @return mixed
*/
public function setting(string $key): mixed
{
return $this->getSettings()[$key] ?? null;
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* @property int $id
* @property int $slide_id
* @property string $label
* @property int $position
*/
class SlideOption extends Entity
{
/**
* @var array<string, bool>
*/
protected array $_accessible = [
'label' => true,
'position' => true,
];
}
View File
Whitespace-only changes.
+233
View File
@@ -0,0 +1,233 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Model\Entity\Poll;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Utility\Security;
use Cake\Validation\Validator;
use RuntimeException;
/**
* Polls ("presentations"). Access control works exclusively via the secret
* admin token - there are no user accounts.
*
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\HasMany $Slides
* @method \App\Model\Entity\Poll newEmptyEntity()
* @method \App\Model\Entity\Poll get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
* @method \App\Model\Entity\Poll saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
*/
class PollsTable extends Table
{
/**
* Characters used for join codes (no 0/O, 1/I/L to avoid confusion).
*/
public const JOIN_CODE_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
public const JOIN_CODE_LENGTH = 6;
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('polls');
$this->setDisplayField('title');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->hasMany('Slides', [
'foreignKey' => 'poll_id',
'sort' => ['Slides.position' => 'ASC', 'Slides.id' => 'ASC'],
'dependent' => true,
'cascadeCallbacks' => false,
]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('title')
->maxLength('title', 200, __('Der Titel darf maximal 200 Zeichen lang sein.'))
->requirePresence('title', 'create')
->notEmptyString('title', __('Bitte gib einen Titel ein.'));
$validator
->email('email', false, __('Bitte gib eine gültige E-Mail-Adresse ein.'))
->maxLength('email', 255)
->requirePresence('email', 'create')
->notEmptyString('email', __('Bitte gib deine E-Mail-Adresse ein.'));
$validator->boolean('is_active');
$validator->boolean('show_results_to_participants');
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->isUnique(['join_code']), ['errorField' => 'join_code']);
$rules->add($rules->isUnique(['admin_token_hash']), ['errorField' => 'admin_token_hash']);
return $rules;
}
/**
* Creates a new admin token: URL safe, 256 bit entropy.
*
* @return string
*/
public static function generateToken(): string
{
return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
}
/**
* @param string $token Plain admin token
* @return string sha256 hex digest
*/
public static function hashToken(string $token): string
{
return hash('sha256', $token);
}
/**
* Assigns a fresh admin token to the poll (hash + encrypted copy).
*
* @param \App\Model\Entity\Poll $poll Poll entity
* @return string The plain token (only ever shown in the admin URL / mail)
*/
public function assignNewToken(Poll $poll): string
{
$token = static::generateToken();
$poll->admin_token_hash = static::hashToken($token);
$poll->admin_token_encrypted = base64_encode(Security::encrypt($token, static::encryptionKey()));
return $token;
}
/**
* Decrypts the stored admin token (used by the recovery mail).
*
* @param \App\Model\Entity\Poll $poll Poll entity
* @return string|null
*/
public function decryptToken(Poll $poll): ?string
{
$raw = base64_decode((string)$poll->admin_token_encrypted, true);
if ($raw === false) {
return null;
}
$token = Security::decrypt($raw, static::encryptionKey());
if ($token === null || static::hashToken($token) !== $poll->admin_token_hash) {
return null;
}
return $token;
}
/**
* @return string 32 byte key derived from Security.salt
*/
protected static function encryptionKey(): string
{
return hash('sha256', 'plenario-admin-token|' . Security::getSalt());
}
/**
* Generates a join code that is not yet in use.
*
* @return string
*/
public function generateJoinCode(): string
{
$alphabet = self::JOIN_CODE_ALPHABET;
$max = strlen($alphabet) - 1;
for ($attempt = 0; $attempt < 50; $attempt++) {
$code = '';
for ($i = 0; $i < self::JOIN_CODE_LENGTH; $i++) {
$code .= $alphabet[random_int(0, $max)];
}
if (!$this->exists(['join_code' => $code])) {
return $code;
}
}
throw new RuntimeException('Could not generate a unique join code.');
}
/**
* Normalises user input like " k7p-2qx " to "K7P2QX".
*
* @param string $code Raw user input
* @return string
*/
public static function normalizeJoinCode(string $code): string
{
return (string)preg_replace('/[^A-Z0-9]/', '', strtoupper($code));
}
/**
* Creates and persists a new poll.
*
* @param array<string, mixed> $data title + email
* @return array{0: \App\Model\Entity\Poll, 1: string|null} The entity (check getErrors()) and the plain token on success
*/
public function createPoll(array $data): array
{
$poll = $this->newEntity([
'title' => trim((string)($data['title'] ?? '')),
'email' => strtolower(trim((string)($data['email'] ?? ''))),
], ['fields' => ['title', 'email']]);
if ($poll->hasErrors()) {
return [$poll, null];
}
$token = $this->assignNewToken($poll);
$poll->join_code = $this->generateJoinCode();
$poll->is_active = true;
$poll->show_results_to_participants = true;
if (!$this->save($poll)) {
return [$poll, null];
}
return [$poll, $token];
}
/**
* @param \Cake\ORM\Query\SelectQuery $query Query
* @param string $token Plain admin token
* @return \Cake\ORM\Query\SelectQuery
*/
public function findByAdminToken(SelectQuery $query, string $token): SelectQuery
{
return $query->where(['Polls.admin_token_hash' => static::hashToken($token)]);
}
/**
* @param \Cake\ORM\Query\SelectQuery $query Query
* @param string $code Join code (will be normalised)
* @return \Cake\ORM\Query\SelectQuery
*/
public function findByJoinCode(SelectQuery $query, string $code): SelectQuery
{
return $query->where(['Polls.join_code' => static::normalizeJoinCode($code)]);
}
}
+139
View File
@@ -0,0 +1,139 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use App\Service\VoteService;
use Cake\ORM\Table;
/**
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
* @property \App\Model\Table\SlideOptionsTable&\Cake\ORM\Association\BelongsTo $SlideOptions
* @method \App\Model\Entity\Response newEntity(array $data, array $options = [])
*/
class ResponsesTable extends Table
{
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('responses');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp', [
'events' => ['Model.beforeSave' => ['created' => 'new']],
]);
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
$this->belongsTo('SlideOptions', ['foreignKey' => 'slide_option_id']);
}
/**
* @param int $slideId Slide id
* @param string $participantHash Participant hash
* @return bool
*/
public function hasResponded(int $slideId, string $participantHash): bool
{
return $this->exists(['slide_id' => $slideId, 'participant_hash' => $participantHash]);
}
/**
* Word cloud terms a participant named/upvoted and downvoted on a slide.
*
* @param int $slideId Slide id
* @param string $participantHash Participant hash
* @return array{up: list<string>, down: list<string>} raw text values
*/
public function wordVotesOf(int $slideId, string $participantHash): array
{
$rows = $this->find()
->select(['text_value', 'numeric_value'])
->where(['slide_id' => $slideId, 'participant_hash' => $participantHash, 'text_value IS NOT' => null])
->orderBy(['id' => 'ASC'])
->disableHydration()
->all();
$votes = ['up' => [], 'down' => []];
foreach ($rows as $row) {
$votes[(int)$row['numeric_value'] === VoteService::DOWNVOTE ? 'down' : 'up'][] = (string)$row['text_value'];
}
return $votes;
}
/**
* Whether anybody named (or upvoted) a word cloud term on a slide.
*
* @param int $slideId Slide id
* @param string $key Word key, see VoteService::wordKey()
* @return bool
*/
public function wordExists(int $slideId, string $key): bool
{
$rows = $this->find()
->select(['text_value'])
->where([
'slide_id' => $slideId,
'text_value IS NOT' => null,
'numeric_value IS' => null,
])
->disableHydration()
->all();
foreach ($rows as $row) {
if (VoteService::wordKey((string)$row['text_value']) === $key) {
return true;
}
}
return false;
}
/**
* Number of distinct participants that answered a slide.
*
* @param int $slideId Slide id
* @return int
*/
public function countParticipants(int $slideId): int
{
$row = $this->find()
->select(['n' => $this->find()->func()->count('DISTINCT participant_hash')])
->where(['slide_id' => $slideId])
->disableHydration()
->first();
return (int)($row['n'] ?? 0);
}
/**
* Number of responding participants per slide of a poll.
*
* @param int $pollId Poll id
* @return array<int, int> slide_id => participant count
*/
public function countParticipantsPerSlide(int $pollId): array
{
$rows = $this->find()
->select([
'slide_id' => 'Responses.slide_id',
'n' => $this->find()->func()->count('DISTINCT Responses.participant_hash'),
])
->innerJoinWith('Slides')
->where(['Slides.poll_id' => $pollId])
->groupBy(['Responses.slide_id'])
->disableHydration()
->all();
$counts = [];
foreach ($rows as $row) {
$counts[(int)$row['slide_id']] = (int)$row['n'];
}
return $counts;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
/**
* @property \App\Model\Table\SlidesTable&\Cake\ORM\Association\BelongsTo $Slides
* @property \App\Model\Table\ResponsesTable&\Cake\ORM\Association\HasMany $Responses
* @method \App\Model\Entity\SlideOption newEntity(array $data, array $options = [])
*/
class SlideOptionsTable extends Table
{
/**
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
$this->setTable('slide_options');
$this->setDisplayField('label');
$this->setPrimaryKey('id');
$this->belongsTo('Slides', ['foreignKey' => 'slide_id', 'joinType' => 'INNER']);
$this->hasMany('Responses', ['foreignKey' => 'slide_option_id', 'dependent' => true]);
}
/**
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('label')
->maxLength('label', 255)
->notEmptyString('label');
return $validator;
}
}
+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;
}
}