mirror of
https://github.com/MarijnDoeve/TijdVoorDeTest.git
synced 2026-07-12 21:05:19 +02:00
Compare commits
27 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
38411dd44b
|
|||
|
f3d6984622
|
|||
|
a4f8340b04
|
|||
| 8382900b9e | |||
| c2637481f2 | |||
| 938456087a | |||
| 33a0e8a584 | |||
| 2fd15ba8fa | |||
| 6d6bcddfeb | |||
| 5e7028c972 | |||
| 0ee15e3cbb | |||
| 352e34a428 | |||
| b1a959fdc6 | |||
| 27d3d64154 | |||
| e7586c2d6b | |||
| a49d32e8ff | |||
| 4547a43199 | |||
| 1d3e99d2b2 | |||
| d7e8d094cf | |||
| ba1e8d8eb6 | |||
| 5d92d91432 | |||
| 04c40412cd | |||
| b915d87d4a | |||
| 47077288d5 | |||
| b965b2f10a | |||
| 88cff7f480 | |||
| 135e4f0ae5 |
@@ -1,3 +1,5 @@
|
||||
# define your env variables for the test env here
|
||||
KERNEL_CLASS='Tvdt\Kernel'
|
||||
APP_SECRET='$ecretf0rt3st'
|
||||
MAILER_DSN=null://null
|
||||
MAILER_SENDER=test@example.org
|
||||
|
||||
+23
-3
@@ -4,7 +4,7 @@ setopt ERR_EXIT PIPE_FAIL NOUNSET
|
||||
# Collect staged PHP and Twig files
|
||||
STAGED_PHP=()
|
||||
while IFS= read -r file; do
|
||||
[[ -n "$file" ]] && STAGED_PHP+=("$file")
|
||||
[[ -n "$file" && "$file" != "config/reference.php" ]] && STAGED_PHP+=("$file")
|
||||
done < <(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.php$' || true)
|
||||
|
||||
STAGED_TWIG=()
|
||||
@@ -12,7 +12,12 @@ while IFS= read -r file; do
|
||||
[[ -n "$file" ]] && STAGED_TWIG+=("$file")
|
||||
done < <(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.twig$' || true)
|
||||
|
||||
if [[ ${#STAGED_PHP[@]} -eq 0 && ${#STAGED_TWIG[@]} -eq 0 ]]; then
|
||||
STAGED_TS=()
|
||||
while IFS= read -r file; do
|
||||
[[ -n "$file" ]] && STAGED_TS+=("$file")
|
||||
done < <(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.ts$' || true)
|
||||
|
||||
if [[ ${#STAGED_PHP[@]} -eq 0 && ${#STAGED_TWIG[@]} -eq 0 && ${#STAGED_TS[@]} -eq 0 ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -32,7 +37,7 @@ if [[ ${#STAGED_PHP[@]} -gt 0 ]]; then
|
||||
git add "${STAGED_PHP[@]}"
|
||||
|
||||
echo " → PHP-CS-Fixer"
|
||||
"${DOCKER_CMD[@]}" vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php "${STAGED_PHP[@]}"
|
||||
"${DOCKER_CMD[@]}" vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.dist.php --path-mode=intersection "${STAGED_PHP[@]}"
|
||||
git add "${STAGED_PHP[@]}"
|
||||
|
||||
echo " → PHPStan"
|
||||
@@ -46,3 +51,18 @@ if [[ ${#STAGED_TWIG[@]} -gt 0 ]]; then
|
||||
"${DOCKER_CMD[@]}" vendor/bin/twig-cs-fixer fix "${STAGED_TWIG[@]}"
|
||||
git add "${STAGED_TWIG[@]}"
|
||||
fi
|
||||
|
||||
if [[ ${#STAGED_TS[@]} -gt 0 ]]; then
|
||||
echo "TypeScript (${#STAGED_TS[@]} file(s)): Deno fmt → lint → check"
|
||||
|
||||
echo " → Deno fmt"
|
||||
"${DOCKER_CMD[@]}" deno fmt "${STAGED_TS[@]}"
|
||||
git add "${STAGED_TS[@]}"
|
||||
|
||||
echo " → Deno lint"
|
||||
"${DOCKER_CMD[@]}" deno lint --fix "${STAGED_TS[@]}"
|
||||
git add "${STAGED_TS[@]}"
|
||||
|
||||
echo " → Deno check"
|
||||
"${DOCKER_CMD[@]}" deno check "${STAGED_TS[@]}"
|
||||
fi
|
||||
|
||||
@@ -70,6 +70,8 @@ jobs:
|
||||
set: |
|
||||
*.cache-from=type=gha,scope=${{github.ref}}-devbuild
|
||||
- name: Start services
|
||||
env:
|
||||
HTTP_PORT: "80"
|
||||
run: docker compose up php database --wait --no-build
|
||||
- name: Warm up dev cache
|
||||
run: docker compose exec -T php bin/console cache:warmup --env=dev
|
||||
@@ -93,6 +95,31 @@ jobs:
|
||||
id: rector
|
||||
continue-on-error: true
|
||||
run: docker compose exec -T php vendor/bin/rector process --dry-run --no-progress-bar --output-format=github
|
||||
- name: Translations
|
||||
id: translations
|
||||
continue-on-error: true
|
||||
run: |
|
||||
docker compose exec -T php bin/console translation:extract --force --format=xliff --sort=asc nl
|
||||
if ! git diff --exit-code -- translations; then
|
||||
echo "::error::Translations are out of date. Run 'just translations' and commit the changes."
|
||||
exit 1
|
||||
fi
|
||||
- name: TypeScript Formatting
|
||||
id: ts_fmt
|
||||
continue-on-error: true
|
||||
run: docker compose exec -T php deno fmt --check assets/
|
||||
- name: TypeScript Lint
|
||||
id: ts_lint
|
||||
continue-on-error: true
|
||||
run: docker compose exec -T php deno lint assets/
|
||||
- name: TypeScript Type Check
|
||||
id: ts_check
|
||||
continue-on-error: true
|
||||
run: docker compose exec -T php deno check assets/*.ts assets/controllers/*.ts assets/controllers/bo/*.ts
|
||||
- name: TypeScript Tests
|
||||
id: ts_test
|
||||
continue-on-error: true
|
||||
run: docker compose exec -T php deno test assets/
|
||||
- name: Check HTTP reachability
|
||||
run: curl -v --fail-with-body http://localhost
|
||||
- name: Assert all checks passed
|
||||
@@ -111,6 +138,11 @@ jobs:
|
||||
check "Twig Coding Style" "${{ steps.twig_cs.outcome }}"
|
||||
check "PHPStan" "${{ steps.phpstan.outcome }}"
|
||||
check "Rector" "${{ steps.rector.outcome }}"
|
||||
check "Translations" "${{ steps.translations.outcome }}"
|
||||
check "TypeScript Formatting" "${{ steps.ts_fmt.outcome }}"
|
||||
check "TypeScript Lint" "${{ steps.ts_lint.outcome }}"
|
||||
check "TypeScript Type Check" "${{ steps.ts_check.outcome }}"
|
||||
check "TypeScript Tests" "${{ steps.ts_test.outcome }}"
|
||||
exit $failed
|
||||
|
||||
tests:
|
||||
@@ -123,6 +155,7 @@ jobs:
|
||||
checks: write
|
||||
pull-requests: write
|
||||
contents: read
|
||||
code-quality: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
|
||||
@@ -141,6 +174,10 @@ jobs:
|
||||
*.cache-from=type=gha,scope=${{github.ref}}-devbuild
|
||||
- name: Start services
|
||||
run: docker compose up php database --wait --no-build
|
||||
- name: Build SCSS
|
||||
run: docker compose exec -T php bin/console sass:build
|
||||
- name: Build TypeScript
|
||||
run: docker compose exec -T php bin/console typescript:build
|
||||
- name: Create test database
|
||||
run: docker compose exec -T php bin/console -e test doctrine:database:create
|
||||
- name: Run migrations
|
||||
@@ -148,13 +185,26 @@ jobs:
|
||||
- name: Load fixtures
|
||||
run: docker compose exec -T php bin/console -e test doctrine:fixtures:load --no-interaction --group=test
|
||||
- name: Run PHPUnit
|
||||
run: docker compose exec -T php vendor/bin/phpunit --log-junit var/phpunit/junit.xml
|
||||
# Reports are written outside var/ since var/ is a Docker volume (see the Dockerfile's
|
||||
# VOLUME /app/var/) and isn't bind-mounted to the runner, unlike the rest of the project.
|
||||
run: docker compose exec -T -e MAILER_DSN=null://null php vendor/bin/phpunit --log-junit reports/junit.xml --coverage-cobertura reports/coverage/cobertura.xml
|
||||
- name: Publish PHPUnit test results
|
||||
if: always()
|
||||
uses: mikepenz/action-junit-report@d9f48fc87bc235f7e214acf696ca5abc0a986f16 # v6
|
||||
with:
|
||||
report_paths: var/phpunit/junit.xml
|
||||
report_paths: reports/junit.xml
|
||||
check_name: PHPUnit
|
||||
- name: Upload code coverage
|
||||
# Requires "Code Quality" to be enabled for this repository under
|
||||
# Settings > Code security > Code quality; fail-on-error is false so CI
|
||||
# doesn't go red before that one-time, manual repository setting is turned on.
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: actions/upload-code-coverage@82c7aee3fb2ad768e00b00a0a8d749c5815085b6 # v1
|
||||
with:
|
||||
file: reports/coverage/cobertura.xml
|
||||
language: PHP
|
||||
label: phpunit
|
||||
fail-on-error: false
|
||||
- name: Doctrine Schema Validator
|
||||
run: docker compose exec -T php bin/console -e test doctrine:schema:validate
|
||||
|
||||
@@ -164,7 +214,7 @@ jobs:
|
||||
timeout-minutes: 20
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
permissions:
|
||||
actions: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Wait for and verify successful CI run on this commit
|
||||
env:
|
||||
@@ -172,6 +222,8 @@ jobs:
|
||||
run: |
|
||||
max_attempts=30
|
||||
attempt=0
|
||||
triggered=false
|
||||
|
||||
while [[ $attempt -lt $max_attempts ]]; do
|
||||
attempt=$((attempt + 1))
|
||||
|
||||
@@ -189,12 +241,32 @@ jobs:
|
||||
--jq "[.workflow_runs[] | select(.id != ${{ github.run_id }}) | select(.status == \"in_progress\" or .status == \"queued\" or .status == \"waiting\" or .status == \"requested\" or .status == \"pending\")] | length")
|
||||
|
||||
if [[ "$in_progress_count" -gt 0 ]]; then
|
||||
echo "CI still in progress (attempt $attempt/$max_attempts), waiting 30s..."
|
||||
echo "CI in progress (attempt $attempt/$max_attempts), waiting 30s..."
|
||||
sleep 30
|
||||
else
|
||||
echo "::error::No prior successful CI run found for ${{ github.sha }}. Only tag commits that have passed CI on main."
|
||||
continue
|
||||
fi
|
||||
|
||||
if [[ "$triggered" == "false" ]]; then
|
||||
echo "No prior CI run found for ${{ github.sha }}. Triggering CI on ${{ github.ref }}..."
|
||||
gh workflow run ci.yml --repo "${{ github.repository }}" --ref "${{ github.ref }}"
|
||||
triggered=true
|
||||
echo "Triggered. Waiting 20s for run to register..."
|
||||
sleep 20
|
||||
continue
|
||||
fi
|
||||
|
||||
failed_conclusion=$(gh api \
|
||||
"repos/${{ github.repository }}/actions/workflows/ci.yml/runs?head_sha=${{ github.sha }}&per_page=10" \
|
||||
--jq "[.workflow_runs[] | select(.id != ${{ github.run_id }}) | select(.status == \"completed\") | select(.conclusion != \"success\")] | first | .conclusion // empty" \
|
||||
--raw-output)
|
||||
|
||||
if [[ -n "$failed_conclusion" ]]; then
|
||||
echo "::error::Triggered CI run on main failed with conclusion: $failed_conclusion. Fix the issue before re-tagging."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Waiting for triggered run to register (attempt $attempt/$max_attempts)..."
|
||||
sleep 20
|
||||
done
|
||||
|
||||
echo "::error::Timed out waiting for CI run to complete for ${{ github.sha }}."
|
||||
@@ -232,6 +304,7 @@ jobs:
|
||||
id: meta
|
||||
run: |
|
||||
REPO_LOWER=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
|
||||
echo "build_time=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> "$GITHUB_OUTPUT"
|
||||
if [[ "${{ github.ref }}" == refs/tags/* ]]; then
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
SENTRY_VERSION="${TAG#v}"
|
||||
@@ -258,9 +331,12 @@ jobs:
|
||||
compose.yaml
|
||||
compose.build.yaml
|
||||
set: |
|
||||
*.cache-from=type=gha,scope=${{github.ref}}-devbuild
|
||||
*.cache-from=type=gha,scope=refs/heads/main-devbuild
|
||||
*.cache-from=type=gha,scope=${{github.ref}}
|
||||
*.cache-from=type=gha,scope=refs/heads/main
|
||||
*.cache-to=type=gha,scope=${{github.ref}},mode=max
|
||||
*.args.BUILD_TIME=${{ steps.meta.outputs.build_time }}
|
||||
*.tags=${{ steps.meta.outputs.full_name }}
|
||||
|
||||
- name: Create Sentry release
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/frankenphp/data
|
||||
/reports/
|
||||
|
||||
### Generated by gibo (https://github.com/simonwhitaker/gibo)
|
||||
### https://raw.github.com/github/gitignore/6eeebe6f49678aacd8311ce079842c971b3ebe96/Symfony.gitignore
|
||||
|
||||
Generated
+2
@@ -170,6 +170,8 @@
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/ergebnis/agent-detector" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-deepclone" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/sebastian/file-filter" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/object-mapper" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/vendor/symfonycasts/reset-password-bundle" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
|
||||
Generated
+164
-162
@@ -41,169 +41,171 @@
|
||||
</component>
|
||||
<component name="PhpIncludePathManager">
|
||||
<include_path>
|
||||
<path value="$PROJECT_DIR$/vendor/psr/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/container" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/log" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/event-dispatcher" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/http-message" />
|
||||
<path value="$PROJECT_DIR$/vendor/gedmo/doctrine-extensions" />
|
||||
<path value="$PROJECT_DIR$/vendor/nikic/php-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/twig" />
|
||||
<path value="$PROJECT_DIR$/vendor/fidry/cpu-core-counter" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/stream" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/promise" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/event-loop" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/http-factory" />
|
||||
<path value="$PROJECT_DIR$/vendor/clue/ndjson-react" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/clock" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/extra-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/intl-extra" />
|
||||
<path value="$PROJECT_DIR$/vendor/dama/doctrine-test-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/stof/doctrine-extensions-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/manifest" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/egulias/email-validator" />
|
||||
<path value="$PROJECT_DIR$/vendor/myclabs/deep-copy" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-symfony" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-doctrine" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/child-process" />
|
||||
<path value="$PROJECT_DIR$/vendor/jean85/pretty-package-versions" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/dns" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/socket" />
|
||||
<path value="$PROJECT_DIR$/vendor/sentry/sentry" />
|
||||
<path value="$PROJECT_DIR$/vendor/staabm/side-effects-detector" />
|
||||
<path value="$PROJECT_DIR$/vendor/rector/rector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sentry/sentry-symfony" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-icu" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/form" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/framework-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-deepclone" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dotenv" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/validator" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/ux-turbo" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/serializer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/extension-installer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpdoc-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-invoker" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-file-iterator" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-text-template" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-code-coverage" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/asset-mapper" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-http" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/uid" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/var-dumper" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/brevo-mailer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/runtime" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/phpunit-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/browser-kit" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/asset" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/translation-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/config" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/intl" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/translation" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/css-selector" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/web-profiler-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-normalizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/twig-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/finder" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dom-crawler" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/property-access" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/options-resolver" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-csrf" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/mailer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/filesystem" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/twig-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-uuid" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-idn" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/maker-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/service-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-client-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/deprecation-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/routing" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-foundation" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/doctrine-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/property-info" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/type-info" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/psr-http-message-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-kernel" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-client" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/stopwatch" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/string" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-core" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/yaml" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/mime" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-grapheme" />
|
||||
<path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/process" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/console" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/error-handler" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/cache-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/var-exporter" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/flex" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/clock" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/password-hasher" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dependency-injection" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/stimulus-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-migrations-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/lexer" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/dbal" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/migrations" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/data-fixtures" />
|
||||
<path value="$PROJECT_DIR$/vendor/ergebnis/agent-detector" />
|
||||
<path value="$PROJECT_DIR$/vendor/evenement/evenement" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/deprecations" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/markbaker/matrix" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpoffice/phpspreadsheet" />
|
||||
<path value="$PROJECT_DIR$/vendor/maennchen/zipstream-php" />
|
||||
<path value="$PROJECT_DIR$/vendor/markbaker/complex" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-fixtures-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/instantiator" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/inflector" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/persistence" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/collections" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/sql-formatter" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/orm" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/event-manager" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/type" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/lines-of-code" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/file-filter" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/exporter" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/git-state" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/cli-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/environment" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/global-state" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-enumerator" />
|
||||
<path value="$PROJECT_DIR$/vendor/ralouphie/getallheaders" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/comparator" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/diff" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-reflector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/complexity" />
|
||||
<path value="$PROJECT_DIR$/vendor/thecodingmachine/safe" />
|
||||
<path value="$PROJECT_DIR$/vendor/thecodingmachine/phpstan-safe-rule" />
|
||||
<path value="$PROJECT_DIR$/vendor/vincentlanglet/twig-cs-fixer" />
|
||||
<path value="$PROJECT_DIR$/vendor/martin-georgiev/postgresql-for-doctrine" />
|
||||
<path value="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfonycasts/verify-email-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/webmozart/assert" />
|
||||
<path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/type-resolver" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-docblock" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfonycasts/sass-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" />
|
||||
<path value="$PROJECT_DIR$/vendor/composer" />
|
||||
<path value="$PROJECT_DIR$/vendor/dama/doctrine-test-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/clue/ndjson-react" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/http-factory" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/clock" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/twig" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/intl-extra" />
|
||||
<path value="$PROJECT_DIR$/vendor/twig/extra-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/stof/doctrine-extensions-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/event-dispatcher" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/log" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/container" />
|
||||
<path value="$PROJECT_DIR$/vendor/psr/http-message" />
|
||||
<path value="$PROJECT_DIR$/vendor/rector/rector" />
|
||||
<path value="$PROJECT_DIR$/vendor/jean85/pretty-package-versions" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/child-process" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/socket" />
|
||||
<path value="$PROJECT_DIR$/vendor/egulias/email-validator" />
|
||||
<path value="$PROJECT_DIR$/vendor/staabm/side-effects-detector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sentry/sentry" />
|
||||
<path value="$PROJECT_DIR$/vendor/sentry/sentry-symfony" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/event-loop" />
|
||||
<path value="$PROJECT_DIR$/vendor/nikic/php-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/gedmo/doctrine-extensions" />
|
||||
<path value="$PROJECT_DIR$/vendor/fidry/cpu-core-counter" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/dns" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/promise" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/stream" />
|
||||
<path value="$PROJECT_DIR$/vendor/react/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-text-template" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-timer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpdoc-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/framework-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-file-iterator" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-invoker" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpunit/php-code-coverage" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/phar-io/manifest" />
|
||||
<path value="$PROJECT_DIR$/vendor/myclabs/deep-copy" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/extension-installer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-phpunit" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-symfony" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpstan/phpstan-doctrine" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/intl" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/browser-kit" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/asset" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-http" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/config" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/translation-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/translation" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/ux-turbo" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/form" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-icu" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-deepclone" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/cache" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/validator" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dotenv" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/serializer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-idn" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-csrf" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/options-resolver" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/filesystem" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/web-profiler-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-uuid" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/twig-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/maker-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/runtime" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/asset-mapper" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/uid" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/mailer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/brevo-mailer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/var-dumper" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/phpunit-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/yaml" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-kernel" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/psr-http-message-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/stopwatch" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/deprecation-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/security-core" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/string" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/mime" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dom-crawler" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/css-selector" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-normalizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-client" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/finder" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/twig-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/property-access" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/dependency-injection" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/cache-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/error-handler" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/flex" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/process" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/password-hasher" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/clock" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/stimulus-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/property-info" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-client-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/service-contracts" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/routing" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/var-exporter" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/doctrine-bridge" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/http-foundation" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/type-info" />
|
||||
<path value="$PROJECT_DIR$/vendor/theseer/tokenizer" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-grapheme" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/console" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/orm" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/instantiator" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-fixtures-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/persistence" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/deprecations" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/sql-formatter" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/collections" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/event-manager" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/migrations" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-migrations-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/inflector" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/dbal" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/lexer" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/data-fixtures" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-reflector" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/object-enumerator" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/global-state" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/comparator" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/lines-of-code" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/recursion-context" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/diff" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/complexity" />
|
||||
<path value="$PROJECT_DIR$/vendor/maennchen/zipstream-php" />
|
||||
<path value="$PROJECT_DIR$/vendor/evenement/evenement" />
|
||||
<path value="$PROJECT_DIR$/vendor/ergebnis/agent-detector" />
|
||||
<path value="$PROJECT_DIR$/vendor/doctrine/doctrine-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/ralouphie/getallheaders" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpoffice/phpspreadsheet" />
|
||||
<path value="$PROJECT_DIR$/vendor/markbaker/matrix" />
|
||||
<path value="$PROJECT_DIR$/vendor/markbaker/complex" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfonycasts/sass-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfonycasts/verify-email-bundle" />
|
||||
<path value="$PROJECT_DIR$/vendor/friendsofphp/php-cs-fixer" />
|
||||
<path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
|
||||
<path value="$PROJECT_DIR$/vendor/vincentlanglet/twig-cs-fixer" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-docblock" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/type-resolver" />
|
||||
<path value="$PROJECT_DIR$/vendor/phpdocumentor/reflection-common" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/cli-parser" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/version" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/type" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/file-filter" />
|
||||
<path value="$PROJECT_DIR$/vendor/webmozart/assert" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/git-state" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/exporter" />
|
||||
<path value="$PROJECT_DIR$/vendor/sebastian/environment" />
|
||||
<path value="$PROJECT_DIR$/vendor/thecodingmachine/phpstan-safe-rule" />
|
||||
<path value="$PROJECT_DIR$/vendor/thecodingmachine/safe" />
|
||||
<path value="$PROJECT_DIR$/vendor/martin-georgiev/postgresql-for-doctrine" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfony/object-mapper" />
|
||||
<path value="$PROJECT_DIR$/vendor/symfonycasts/reset-password-bundle" />
|
||||
</include_path>
|
||||
</component>
|
||||
<component name="PhpInterpreters">
|
||||
|
||||
@@ -4,7 +4,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Project Overview
|
||||
|
||||
**Tijd voor de test** is a PHP/Symfony 8.1 application for managing quizzes in the style of **Wie is de Mol?** (WIDM) — a Dutch TV show where contestants try to identify a saboteur ("de Mol") among them. At the end of each episode, participants take a quiz about the Mol's identity and actions; the candidate with the least correct answers is eliminated. This app replicates that quiz format with:
|
||||
**Tijd voor de test** is a PHP/Symfony 8.1 application for managing quizzes in the style of **Wie is de Mol?** (WIDM) —
|
||||
a Dutch TV show where contestants try to identify a saboteur ("de Mol") among them. At the end of each episode,
|
||||
participants take a quiz about the Mol's identity and actions; the candidate with the least correct answers is
|
||||
eliminated. This app replicates that quiz format with:
|
||||
|
||||
- Test creation with variable question counts
|
||||
- Season management with active test controls
|
||||
- Candidate answer tracking with automatic timing
|
||||
@@ -12,13 +16,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
- Backoffice management for quiz administration and statistics
|
||||
|
||||
Tech Stack:
|
||||
|
||||
- **Framework**: Symfony 8.1
|
||||
- **PHP**: 8.5+
|
||||
- **Database**: PostgreSQL 16
|
||||
- **ORM**: Doctrine
|
||||
- **Server**: FrankenPHP with Caddy
|
||||
- **Container**: Docker Compose
|
||||
- **Frontend**: Twig templates with SASS (via asset mapper)
|
||||
- **Frontend**: Twig templates with SASS and TypeScript (via asset mapper)
|
||||
- **Testing**: PHPUnit 13 with DAMA Doctrine test bundle
|
||||
|
||||
## Build & Development Commands
|
||||
@@ -35,6 +40,24 @@ just shell # Interactive shell inside the PHP container
|
||||
just shell-run # Shell in a fresh one-off container
|
||||
```
|
||||
|
||||
### Working in git worktrees
|
||||
|
||||
`just up` auto-runs `just init` first, which generates a gitignored `.env.local` per checkout with a unique
|
||||
`COMPOSE_PROJECT_NAME`, `IMAGES_PREFIX`, and free `HTTP_PORT`/`HTTPS_PORT`/`POSTGRES_PORT`/`MAILPIT_PORT`/
|
||||
`SPOTLIGHT_PORT`. This means every worktree gets its own containers, network, volumes, and image tag — running
|
||||
`just up` in two worktrees at the same time does **not** make them share a database, image, or port, even if the
|
||||
worktree directories have the same basename.
|
||||
|
||||
- Run `just ports` to see the ports assigned to the *current* checkout — the app for that worktree is at
|
||||
`https://localhost:<HTTPS_PORT>`, not a fixed port. Never assume port 8080/8443/5432/etc. when working inside a
|
||||
worktree; always check `.env.local` or `just ports` first.
|
||||
- `.env.local` is generated once and reused; it's safe to run `just init`/`just up` repeatedly. Delete `.env.local`
|
||||
and re-run `just init` to force new ports (e.g. if the assigned ones are now taken by something else).
|
||||
- Each worktree's Postgres data, uploaded files, and Caddy state live in per-worktree Docker volumes — nothing is
|
||||
shared with the main checkout or other worktrees. Migrations/fixtures must be (re-)run per worktree.
|
||||
- `just down`/`just clean` in one worktree only ever affects that worktree's own containers/volumes — safe to run
|
||||
without impacting other worktrees.
|
||||
|
||||
### Database
|
||||
|
||||
```bash
|
||||
@@ -76,7 +99,7 @@ All code quality checks run in CI/CD (.github/workflows/ci.yml) and should pass
|
||||
|
||||
```
|
||||
src/
|
||||
Controller/ # HTTP request handlers (attribute-routed)
|
||||
Controller/ # HTTP request handlers (attribute-routed)
|
||||
Backoffice/ # Admin panel controllers
|
||||
Entity/ # Doctrine ORM entities
|
||||
Repository/ # Database queries
|
||||
@@ -122,53 +145,157 @@ tests/
|
||||
- **Elimination**: Records red/green screens and forced results with joker adjustments.
|
||||
- **User**: Administrative accounts for managing the system.
|
||||
|
||||
## Domain Context: "De Test" (Wie is de Mol)
|
||||
|
||||
**Wie is de Mol?** (WIDM) is a Dutch reality competition: a group of contestants ("kandidaten") travels together while
|
||||
one of them, "de Mol", secretly sabotages assignments. Each episode ends with the fixed line: *"Tijd voor de test.
|
||||
Twintig vragen over de identiteit en het doen en laten van de Mol. Degene die het minst weet, ligt uit het spel. Behalve
|
||||
de Mol. Die hoeft nooit naar huis."* ("Time for the test. Twenty questions about the identity and the actions of the
|
||||
Mol. Whoever knows the least is out of the game. Except the Mol — they never have to go home.") The contestant with the
|
||||
worst score is eliminated ("afvallen"); the Mol is immune regardless of score, since they already know the answers. This
|
||||
app is a generic engine for running that quiz format for private/fan seasons, not just modeling the TV show
|
||||
incidentally — the entity model below exists specifically to reproduce WIDM's test mechanics.
|
||||
|
||||
### What a test's 20 questions actually are
|
||||
|
||||
Per the intro line, questions fall into two factual categories — never opinion ("who would you vote off") — plus a
|
||||
third recurring format used on the show:
|
||||
|
||||
1. **Identity of the Mol**: guessing which contestant is the Mol.
|
||||
2. **The Mol's actions**: what the Mol did or where the Mol was during a specific assignment/moment.
|
||||
3. **Candidate self-answered questions**: earlier, every contestant privately answered a question about themselves
|
||||
(an interview-style question); the test then asks other contestants to guess what a *specific* candidate answered
|
||||
about themselves. This tests how well contestants know each other, not just Mol-tracking.
|
||||
|
||||
### Why answers can be bound to candidates
|
||||
|
||||
All three categories above can have contestants themselves as the answer options rather than free text: "who is the
|
||||
Mol" and "who did X" both need contestant names as options, and "what did candidate Y answer" needs Y's own submitted
|
||||
answer among the options. In the domain model this is `Answer::$candidates` (a `ManyToMany` to `Candidate`, on both
|
||||
sides): an answer option can *be* another contestant, not just text.
|
||||
|
||||
Because the relationship is many-to-many on the answer side too, a single answer option can cover **more than one
|
||||
candidate at once** — e.g. "Anna en Bram" as one option for "who missed the assignment together", or an option
|
||||
representing everyone who gave a particular self-answer in category 3 above. So a candidate-bound answer isn't always
|
||||
one candidate, it can be a group; treat `Answer::$candidates` as "the set of contestants this option represents", not
|
||||
as a single foreign key.
|
||||
|
||||
Combined with `GivenAnswer::$candidate` (who answered), every given answer on a candidate-bound question is a directed
|
||||
relationship from the answering candidate to *every* candidate covered by the chosen option — a one-to-many edge when
|
||||
the option is a group, not just candidate A pointed at candidate B. This is the mechanic behind any "who's suspected of
|
||||
what" or sociogram-style statistic — it only applies to candidate-bound questions, plain trivia questions have no such
|
||||
relationship. `Quiz::getQuestionErrors()` already relies on this distinction to validate that every active candidate is
|
||||
covered exactly once per candidate-bound question (a candidate appearing across multiple group-options on the same
|
||||
question counts as covered more than once).
|
||||
|
||||
### Elimination mechanics
|
||||
|
||||
- **Red/green screens**: at the end of a test, contestants are shown red or green screens one at a time to build tension
|
||||
before the elimination is revealed. `Elimination::$data` stores the colour shown per candidate (
|
||||
`SCREEN_RED/SCREEN_GREEN` via `getScreenColour()`), independent of the actual quiz score.
|
||||
- **Jokers / corrections**: contestants can hold a "joker" (an advantage, e.g. an extra correct answer) that adjusts
|
||||
their effective score without changing what they actually answered. This is `QuizCandidate::$corrections` — a float
|
||||
added to the raw score, kept separate from `GivenAnswer` so the audit trail of what was actually answered stays
|
||||
untouched.
|
||||
- **Dropouts**: `Quiz::$dropouts` controls how many contestants can be eliminated in a single test (normally 1, but some
|
||||
episodes eliminate more).
|
||||
- **Finalization/locking**: `Quiz::$isFinalized` and `$isLocked` gate when a quiz's questions/answers can still be
|
||||
edited — a quiz becomes immutable once a candidate has started it or an admin explicitly finalizes it. Treat this as
|
||||
the natural point where computed results (scores, statistics) can be cached indefinitely, since nothing that feeds
|
||||
them can change afterward.
|
||||
|
||||
### Terminology map (Dutch UI ↔ domain code)
|
||||
|
||||
| UI/domain term (Dutch) | Code |
|
||||
|------------------------------|-------------------------------|
|
||||
| Test | `Quiz` |
|
||||
| Vraag | `Question` |
|
||||
| Antwoord | `Answer` |
|
||||
| Kandidaat | `Candidate` |
|
||||
| Ingevuld antwoord | `GivenAnswer` |
|
||||
| Afvallen / rood-groen scherm | `Elimination` |
|
||||
| Joker / correctie | `QuizCandidate::$corrections` |
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### Routing
|
||||
|
||||
- Routes are **attribute-based** (PHP 8 attributes in controller methods)
|
||||
- Configured in `config/routes/attributes.yaml` for automatic discovery
|
||||
- Main entry point: `config/routes.yaml`
|
||||
|
||||
### Service Container & Dependency Injection
|
||||
|
||||
- Services in `src/` are automatically registered via PSR-4 namespace `Tvdt\`
|
||||
- Exclusions: Entity, DependencyInjection, Kernel classes
|
||||
- Autowiring and autoconfiguration enabled by default
|
||||
- Service definitions in `config/services.yaml`
|
||||
|
||||
### Database & Migrations
|
||||
|
||||
- PostgreSQL-based with Doctrine ORM
|
||||
- Migrations in `migrations/` at project root, namespace `DoctrineMigrations` (intentionally not autoloaded); generate with `bin/console make:migration`
|
||||
- Migrations in `migrations/` at project root, namespace `DoctrineMigrations` (intentionally not autoloaded); generate
|
||||
with `bin/console make:migration`
|
||||
- Test fixtures in `src/DataFixtures/` (loaded with `--group=test`)
|
||||
- Test database configured separately via `.env.test`
|
||||
|
||||
### Testing Infrastructure
|
||||
|
||||
- **PHPUnit 13** with DAMA Doctrine Test Bundle for transaction rollback
|
||||
- Bootstrap: `tests/bootstrap.php` loads env vars and autoloader; `tests/symfony-container.php` boots the test kernel/container (used by Rector)
|
||||
- Bootstrap: `tests/bootstrap.php` loads env vars and autoloader; `tests/symfony-container.php` boots the test
|
||||
kernel/container (used by Rector)
|
||||
- Symfony test utilities (BrowserKit, CSS selectors) available
|
||||
- Coverage excluded from: `src/DataFixtures/`
|
||||
- Test environment: `APP_ENV=test` (set in phpunit.dist.xml)
|
||||
|
||||
### Testing Conventions (TDD)
|
||||
|
||||
- **Write the failing test first.** When fixing any PHP-reachable bug, write a PHPUnit test that reproduces the failure
|
||||
before touching the production code. Fix the code until the test passes.
|
||||
- For bugs in `assets/*.ts` logic, write a `deno test` first instead — same TDD rule, different runner. Only skip a
|
||||
test if the bug is in markup/DOM wiring that isn't worth a test per the rule below.
|
||||
- Don't write tests for trivial presentational markup (e.g. asserting a tooltip/popover attribute or a CSS class exists
|
||||
in a template). Tests cover behavior: routing, forms, persistence, authorization.
|
||||
- Follow the pattern in `tests/Controller/Backoffice/` for controller/integration tests: log in, GET for CSRF token,
|
||||
POST form data, assert redirect, clear entity manager, assert DB state.
|
||||
- **Prefer `TestCase` over `WebTestCase`/`KernelTestCase`.** Reach for the full kernel/DB boot only when the test
|
||||
genuinely needs routing, persistence, or the container — pure logic (services, listeners, helpers) should be tested
|
||||
with plain PHPUnit `TestCase` and mocked dependencies; it's faster and more isolated.
|
||||
- **Boy Scout Rule**: when you're already touching a file for an unrelated change, fix small nearby issues in the same
|
||||
commit (e.g. a test that unnecessarily extends `WebTestCase`, a stale comment) rather than leaving them for later —
|
||||
but don't let this balloon into an unrelated refactor.
|
||||
|
||||
### Code Style & Standards
|
||||
|
||||
- **PHP-CS-Fixer**: Symfony ruleset + risky rules enabled
|
||||
- Strict types declaration required
|
||||
- Trailing commas in multiline structures
|
||||
- No else-only blocks
|
||||
- **Rector**: Aggressive modernization with all attribute sets + prepared sets (dead code, code quality, Doctrine, Symfony, PHPUnit)
|
||||
- Strict types declaration required
|
||||
- Trailing commas in multiline structures
|
||||
- No else-only blocks
|
||||
- **Rector**: Aggressive modernization with all attribute sets + prepared sets (dead code, code quality, Doctrine,
|
||||
Symfony, PHPUnit)
|
||||
- **PHPStan**: Level 8 with extensions for Doctrine and Symfony
|
||||
- **Twig-CS-Fixer**: Template style enforcement
|
||||
- **Safe functions**: Use `thecodingmachine/safe` wrappers for standard PHP functions that return `false` on failure — they throw exceptions instead
|
||||
- **Safe functions**: Use `thecodingmachine/safe` wrappers for standard PHP functions that return `false` on failure —
|
||||
they throw exceptions instead
|
||||
- **TypeScript (`assets/`)**: Compiled via `sensiolabs/typescript-bundle` (standalone SWC binary, no Node/npm).
|
||||
Formatting, linting, type-checking, and tests use **Deno** (`deno fmt` / `deno lint` / `deno check` / `deno test`) —
|
||||
a single standalone binary, kept dev-only (installed in the `frankenphp_dev` Docker stage, not prod), consistent
|
||||
with the project's no-Node-anywhere approach. See `deno.json` for config; run via `just fix-ts` / `just check-ts` /
|
||||
`just test-ts`. Tests live alongside their source as `*_test.ts` files
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
- `.env` - Local development defaults (uncommitted in .env.local)
|
||||
- `.env.dev` - Development overrides
|
||||
- `.env.test` - Test environment configuration
|
||||
- Production uses `composer dump-env prod` for compiled configuration
|
||||
- Key variables:
|
||||
- `APP_ENV` - Environment (dev/test/prod)
|
||||
- `DATABASE_URL` - PostgreSQL connection string
|
||||
- `MAILER_SENDER` - From address for emails
|
||||
- `APP_ENV` - Environment (dev/test/prod)
|
||||
- `DATABASE_URL` - PostgreSQL connection string
|
||||
- `MAILER_SENDER` - From address for emails
|
||||
|
||||
### Frontend Build
|
||||
|
||||
- Asset mapper (no Node.js/Webpack) for JS/CSS bundling; JS modules declared in `importmap.php`
|
||||
- **Stimulus** controllers in `assets/controllers/`, **Turbo** for SPA-like navigation
|
||||
- Sass sources in `assets/styles/`, compiled via `bin/console sass:build`
|
||||
@@ -181,27 +308,29 @@ GitHub Actions workflow (`.github/workflows/ci.yml`):
|
||||
|
||||
1. **Linting**: Dockerfile (hadolint), Twig templates
|
||||
2. **Code Quality**:
|
||||
- PHP-CS-Fixer style check
|
||||
- Twig-CS-Fixer style check
|
||||
- PHPStan static analysis
|
||||
- Rector dry-run
|
||||
- PHP-CS-Fixer style check
|
||||
- Twig-CS-Fixer style check
|
||||
- PHPStan static analysis
|
||||
- Rector dry-run
|
||||
- Translation extraction check (fails if `translation:extract` produces uncommitted changes)
|
||||
3. **Integration Tests**:
|
||||
- Docker image build and start services
|
||||
- Database creation and migration
|
||||
- Fixture loading
|
||||
- Full PHPUnit test suite with JUnit XML output
|
||||
- Doctrine schema validation
|
||||
- Docker image build and start services
|
||||
- Database creation and migration
|
||||
- Fixture loading
|
||||
- Full PHPUnit test suite with JUnit XML output
|
||||
- Doctrine schema validation
|
||||
4. **Build & Deploy** (on tags or main, disabled currently):
|
||||
- Docker image push to GitHub Container Registry
|
||||
- Sentry release creation
|
||||
- Portainer webhook trigger for production deployment
|
||||
- Docker image push to GitHub Container Registry
|
||||
- Sentry release creation
|
||||
- Portainer webhook trigger for production deployment
|
||||
|
||||
Runs on all pushes to main and pull requests. Concurrency cancels old runs on new commits.
|
||||
|
||||
## Important Files & Conventions
|
||||
|
||||
- **Kernel**: `src/Kernel.php` - Symfony kernel class
|
||||
- **AbstractController**: Base class for all controllers — defines route parameter regexes (`SEASON_CODE_REGEX`, `CANDIDATE_HASH_REGEX`) and flash helpers
|
||||
- **AbstractController**: Base class for all controllers — defines route parameter regexes (`SEASON_CODE_REGEX`,
|
||||
`CANDIDATE_HASH_REGEX`) and flash helpers
|
||||
- **Flash Messages**: Use `FlashType` enum instead of string literals
|
||||
- **QuizSpreadsheetService**: Handles importing quizzes from XLSX files
|
||||
- **Rector container**: `tests/symfony-container.php` — boots a test kernel so Rector can resolve Symfony service types
|
||||
@@ -220,13 +349,24 @@ Runs on all pushes to main and pull requests. Concurrency cancels old runs on ne
|
||||
## Composer Scripts
|
||||
|
||||
Auto-executed scripts on install/update:
|
||||
|
||||
- `cache:clear` - Symfony cache clear
|
||||
- `assets:install` - Copy public assets
|
||||
- `importmap:install` - JS import map setup
|
||||
|
||||
## Writing Style (Help Content & UI Text)
|
||||
|
||||
When writing Dutch help content in `templates/backoffice/help/nl/`:
|
||||
|
||||
- **No em-dashes** (—): use a comma or restructure the sentence instead.
|
||||
- **No semicolons** (;): use a comma. Semicolons are technically correct but read as AI-generated text.
|
||||
- **Natural Dutch**: write the way a person would explain it to a colleague, not in formal documentation style.
|
||||
- **Colons after bold labels** (e.g. `<strong>Label:</strong> description`) are fine and intentional.
|
||||
|
||||
## Notes for Future Work
|
||||
|
||||
- The backoffice elimination logic is in `Controller/Backoffice/PrepareEliminationController.php`
|
||||
- Quiz timing logic starts on candidate start click and stops on final answer selection
|
||||
- Background music feature noted but not yet implemented (requirements only)
|
||||
- Statistics functionality is marked TBD in README
|
||||
- Statistics module (per-quiz statistics page, candidate accusation matrix, caching) is planned per GitHub issue #199 —
|
||||
see "Domain Context" above for why candidate-bound answers matter to it
|
||||
|
||||
+11
-1
@@ -32,7 +32,6 @@ RUN set -eux; \
|
||||
opcache \
|
||||
zip \
|
||||
gd \
|
||||
excimer \
|
||||
;
|
||||
|
||||
# https://getcomposer.org/doc/03-cli.md#composer-allow-superuser
|
||||
@@ -63,11 +62,18 @@ ENV APP_ENV=dev XDEBUG_MODE=off
|
||||
# hadolint ignore=DL3008
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
bash-completion \
|
||||
unzip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --link frankenphp/console-complete.bash /usr/share/bash-completion/completions/console
|
||||
COPY --link frankenphp/composer-complete.bash /usr/share/bash-completion/completions/composer
|
||||
|
||||
# Deno: standalone binary (no Node/npm) used for TypeScript lint/format/type-check/test,
|
||||
# dev-only tooling so it's not installed in the prod stage.
|
||||
ENV DENO_INSTALL=/usr/local
|
||||
# hadolint ignore=DL4006
|
||||
RUN curl -fsSL https://deno.land/install.sh | sh -s v2.9.2
|
||||
|
||||
RUN mv "$PHP_INI_DIR/php.ini-development" "$PHP_INI_DIR/php.ini"
|
||||
|
||||
RUN set -eux; \
|
||||
@@ -110,3 +116,7 @@ RUN set -eux; \
|
||||
bin/console sass:build; \
|
||||
bin/console asset-map:compile --no-debug --quiet --no-ansi; \
|
||||
sync;
|
||||
|
||||
# Build timestamp for /.well-known/security.txt Expires; must be injected last to avoid cache busting.
|
||||
ARG BUILD_TIME=""
|
||||
ENV BUILD_TIME=$BUILD_TIME
|
||||
|
||||
@@ -1,9 +1,81 @@
|
||||
up *args:
|
||||
# Load per-worktree overrides (project name, image tag, ports) generated by `just init`
|
||||
set dotenv-load := true
|
||||
set dotenv-filename := ".env.local"
|
||||
|
||||
# Generate a per-worktree COMPOSE_PROJECT_NAME, IMAGES_PREFIX and free host ports in .env.local,
|
||||
# so multiple worktrees/checkouts of this repo can run `just up` at the same time without their
|
||||
# containers, volumes, images or ports colliding. Safe to re-run; no-ops if already configured.
|
||||
init:
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [ -f .env.local ] && grep -q '^COMPOSE_PROJECT_NAME=' .env.local; then
|
||||
echo ".env.local already configured for this worktree, skipping (delete it to regenerate)."
|
||||
exit 0
|
||||
fi
|
||||
free_port() {
|
||||
local port="$1" max="$2"
|
||||
while [ "$port" -le "$max" ]; do
|
||||
if ! (exec 3<>/dev/tcp/127.0.0.1/"$port") 2>/dev/null; then
|
||||
echo "$port"
|
||||
return
|
||||
fi
|
||||
exec 3>&- 2>/dev/null || true
|
||||
port=$((port + 1))
|
||||
done
|
||||
echo "no free port found between $1 and $2" >&2
|
||||
exit 1
|
||||
}
|
||||
if command -v sha1sum >/dev/null 2>&1; then
|
||||
hash_cmd=(sha1sum)
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
hash_cmd=(shasum)
|
||||
else
|
||||
hash_cmd=(sha256sum)
|
||||
fi
|
||||
hash=$(pwd | "${hash_cmd[@]}" | cut -c1-8)
|
||||
project="tvdt-${hash}"
|
||||
http_port=$(free_port 8080 8179)
|
||||
https_port=$(free_port 8443 8542)
|
||||
postgres_port=$(free_port 5430 5529)
|
||||
mailpit_port=$(free_port 8025 8124)
|
||||
spotlight_port=$(free_port 8969 9068)
|
||||
{
|
||||
echo "COMPOSE_PROJECT_NAME=${project}"
|
||||
echo "IMAGES_PREFIX=${project}-"
|
||||
echo "HTTP_PORT=${http_port}"
|
||||
echo "HTTPS_PORT=${https_port}"
|
||||
echo "POSTGRES_PORT=${postgres_port}"
|
||||
echo "MAILPIT_PORT=${mailpit_port}"
|
||||
echo "SPOTLIGHT_PORT=${spotlight_port}"
|
||||
} >> .env.local
|
||||
echo "Generated .env.local for this worktree:"
|
||||
cat .env.local
|
||||
|
||||
up *args: init
|
||||
#!/usr/bin/env bash
|
||||
set -a
|
||||
[ -f .env.local ] && source .env.local
|
||||
set +a
|
||||
docker compose up -d {{ args }}
|
||||
|
||||
down *args:
|
||||
docker compose down --remove-orphans {{ args }}
|
||||
|
||||
# Show the URLs (and DB connection) assigned to this worktree (see `just init`)
|
||||
ports:
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
if [ ! -f .env.local ]; then
|
||||
echo "No .env.local yet, run 'just up' or 'just init' first."
|
||||
exit 0
|
||||
fi
|
||||
set -a
|
||||
source .env.local
|
||||
set +a
|
||||
echo "Tvdt: https://localhost:${HTTPS_PORT}"
|
||||
echo "Mailpit: http://localhost:${MAILPIT_PORT}"
|
||||
echo "Spotlight: http://localhost:${SPOTLIGHT_PORT}"
|
||||
|
||||
stop:
|
||||
docker compose stop
|
||||
|
||||
@@ -40,6 +112,16 @@ phpstan *args:
|
||||
test *args:
|
||||
docker compose exec php vendor/bin/phpunit {{ args }}
|
||||
|
||||
fix-ts:
|
||||
docker compose exec php deno fmt assets/
|
||||
docker compose exec php deno lint --fix assets/
|
||||
|
||||
check-ts:
|
||||
docker compose exec php deno check assets/*.ts assets/controllers/*.ts assets/controllers/bo/*.ts
|
||||
|
||||
test-ts *args:
|
||||
docker compose exec php deno test assets/ {{ args }}
|
||||
|
||||
[confirm]
|
||||
clean:
|
||||
docker compose down -v --remove-orphans
|
||||
|
||||
@@ -25,8 +25,13 @@ just migrate # Run pending database migrations
|
||||
just fixtures # Load dev fixtures (truncates first)
|
||||
```
|
||||
|
||||
The app is available at **https://localhost** (self-signed cert — run
|
||||
`just trust-cert` on macOS to trust it).
|
||||
`just up` first runs `just init`, which generates a `.env.local` (gitignored)
|
||||
with a unique `COMPOSE_PROJECT_NAME`, image tag and free host ports for this
|
||||
checkout, so multiple worktrees/clones can run at the same time without their
|
||||
containers, volumes, images or ports colliding. Run `just ports` to see the
|
||||
ports assigned to the current checkout — the app is served at
|
||||
`https://localhost:<HTTPS_PORT>` (self-signed cert — run `just trust-cert` on
|
||||
macOS to trust it).
|
||||
|
||||
### Useful commands
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import './styles/backoffice.scss';
|
||||
import './stimulus.js';
|
||||
import './bootstrap.js';
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import 'bootstrap-icons/font/bootstrap-icons.min.css';
|
||||
import './styles/backoffice.scss';
|
||||
import '@hotwired/turbo';
|
||||
import './stimulus.ts';
|
||||
import './bootstrap.ts';
|
||||
import * as Sentry from '@sentry/browser';
|
||||
|
||||
const dsn = document.querySelector<HTMLMetaElement>('meta[name="sentry-dsn"]')
|
||||
?.content ?? '';
|
||||
const userEmail =
|
||||
document.querySelector<HTMLMetaElement>('meta[name="user-email"]')
|
||||
?.content ?? '';
|
||||
|
||||
// When no real DSN is configured, route to the local Spotlight sidecar so
|
||||
// nothing reaches Sentry. A syntactically valid DSN is still required for the
|
||||
// SDK to initialise; the tunnel option redirects all transport to Spotlight.
|
||||
const useSpotlight = !dsn;
|
||||
const effectiveDsn = dsn || 'https://0@o0.ingest.sentry.io/0';
|
||||
|
||||
const feedbackIntegration = Sentry.feedbackIntegration({
|
||||
colorScheme: 'system',
|
||||
showName: false,
|
||||
showEmail: true,
|
||||
isEmailRequired: false,
|
||||
autoInject: false,
|
||||
triggerLabel: 'Report feedback',
|
||||
formTitle: 'Report Feedback',
|
||||
submitButtonLabel: 'Send Feedback',
|
||||
});
|
||||
|
||||
Sentry.init({
|
||||
dsn: effectiveDsn,
|
||||
tunnel: useSpotlight ? 'http://localhost:8969/stream' : undefined,
|
||||
integrations: [feedbackIntegration],
|
||||
});
|
||||
|
||||
// autoInject is unreliable in Sentry v10 due to the setupOnce guard; mount manually.
|
||||
feedbackIntegration.createWidget();
|
||||
|
||||
if (userEmail) {
|
||||
Sentry.setUser({ email: userEmail });
|
||||
}
|
||||
Vendored
-1
@@ -1 +0,0 @@
|
||||
import * as bootstrap from 'bootstrap'
|
||||
@@ -0,0 +1 @@
|
||||
import 'bootstrap';
|
||||
@@ -0,0 +1,172 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['collection'];
|
||||
static values = { prototype: String };
|
||||
|
||||
declare readonly collectionTarget: HTMLElement;
|
||||
declare readonly prototypeValue: string;
|
||||
|
||||
index = 0;
|
||||
_dragging: Element | null = null;
|
||||
_form: HTMLFormElement | null = null;
|
||||
_submitHandler: (() => void) | null = null;
|
||||
|
||||
connect(): void {
|
||||
this.index = this.collectionTarget.children.length;
|
||||
this._syncOrdering();
|
||||
|
||||
if (this.index === 0) {
|
||||
this.addItem();
|
||||
}
|
||||
|
||||
// `submit` fires on the ancestor <form>, which is outside this controller's
|
||||
// subtree. Stimulus data-action only works within the controller element, so
|
||||
// addEventListener on the form is the only option here.
|
||||
this._form = this.element.closest('form');
|
||||
if (this._form) {
|
||||
this._submitHandler = () => {
|
||||
[...this.collectionTarget.children].forEach((item) => {
|
||||
const input = item.querySelector<HTMLInputElement>(
|
||||
'input[type="text"]',
|
||||
);
|
||||
if (input && input.value.trim() === '') item.remove();
|
||||
});
|
||||
};
|
||||
this._form.addEventListener('submit', this._submitHandler);
|
||||
}
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
if (this._form && this._submitHandler) {
|
||||
this._form.removeEventListener('submit', this._submitHandler);
|
||||
}
|
||||
}
|
||||
|
||||
addItem(): void {
|
||||
const item = document.createElement('div');
|
||||
item.innerHTML = this.prototypeValue.replace(
|
||||
/__name__/g,
|
||||
String(this.index),
|
||||
);
|
||||
const el = item.firstElementChild;
|
||||
if (el) this.collectionTarget.appendChild(el);
|
||||
this.index++;
|
||||
this._syncOrdering();
|
||||
}
|
||||
|
||||
removeItem(event: Event): void {
|
||||
(event.target as HTMLElement).closest('[data-collection-item]')
|
||||
?.remove();
|
||||
this._notifyChange();
|
||||
}
|
||||
|
||||
sortAlphabetically(): void {
|
||||
const items = [...this.collectionTarget.children];
|
||||
items.sort((a, b) => {
|
||||
const textA =
|
||||
(a.querySelector<HTMLInputElement>('input[type="text"]')
|
||||
?.value ?? '').toLowerCase();
|
||||
const textB =
|
||||
(b.querySelector<HTMLInputElement>('input[type="text"]')
|
||||
?.value ?? '').toLowerCase();
|
||||
return textA.localeCompare(textB);
|
||||
});
|
||||
items.forEach((item) => this.collectionTarget.appendChild(item));
|
||||
this._syncOrdering();
|
||||
this._notifyChange();
|
||||
}
|
||||
|
||||
randomize(): void {
|
||||
const items = [...this.collectionTarget.children];
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[items[i], items[j]] = [items[j], items[i]];
|
||||
}
|
||||
items.forEach((item) => this.collectionTarget.appendChild(item));
|
||||
this._syncOrdering();
|
||||
this._notifyChange();
|
||||
}
|
||||
|
||||
autoExpand(event: Event): void {
|
||||
const target = event.target as HTMLInputElement;
|
||||
if (target.type !== 'text') return;
|
||||
const item = target.closest('[data-collection-item]');
|
||||
const last = [...this.collectionTarget.children].at(-1);
|
||||
if (item && item === last && target.value.trim() !== '') {
|
||||
this.addItem();
|
||||
}
|
||||
}
|
||||
|
||||
// — drag-and-drop —
|
||||
|
||||
dragStart(event: DragEvent): void {
|
||||
this._dragging = (event.currentTarget as HTMLElement).closest(
|
||||
'[data-collection-item]',
|
||||
);
|
||||
this._dragging?.classList.add('opacity-50');
|
||||
event.dataTransfer!.effectAllowed = 'move';
|
||||
}
|
||||
|
||||
dragEnd(event: DragEvent): void {
|
||||
(event.currentTarget as HTMLElement).closest('[data-collection-item]')
|
||||
?.classList.remove('opacity-50');
|
||||
this._dragging = null;
|
||||
this.collectionTarget.querySelectorAll('[data-collection-item]')
|
||||
.forEach((i) =>
|
||||
i.classList.remove(
|
||||
'border-top',
|
||||
'border-bottom',
|
||||
'border-primary',
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
dragOver(event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
const el = event.currentTarget as HTMLElement;
|
||||
if (!this._dragging || this._dragging === el) return;
|
||||
event.dataTransfer!.dropEffect = 'move';
|
||||
const rect = el.getBoundingClientRect();
|
||||
const isBottom = event.clientY > rect.top + rect.height / 2;
|
||||
el.classList.toggle('border-top', !isBottom);
|
||||
el.classList.toggle('border-bottom', isBottom);
|
||||
el.classList.add('border-primary');
|
||||
}
|
||||
|
||||
dragLeave(event: DragEvent): void {
|
||||
(event.currentTarget as HTMLElement).classList.remove(
|
||||
'border-top',
|
||||
'border-bottom',
|
||||
'border-primary',
|
||||
);
|
||||
}
|
||||
|
||||
drop(event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
const el = event.currentTarget as HTMLElement;
|
||||
el.classList.remove('border-top', 'border-bottom', 'border-primary');
|
||||
if (!this._dragging || this._dragging === el) return;
|
||||
const rect = el.getBoundingClientRect();
|
||||
const isBottom = event.clientY > rect.top + rect.height / 2;
|
||||
this.collectionTarget.insertBefore(
|
||||
this._dragging,
|
||||
isBottom ? el.nextSibling : el,
|
||||
);
|
||||
this._syncOrdering();
|
||||
this._notifyChange();
|
||||
}
|
||||
|
||||
_notifyChange(): void {
|
||||
this.element.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
|
||||
_syncOrdering(): void {
|
||||
[...this.collectionTarget.children].forEach((el, i) => {
|
||||
const input = el.querySelector<HTMLInputElement>(
|
||||
'input[name*="[ordering]"]',
|
||||
);
|
||||
if (input) input.value = String(i);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { assertEquals } from '@std/assert';
|
||||
|
||||
// Stimulus's Controller base class constructor only does `this.context = context`,
|
||||
// and target getters are normally installed by Application.register — since we
|
||||
// construct the controller directly (no real Stimulus app), collectionTarget/element
|
||||
// are assigned here as plain writable properties, backed by a minimal fake DOM
|
||||
// container that supports the one operation these methods actually rely on:
|
||||
// appendChild() moving an existing child to the end (real DOM semantics).
|
||||
class FakeInput {
|
||||
value: string;
|
||||
constructor(value = '') {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeItem {
|
||||
textInput: FakeInput;
|
||||
orderingInput = new FakeInput();
|
||||
|
||||
constructor(text: string) {
|
||||
this.textInput = new FakeInput(text);
|
||||
}
|
||||
|
||||
querySelector<T>(selector: string): T | null {
|
||||
if (selector.includes('type="text"')) {
|
||||
return this.textInput as unknown as T;
|
||||
}
|
||||
if (selector.includes('ordering')) {
|
||||
return this.orderingInput as unknown as T;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeCollection {
|
||||
children: FakeItem[] = [];
|
||||
|
||||
appendChild(item: FakeItem) {
|
||||
const idx = this.children.indexOf(item);
|
||||
if (idx !== -1) this.children.splice(idx, 1);
|
||||
this.children.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
const { default: FormCollectionController } = await import(
|
||||
'./form_collection_controller.ts'
|
||||
);
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function makeController(items: FakeItem[]): any {
|
||||
const collectionTarget = new FakeCollection();
|
||||
collectionTarget.children = items;
|
||||
// `element` is a read-only getter on Controller (delegates to `this.scope.element`),
|
||||
// so the fake element is supplied via the constructor context rather than assigned.
|
||||
const controller = new FormCollectionController({
|
||||
scope: { element: { dispatchEvent: () => true } },
|
||||
} as never);
|
||||
return Object.assign(controller, { collectionTarget });
|
||||
}
|
||||
|
||||
Deno.test("_syncOrdering writes the current index into each item's ordering input", () => {
|
||||
const items = [new FakeItem('c'), new FakeItem('a'), new FakeItem('b')];
|
||||
const controller = makeController(items);
|
||||
|
||||
controller._syncOrdering();
|
||||
|
||||
assertEquals(items.map((i) => i.orderingInput.value), ['0', '1', '2']);
|
||||
});
|
||||
|
||||
Deno.test('sortAlphabetically reorders items by their text input value, case-insensitively', () => {
|
||||
const c = new FakeItem('Charlie');
|
||||
const a = new FakeItem('alice');
|
||||
const b = new FakeItem('Bob');
|
||||
const controller = makeController([c, a, b]);
|
||||
|
||||
controller.sortAlphabetically();
|
||||
|
||||
assertEquals(
|
||||
controller.collectionTarget.children.map((i: FakeItem) =>
|
||||
i.textInput.value
|
||||
),
|
||||
['alice', 'Bob', 'Charlie'],
|
||||
);
|
||||
// _syncOrdering must run after the reorder, against the new order
|
||||
assertEquals(
|
||||
controller.collectionTarget.children.map((i: FakeItem) =>
|
||||
i.orderingInput.value
|
||||
),
|
||||
['0', '1', '2'],
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test('randomize keeps the same set of items and resyncs ordering', () => {
|
||||
const items = [
|
||||
new FakeItem('1'),
|
||||
new FakeItem('2'),
|
||||
new FakeItem('3'),
|
||||
new FakeItem('4'),
|
||||
];
|
||||
const controller = makeController([...items]);
|
||||
|
||||
controller.randomize();
|
||||
|
||||
const resultValues = controller.collectionTarget.children.map((
|
||||
i: FakeItem,
|
||||
) => i.textInput.value);
|
||||
assertEquals(resultValues.slice().sort(), ['1', '2', '3', '4']);
|
||||
assertEquals(
|
||||
controller.collectionTarget.children.map((i: FakeItem) =>
|
||||
i.orderingInput.value
|
||||
),
|
||||
['0', '1', '2', '3'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
import { Modal } from 'bootstrap';
|
||||
import { visit } from '@hotwired/turbo';
|
||||
|
||||
// Bootstrap's public Modal type doesn't expose `_config` (an internal, but stable, field
|
||||
// across all 5.x releases) — extend it locally rather than casting to `any` everywhere.
|
||||
interface ModalWithConfig extends Modal {
|
||||
_config: { backdrop: boolean | 'static'; keyboard: boolean };
|
||||
}
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['modal', 'frame'];
|
||||
|
||||
declare readonly modalTarget: HTMLElement;
|
||||
declare readonly frameTarget: HTMLElement;
|
||||
|
||||
_dirty = false;
|
||||
|
||||
open(event: MouseEvent): void {
|
||||
event.preventDefault();
|
||||
const { src, modalTitle } =
|
||||
(event.currentTarget as HTMLElement).dataset;
|
||||
if (modalTitle) {
|
||||
const titleEl = this.modalTarget.querySelector('.modal-title');
|
||||
if (titleEl) titleEl.textContent = modalTitle;
|
||||
}
|
||||
this.resetDirty();
|
||||
this.frameTarget.innerHTML =
|
||||
'<div class="modal-body text-center py-4"><div class="spinner-border" role="status"></div></div>';
|
||||
this.frameTarget.removeAttribute('src');
|
||||
if (src) this.frameTarget.setAttribute('src', src);
|
||||
Modal.getOrCreateInstance(this.modalTarget).show();
|
||||
}
|
||||
|
||||
frameSubmitEnd(event: CustomEvent<{ success: boolean }>): void {
|
||||
if (event.detail.success) {
|
||||
Modal.getOrCreateInstance(this.modalTarget).hide();
|
||||
visit(window.location.href);
|
||||
}
|
||||
}
|
||||
|
||||
markDirty(): void {
|
||||
if (this._dirty) return;
|
||||
this._dirty = true;
|
||||
// Using _config instead of preventDefault on hide.bs.modal because we need
|
||||
// to block only user-triggered dismissal (backdrop click, Escape key) while
|
||||
// keeping programmatic hide() working — frameSubmitEnd() calls hide() after
|
||||
// a successful save and must not be blocked. _config.backdrop/keyboard is
|
||||
// the correct primitive for that distinction and has been stable across all
|
||||
// Bootstrap 5.x releases.
|
||||
const modal = Modal.getOrCreateInstance(
|
||||
this.modalTarget,
|
||||
) as ModalWithConfig;
|
||||
modal._config.backdrop = 'static';
|
||||
modal._config.keyboard = false;
|
||||
}
|
||||
|
||||
resetDirty(): void {
|
||||
this._dirty = false;
|
||||
const modal = Modal.getOrCreateInstance(
|
||||
this.modalTarget,
|
||||
) as ModalWithConfig;
|
||||
modal._config.backdrop = true;
|
||||
modal._config.keyboard = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
import { Popover } from 'bootstrap';
|
||||
|
||||
export default class extends Controller {
|
||||
popovers: Popover[] = [];
|
||||
|
||||
connect(): void {
|
||||
this.popovers = [
|
||||
...this.element.querySelectorAll('[data-bs-toggle="popover"]'),
|
||||
]
|
||||
.map((popoverTriggerEl) =>
|
||||
Popover.getOrCreateInstance(popoverTriggerEl)
|
||||
);
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.popovers.forEach((popover) => popover.dispose());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
|
||||
type Status = 'saving' | 'saved' | 'error';
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['list', 'item', 'status'];
|
||||
static values = {
|
||||
reorderUrl: String,
|
||||
csrf: String,
|
||||
savedLabel: String,
|
||||
errorLabel: String,
|
||||
errorHint: String,
|
||||
};
|
||||
|
||||
declare readonly listTarget: HTMLElement;
|
||||
declare readonly itemTargets: HTMLElement[];
|
||||
declare readonly statusTarget: HTMLElement;
|
||||
declare readonly hasStatusTarget: boolean;
|
||||
|
||||
declare readonly reorderUrlValue: string;
|
||||
declare readonly csrfValue: string;
|
||||
declare readonly savedLabelValue: string;
|
||||
declare readonly errorLabelValue: string;
|
||||
declare readonly errorHintValue: string;
|
||||
|
||||
_locked = false;
|
||||
_dragging: HTMLElement | null = null;
|
||||
_placeholder: HTMLDivElement | null = null;
|
||||
|
||||
connect(): void {
|
||||
this._locked = false;
|
||||
}
|
||||
|
||||
dragStart(event: DragEvent): void {
|
||||
const item = (event.currentTarget as HTMLElement).closest<HTMLElement>(
|
||||
'[data-bo--question-list-target="item"]',
|
||||
);
|
||||
this._dragging = item;
|
||||
event.dataTransfer!.effectAllowed = 'move';
|
||||
setTimeout(() => item?.classList.add('opacity-50'), 0);
|
||||
}
|
||||
|
||||
dragEnd(event: DragEvent): void {
|
||||
const item = (event.currentTarget as HTMLElement).closest<HTMLElement>(
|
||||
'[data-bo--question-list-target="item"]',
|
||||
);
|
||||
item?.classList.remove('opacity-50');
|
||||
this._dragging = null;
|
||||
this._removePlaceholder();
|
||||
}
|
||||
|
||||
dragOver(event: DragEvent): void {
|
||||
event.preventDefault();
|
||||
if (!this._dragging) return;
|
||||
event.dataTransfer!.dropEffect = 'move';
|
||||
|
||||
const target = (event.target as HTMLElement).closest<HTMLElement>(
|
||||
'[data-bo--question-list-target="item"]',
|
||||
);
|
||||
if (!target || target === this._dragging) return;
|
||||
|
||||
const rect = target.getBoundingClientRect();
|
||||
const insertBefore = event.clientY > rect.top + rect.height / 2
|
||||
? target.nextSibling
|
||||
: target;
|
||||
|
||||
if (!this._placeholder) {
|
||||
this._placeholder = document.createElement('div');
|
||||
this._placeholder.className = 'bg-primary rounded mb-2';
|
||||
this._placeholder.style.height = '3px';
|
||||
}
|
||||
|
||||
if (this._placeholder.nextSibling !== insertBefore) {
|
||||
this.listTarget.insertBefore(this._placeholder, insertBefore);
|
||||
}
|
||||
}
|
||||
|
||||
dragLeave(event: DragEvent): void {
|
||||
if (
|
||||
!event.relatedTarget ||
|
||||
!this.listTarget.contains(event.relatedTarget as Node)
|
||||
) {
|
||||
this._removePlaceholder();
|
||||
}
|
||||
}
|
||||
|
||||
async drop(event: DragEvent): Promise<void> {
|
||||
event.preventDefault();
|
||||
if (!this._dragging || !this._placeholder || this._locked) return;
|
||||
this.listTarget.insertBefore(this._dragging, this._placeholder);
|
||||
this._removePlaceholder();
|
||||
await this._persistOrder();
|
||||
}
|
||||
|
||||
_removePlaceholder(): void {
|
||||
if (this._placeholder) {
|
||||
this._placeholder.remove();
|
||||
this._placeholder = null;
|
||||
}
|
||||
}
|
||||
|
||||
_setStatus(state: Status): void {
|
||||
if (!this.hasStatusTarget) return;
|
||||
const el = this.statusTarget;
|
||||
el.classList.remove(
|
||||
'd-none',
|
||||
'text-bg-success',
|
||||
'text-bg-danger',
|
||||
'text-bg-warning',
|
||||
);
|
||||
if (state === 'saving') {
|
||||
el.classList.add('text-bg-warning');
|
||||
el.textContent = '…';
|
||||
} else if (state === 'saved') {
|
||||
el.classList.add('text-bg-success');
|
||||
el.textContent = this.savedLabelValue || 'Saved';
|
||||
} else if (state === 'error') {
|
||||
el.classList.add('text-bg-danger');
|
||||
el.textContent = this.errorLabelValue || 'Error';
|
||||
}
|
||||
}
|
||||
|
||||
async _persistOrder(): Promise<void> {
|
||||
this._setStatus('saving');
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append('_token', this.csrfValue);
|
||||
this.itemTargets.forEach((el, i) => {
|
||||
params.append('ordering[]', el.dataset.questionId ?? '');
|
||||
const numberEl = el.querySelector('[data-question-number]');
|
||||
if (numberEl) numberEl.textContent = String(i + 1);
|
||||
});
|
||||
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
const res = await fetch(this.reorderUrlValue, {
|
||||
method: 'POST',
|
||||
body: params,
|
||||
});
|
||||
if (res.ok) {
|
||||
this._setStatus('saved');
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// network error — retry on first attempt
|
||||
}
|
||||
}
|
||||
|
||||
this._locked = true;
|
||||
this._setStatus('error');
|
||||
|
||||
const alert = document.createElement('div');
|
||||
alert.className = 'alert alert-danger alert-dismissible mt-3';
|
||||
alert.setAttribute('role', 'alert');
|
||||
const hint = this.errorHintValue || 'Refresh the page to try again.';
|
||||
alert.innerHTML = `${
|
||||
this.errorLabelValue || 'Error saving order'
|
||||
} — ${hint} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`;
|
||||
this.listTarget.after(alert);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { assertEquals } from '@std/assert';
|
||||
|
||||
// Stimulus's Controller base class constructor only does `this.context = context`,
|
||||
// and target/value getters (listTarget, csrfValue, ...) are normally installed by
|
||||
// Application.register — since we construct the controller directly (no real
|
||||
// Stimulus app), they're assigned here as plain writable properties instead.
|
||||
class FakeClassList {
|
||||
classes = new Set<string>();
|
||||
add(...names: string[]) {
|
||||
names.forEach((n) => this.classes.add(n));
|
||||
}
|
||||
remove(...names: string[]) {
|
||||
names.forEach((n) => this.classes.delete(n));
|
||||
}
|
||||
contains(name: string) {
|
||||
return this.classes.has(name);
|
||||
}
|
||||
}
|
||||
|
||||
function fakeElement() {
|
||||
return {
|
||||
classList: new FakeClassList(),
|
||||
textContent: '',
|
||||
after: () => {},
|
||||
setAttribute: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(globalThis as any).document = {
|
||||
createElement: () => ({
|
||||
...fakeElement(),
|
||||
innerHTML: '',
|
||||
}),
|
||||
};
|
||||
|
||||
const { default: QuestionListController } = await import(
|
||||
'./question_list_controller.ts'
|
||||
);
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function makeController(overrides: Record<string, unknown> = {}): any {
|
||||
const controller = new QuestionListController({} as never);
|
||||
return Object.assign(controller, {
|
||||
listTarget: fakeElement(),
|
||||
itemTargets: [],
|
||||
hasStatusTarget: true,
|
||||
statusTarget: fakeElement(),
|
||||
csrfValue: 'csrf-token',
|
||||
reorderUrlValue: '/reorder',
|
||||
savedLabelValue: 'Saved',
|
||||
errorLabelValue: 'Error',
|
||||
errorHintValue: 'Refresh the page.',
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
Deno.test('_setStatus renders the saving state', () => {
|
||||
const controller = makeController();
|
||||
controller._setStatus('saving');
|
||||
assertEquals(
|
||||
controller.statusTarget.classList.contains('text-bg-warning'),
|
||||
true,
|
||||
);
|
||||
assertEquals(controller.statusTarget.textContent, '…');
|
||||
});
|
||||
|
||||
Deno.test('_setStatus renders the saved state with the configured label', () => {
|
||||
const controller = makeController();
|
||||
controller._setStatus('saved');
|
||||
assertEquals(
|
||||
controller.statusTarget.classList.contains('text-bg-success'),
|
||||
true,
|
||||
);
|
||||
assertEquals(controller.statusTarget.textContent, 'Saved');
|
||||
});
|
||||
|
||||
Deno.test('_setStatus is a no-op when there is no status target', () => {
|
||||
const controller = makeController({ hasStatusTarget: false });
|
||||
controller._setStatus('saving');
|
||||
assertEquals(controller.statusTarget.textContent, '');
|
||||
});
|
||||
|
||||
Deno.test('_persistOrder posts the item ordering and reports success', async () => {
|
||||
const numberEl = { textContent: '' };
|
||||
const item = {
|
||||
dataset: { questionId: '42' },
|
||||
querySelector: () => numberEl,
|
||||
};
|
||||
const controller = makeController({ itemTargets: [item] });
|
||||
|
||||
let requestBody: URLSearchParams | undefined;
|
||||
globalThis.fetch = ((_url: string, init: RequestInit) => {
|
||||
requestBody = init.body as URLSearchParams;
|
||||
return Promise.resolve({ ok: true } as Response);
|
||||
}) as typeof fetch;
|
||||
|
||||
await controller._persistOrder();
|
||||
|
||||
assertEquals(controller._locked, false);
|
||||
assertEquals(
|
||||
controller.statusTarget.classList.contains('text-bg-success'),
|
||||
true,
|
||||
);
|
||||
assertEquals(numberEl.textContent, '1');
|
||||
assertEquals(requestBody?.get('_token'), 'csrf-token');
|
||||
assertEquals(requestBody?.get('ordering[]'), '42');
|
||||
});
|
||||
|
||||
Deno.test('_persistOrder retries once, then locks and shows an error after repeated failure', async () => {
|
||||
const controller = makeController();
|
||||
let calls = 0;
|
||||
globalThis.fetch = (() => {
|
||||
calls++;
|
||||
return Promise.resolve({ ok: false } as Response);
|
||||
}) as typeof fetch;
|
||||
|
||||
await controller._persistOrder();
|
||||
|
||||
assertEquals(calls, 2);
|
||||
assertEquals(controller._locked, true);
|
||||
assertEquals(
|
||||
controller.statusTarget.classList.contains('text-bg-danger'),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test('_persistOrder treats a network error the same as a failed response', async () => {
|
||||
const controller = makeController();
|
||||
globalThis.fetch =
|
||||
(() => Promise.reject(new Error('network down'))) as typeof fetch;
|
||||
|
||||
await controller._persistOrder();
|
||||
|
||||
assertEquals(controller._locked, true);
|
||||
assertEquals(
|
||||
controller.statusTarget.classList.contains('text-bg-danger'),
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import {Controller} from '@hotwired/stimulus';
|
||||
import {Tooltip, Modal} from 'bootstrap';
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['clearModal', 'deleteModal'];
|
||||
|
||||
connect() {
|
||||
this.tooltips = [];
|
||||
const tooltipTriggerList = this.element.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
[...tooltipTriggerList].forEach(tooltipTriggerEl => {
|
||||
this.tooltips.push(Tooltip.getOrCreateInstance(tooltipTriggerEl));
|
||||
});
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
this.tooltips.forEach(tooltip => tooltip.dispose());
|
||||
}
|
||||
|
||||
clearQuiz() {
|
||||
const modal = Modal.getOrCreateInstance(this.clearModalTarget);
|
||||
modal.show();
|
||||
}
|
||||
|
||||
deleteQuiz() {
|
||||
const modal = Modal.getOrCreateInstance(this.deleteModalTarget);
|
||||
modal.show();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
import { Modal, Tooltip } from 'bootstrap';
|
||||
|
||||
export default class extends Controller {
|
||||
static targets = ['clearModal', 'deleteModal'];
|
||||
|
||||
declare readonly clearModalTarget: HTMLElement;
|
||||
declare readonly deleteModalTarget: HTMLElement;
|
||||
|
||||
tooltips: Tooltip[] = [];
|
||||
|
||||
connect(): void {
|
||||
this.tooltips = [];
|
||||
const tooltipTriggerList = this.element.querySelectorAll(
|
||||
'[data-bs-toggle="tooltip"]',
|
||||
);
|
||||
[...tooltipTriggerList].forEach((tooltipTriggerEl) => {
|
||||
this.tooltips.push(Tooltip.getOrCreateInstance(tooltipTriggerEl));
|
||||
});
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.tooltips.forEach((tooltip) => tooltip.dispose());
|
||||
}
|
||||
|
||||
clearQuiz(): void {
|
||||
const modal = Modal.getOrCreateInstance(this.clearModalTarget);
|
||||
modal.show();
|
||||
}
|
||||
|
||||
deleteQuiz(): void {
|
||||
const modal = Modal.getOrCreateInstance(this.deleteModalTarget);
|
||||
modal.show();
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
const nameCheck = /^[-_a-zA-Z0-9]{4,22}$/;
|
||||
const tokenCheck = /^[-_/+a-zA-Z0-9]{24,}$/;
|
||||
|
||||
// Generate and double-submit a CSRF token in a form field and a cookie, as defined by Symfony's SameOriginCsrfTokenManager
|
||||
// Use `form.requestSubmit()` to ensure that the submit event is triggered. Using `form.submit()` will not trigger the event
|
||||
// and thus this event-listener will not be executed.
|
||||
document.addEventListener('submit', function (event) {
|
||||
generateCsrfToken(event.target);
|
||||
}, true);
|
||||
|
||||
// When @hotwired/turbo handles form submissions, send the CSRF token in a header in addition to a cookie
|
||||
// The `framework.csrf_protection.check_header` config option needs to be enabled for the header to be checked
|
||||
document.addEventListener('turbo:submit-start', function (event) {
|
||||
const h = generateCsrfHeaders(event.detail.formSubmission.formElement);
|
||||
Object.keys(h).map(function (k) {
|
||||
event.detail.formSubmission.fetchRequest.headers[k] = h[k];
|
||||
});
|
||||
});
|
||||
|
||||
// When @hotwired/turbo handles form submissions, remove the CSRF cookie once a form has been submitted
|
||||
document.addEventListener('turbo:submit-end', function (event) {
|
||||
removeCsrfToken(event.detail.formSubmission.formElement);
|
||||
});
|
||||
|
||||
export function generateCsrfToken (formElement) {
|
||||
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
|
||||
|
||||
if (!csrfField) {
|
||||
return;
|
||||
}
|
||||
|
||||
let csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
|
||||
let csrfToken = csrfField.value;
|
||||
|
||||
if (!csrfCookie && nameCheck.test(csrfToken)) {
|
||||
csrfField.setAttribute('data-csrf-protection-cookie-value', csrfCookie = csrfToken);
|
||||
csrfField.defaultValue = csrfToken = btoa(String.fromCharCode.apply(null, (window.crypto || window.msCrypto).getRandomValues(new Uint8Array(18))));
|
||||
}
|
||||
csrfField.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
|
||||
if (csrfCookie && tokenCheck.test(csrfToken)) {
|
||||
const cookie = csrfCookie + '_' + csrfToken + '=' + csrfCookie + '; path=/; samesite=strict';
|
||||
document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateCsrfHeaders (formElement) {
|
||||
const headers = {};
|
||||
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
|
||||
|
||||
if (!csrfField) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
const csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
|
||||
|
||||
if (tokenCheck.test(csrfField.value) && nameCheck.test(csrfCookie)) {
|
||||
headers[csrfCookie] = csrfField.value;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function removeCsrfToken (formElement) {
|
||||
const csrfField = formElement.querySelector('input[data-controller="csrf-protection"], input[name="_csrf_token"]');
|
||||
|
||||
if (!csrfField) {
|
||||
return;
|
||||
}
|
||||
|
||||
const csrfCookie = csrfField.getAttribute('data-csrf-protection-cookie-value');
|
||||
|
||||
if (tokenCheck.test(csrfField.value) && nameCheck.test(csrfCookie)) {
|
||||
const cookie = csrfCookie + '_' + csrfField.value + '=0; path=/; samesite=strict; max-age=0';
|
||||
|
||||
document.cookie = window.location.protocol === 'https:' ? '__Host-' + cookie + '; secure' : cookie;
|
||||
}
|
||||
}
|
||||
|
||||
/* stimulusFetch: 'lazy' */
|
||||
export default 'csrf-protection-controller';
|
||||
@@ -0,0 +1,129 @@
|
||||
const nameCheck = /^[-_a-zA-Z0-9]{4,22}$/;
|
||||
const tokenCheck = /^[-_/+a-zA-Z0-9]{24,}$/;
|
||||
|
||||
interface TurboSubmitEventDetail {
|
||||
formSubmission: {
|
||||
formElement: HTMLFormElement;
|
||||
fetchRequest: { headers: Record<string, string> };
|
||||
};
|
||||
}
|
||||
|
||||
const CSRF_FIELD_SELECTOR =
|
||||
'input[data-controller="csrf-protection"], input[name="_csrf_token"]';
|
||||
|
||||
// Generate and double-submit a CSRF token in a form field and a cookie, as defined by Symfony's SameOriginCsrfTokenManager
|
||||
// Use `form.requestSubmit()` to ensure that the submit event is triggered. Using `form.submit()` will not trigger the event
|
||||
// and thus this event-listener will not be executed.
|
||||
document.addEventListener('submit', function (event) {
|
||||
generateCsrfToken(event.target as HTMLFormElement);
|
||||
}, true);
|
||||
|
||||
// When @hotwired/turbo handles form submissions, send the CSRF token in a header in addition to a cookie
|
||||
// The `framework.csrf_protection.check_header` config option needs to be enabled for the header to be checked
|
||||
document.addEventListener('turbo:submit-start', function (event) {
|
||||
const detail = (event as CustomEvent<TurboSubmitEventDetail>).detail;
|
||||
const h = generateCsrfHeaders(detail.formSubmission.formElement);
|
||||
Object.keys(h).forEach(function (k) {
|
||||
detail.formSubmission.fetchRequest.headers[k] = h[k];
|
||||
});
|
||||
});
|
||||
|
||||
// When @hotwired/turbo handles form submissions, remove the CSRF cookie once a form has been submitted
|
||||
document.addEventListener('turbo:submit-end', function (event) {
|
||||
const detail = (event as CustomEvent<TurboSubmitEventDetail>).detail;
|
||||
removeCsrfToken(detail.formSubmission.formElement);
|
||||
});
|
||||
|
||||
export function generateCsrfToken(formElement: HTMLFormElement): void {
|
||||
const csrfField = formElement.querySelector<HTMLInputElement>(
|
||||
CSRF_FIELD_SELECTOR,
|
||||
);
|
||||
|
||||
if (!csrfField) {
|
||||
return;
|
||||
}
|
||||
|
||||
let csrfCookie = csrfField.getAttribute(
|
||||
'data-csrf-protection-cookie-value',
|
||||
);
|
||||
let csrfToken = csrfField.value;
|
||||
|
||||
if (!csrfCookie && nameCheck.test(csrfToken)) {
|
||||
csrfField.setAttribute(
|
||||
'data-csrf-protection-cookie-value',
|
||||
csrfCookie = csrfToken,
|
||||
);
|
||||
csrfField.defaultValue = csrfToken = btoa(
|
||||
String.fromCharCode.apply(
|
||||
null,
|
||||
Array.from(
|
||||
(window.crypto ||
|
||||
(window as unknown as { msCrypto: Crypto }).msCrypto)
|
||||
.getRandomValues(new Uint8Array(18)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
csrfField.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
|
||||
if (csrfCookie && tokenCheck.test(csrfToken)) {
|
||||
const cookie = csrfCookie + '_' + csrfToken + '=' + csrfCookie +
|
||||
'; path=/; samesite=strict';
|
||||
document.cookie = window.location.protocol === 'https:'
|
||||
? '__Host-' + cookie + '; secure'
|
||||
: cookie;
|
||||
}
|
||||
}
|
||||
|
||||
export function generateCsrfHeaders(
|
||||
formElement: HTMLFormElement,
|
||||
): Record<string, string> {
|
||||
const headers: Record<string, string> = {};
|
||||
const csrfField = formElement.querySelector<HTMLInputElement>(
|
||||
CSRF_FIELD_SELECTOR,
|
||||
);
|
||||
|
||||
if (!csrfField) {
|
||||
return headers;
|
||||
}
|
||||
|
||||
const csrfCookie = csrfField.getAttribute(
|
||||
'data-csrf-protection-cookie-value',
|
||||
);
|
||||
|
||||
if (
|
||||
tokenCheck.test(csrfField.value) && nameCheck.test(String(csrfCookie))
|
||||
) {
|
||||
headers[String(csrfCookie)] = csrfField.value;
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
export function removeCsrfToken(formElement: HTMLFormElement): void {
|
||||
const csrfField = formElement.querySelector<HTMLInputElement>(
|
||||
CSRF_FIELD_SELECTOR,
|
||||
);
|
||||
|
||||
if (!csrfField) {
|
||||
return;
|
||||
}
|
||||
|
||||
const csrfCookie = csrfField.getAttribute(
|
||||
'data-csrf-protection-cookie-value',
|
||||
);
|
||||
|
||||
if (
|
||||
tokenCheck.test(csrfField.value) && nameCheck.test(String(csrfCookie))
|
||||
) {
|
||||
const cookie = String(csrfCookie) + '_' + csrfField.value +
|
||||
'=0; path=/; samesite=strict; max-age=0';
|
||||
|
||||
document.cookie = window.location.protocol === 'https:'
|
||||
? '__Host-' + cookie + '; secure'
|
||||
: cookie;
|
||||
}
|
||||
}
|
||||
|
||||
/* stimulusFetch: 'lazy' */
|
||||
export default 'csrf-protection-controller';
|
||||
@@ -0,0 +1,119 @@
|
||||
import { assertEquals, assertMatch } from '@std/assert';
|
||||
|
||||
// The module under test registers `document.addEventListener(...)` calls at
|
||||
// import time and reads `window.location`/`window.crypto`, so a minimal
|
||||
// `document`/`window` stub must exist in the global scope *before* the module
|
||||
// is imported. Deno has no browser DOM, and the actual surface these
|
||||
// functions touch on a form/input is narrow (getAttribute/setAttribute/value/
|
||||
// dispatchEvent), so hand-built fakes are used instead of a full DOM polyfill.
|
||||
let cookieJar = '';
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(globalThis as any).document = {
|
||||
addEventListener: () => {},
|
||||
get cookie() {
|
||||
return cookieJar;
|
||||
},
|
||||
set cookie(value: string) {
|
||||
cookieJar += (cookieJar ? '; ' : '') + value;
|
||||
},
|
||||
};
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(globalThis as any).window = {
|
||||
location: { protocol: 'http:' },
|
||||
crypto: globalThis.crypto,
|
||||
};
|
||||
|
||||
const { generateCsrfHeaders, generateCsrfToken, removeCsrfToken } =
|
||||
await import(
|
||||
'./csrf_protection_controller.ts'
|
||||
);
|
||||
|
||||
function fakeField(attributes: Record<string, string> = {}, value = '') {
|
||||
const store = new Map(Object.entries(attributes));
|
||||
return {
|
||||
getAttribute: (name: string) => store.get(name) ?? null,
|
||||
setAttribute: (name: string, val: string) => {
|
||||
store.set(name, val);
|
||||
},
|
||||
value,
|
||||
defaultValue: value,
|
||||
dispatchEvent: () => true,
|
||||
};
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function fakeForm(field: ReturnType<typeof fakeField> | null): any {
|
||||
return { querySelector: () => field };
|
||||
}
|
||||
|
||||
Deno.test('generateCsrfToken does nothing when the form has no csrf field', () => {
|
||||
cookieJar = '';
|
||||
generateCsrfToken(fakeForm(null));
|
||||
assertEquals(cookieJar, '');
|
||||
});
|
||||
|
||||
Deno.test('generateCsrfToken generates a token and cookie on first use', () => {
|
||||
cookieJar = '';
|
||||
const field = fakeField({}, 'my_field_name');
|
||||
|
||||
generateCsrfToken(fakeForm(field));
|
||||
|
||||
assertEquals(
|
||||
field.getAttribute('data-csrf-protection-cookie-value'),
|
||||
'my_field_name',
|
||||
);
|
||||
assertMatch(field.defaultValue, /^[-_/+a-zA-Z0-9]{24,}$/);
|
||||
assertMatch(cookieJar, /my_field_name_[-_/+a-zA-Z0-9]{24,}=my_field_name/);
|
||||
});
|
||||
|
||||
Deno.test('generateCsrfToken keeps an existing valid token/cookie pair unchanged', () => {
|
||||
cookieJar = '';
|
||||
const token = 'a'.repeat(24);
|
||||
const field = fakeField({
|
||||
'data-csrf-protection-cookie-value': 'existing_name',
|
||||
}, token);
|
||||
|
||||
generateCsrfToken(fakeForm(field));
|
||||
|
||||
assertEquals(field.value, token);
|
||||
assertMatch(cookieJar, new RegExp(`existing_name_${token}=existing_name`));
|
||||
});
|
||||
|
||||
Deno.test('generateCsrfHeaders returns empty headers without a csrf field', () => {
|
||||
assertEquals(generateCsrfHeaders(fakeForm(null)), {});
|
||||
});
|
||||
|
||||
Deno.test('generateCsrfHeaders returns the cookie-name/token header when both are valid', () => {
|
||||
const token = 'b'.repeat(24);
|
||||
const field = fakeField({
|
||||
'data-csrf-protection-cookie-value': 'field_name',
|
||||
}, token);
|
||||
|
||||
assertEquals(generateCsrfHeaders(fakeForm(field)), { field_name: token });
|
||||
});
|
||||
|
||||
Deno.test('generateCsrfHeaders omits the header when the token is too short', () => {
|
||||
const field = fakeField({
|
||||
'data-csrf-protection-cookie-value': 'field_name',
|
||||
}, 'too-short');
|
||||
|
||||
assertEquals(generateCsrfHeaders(fakeForm(field)), {});
|
||||
});
|
||||
|
||||
Deno.test('removeCsrfToken expires the cookie for a valid token/cookie pair', () => {
|
||||
cookieJar = '';
|
||||
const token = 'c'.repeat(24);
|
||||
const field = fakeField({
|
||||
'data-csrf-protection-cookie-value': 'field_name',
|
||||
}, token);
|
||||
|
||||
removeCsrfToken(fakeForm(field));
|
||||
|
||||
assertMatch(cookieJar, new RegExp(`field_name_${token}=0`));
|
||||
});
|
||||
|
||||
Deno.test('removeCsrfToken does nothing without a csrf field', () => {
|
||||
cookieJar = '';
|
||||
removeCsrfToken(fakeForm(null));
|
||||
assertEquals(cookieJar, '');
|
||||
});
|
||||
@@ -1,14 +0,0 @@
|
||||
import {Controller} from '@hotwired/stimulus';
|
||||
|
||||
export default class extends Controller {
|
||||
next() {
|
||||
const currentUrl = new URL(window.location.href);
|
||||
const pathParts = currentUrl.pathname.split('/');
|
||||
// Remove the last segment
|
||||
pathParts.pop();
|
||||
// Update the pathname
|
||||
currentUrl.pathname = pathParts.join('/');
|
||||
// Navigate
|
||||
window.location.href = currentUrl.href;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
|
||||
export default class extends Controller {
|
||||
next(): void {
|
||||
const currentUrl = new URL(window.location.href);
|
||||
const pathParts = currentUrl.pathname.split('/');
|
||||
// Remove the last segment
|
||||
pathParts.pop();
|
||||
// Update the pathname
|
||||
currentUrl.pathname = pathParts.join('/');
|
||||
// Navigate
|
||||
window.location.href = currentUrl.href;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
|
||||
const STORAGE_KEY = 'tvdt-fullscreen';
|
||||
|
||||
export default class extends Controller {
|
||||
connect(): void {
|
||||
document.addEventListener('fullscreenchange', this.onFullscreenChange);
|
||||
this.syncState();
|
||||
|
||||
if (
|
||||
sessionStorage.getItem(STORAGE_KEY) === '1' &&
|
||||
!document.fullscreenElement
|
||||
) {
|
||||
this.request();
|
||||
}
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
document.removeEventListener(
|
||||
'fullscreenchange',
|
||||
this.onFullscreenChange,
|
||||
);
|
||||
}
|
||||
|
||||
toggle(): void {
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen();
|
||||
} else {
|
||||
this.request();
|
||||
}
|
||||
}
|
||||
|
||||
request(): void {
|
||||
document.documentElement.requestFullscreen().catch(() => {});
|
||||
}
|
||||
|
||||
onFullscreenChange = (): void => {
|
||||
sessionStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
document.fullscreenElement ? '1' : '0',
|
||||
);
|
||||
this.syncState();
|
||||
};
|
||||
|
||||
syncState(): void {
|
||||
document.documentElement.classList.toggle(
|
||||
'is-fullscreen',
|
||||
Boolean(document.fullscreenElement),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { assertEquals } from '@std/assert';
|
||||
|
||||
// Stimulus's Controller base class constructor only does `this.context = context`
|
||||
// (see @hotwired/stimulus dist/stimulus.js), and none of this controller's methods
|
||||
// touch Stimulus-specific getters (element/scope/targets), so a plain `{}` context
|
||||
// is enough to construct a real instance. `document`/`sessionStorage` are stubbed
|
||||
// since Deno has no browser DOM.
|
||||
class FakeClassList {
|
||||
classes = new Set<string>();
|
||||
toggle(name: string, force?: boolean) {
|
||||
const shouldAdd = force ?? !this.classes.has(name);
|
||||
if (shouldAdd) this.classes.add(name);
|
||||
else this.classes.delete(name);
|
||||
}
|
||||
contains(name: string) {
|
||||
return this.classes.has(name);
|
||||
}
|
||||
}
|
||||
|
||||
const classList = new FakeClassList();
|
||||
let fullscreenElement: unknown = null;
|
||||
const sessionStore = new Map<string, string>();
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(globalThis as any).document = {
|
||||
documentElement: { classList },
|
||||
get fullscreenElement() {
|
||||
return fullscreenElement;
|
||||
},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
};
|
||||
// Deno defines a native `sessionStorage` accessor on globalThis (get/set pair), so a
|
||||
// plain assignment would just call through to it instead of replacing it — redefine
|
||||
// the property outright.
|
||||
Object.defineProperty(globalThis, 'sessionStorage', {
|
||||
value: {
|
||||
getItem: (key: string) => sessionStore.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => sessionStore.set(key, value),
|
||||
},
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
const { default: FullscreenController } = await import(
|
||||
'./fullscreen_controller.ts'
|
||||
);
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function makeController(): any {
|
||||
return new FullscreenController({} as never);
|
||||
}
|
||||
|
||||
Deno.test('syncState adds is-fullscreen when a fullscreen element is set', () => {
|
||||
fullscreenElement = { tagName: 'HTML' };
|
||||
makeController().syncState();
|
||||
assertEquals(classList.contains('is-fullscreen'), true);
|
||||
});
|
||||
|
||||
Deno.test('syncState removes is-fullscreen when there is no fullscreen element', () => {
|
||||
fullscreenElement = null;
|
||||
makeController().syncState();
|
||||
assertEquals(classList.contains('is-fullscreen'), false);
|
||||
});
|
||||
|
||||
Deno.test('onFullscreenChange persists the fullscreen state and syncs classes', () => {
|
||||
fullscreenElement = { tagName: 'HTML' };
|
||||
makeController().onFullscreenChange();
|
||||
assertEquals(sessionStore.get('tvdt-fullscreen'), '1');
|
||||
assertEquals(classList.contains('is-fullscreen'), true);
|
||||
|
||||
fullscreenElement = null;
|
||||
makeController().onFullscreenChange();
|
||||
assertEquals(sessionStore.get('tvdt-fullscreen'), '0');
|
||||
assertEquals(classList.contains('is-fullscreen'), false);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'bootstrap/dist/css/bootstrap.min.css';
|
||||
import './styles/quiz.scss';
|
||||
import './stimulus.js';
|
||||
import './bootstrap.js';
|
||||
import './stimulus.ts';
|
||||
import './bootstrap.ts';
|
||||
@@ -1,3 +1,3 @@
|
||||
import { startStimulusApp } from '@symfony/stimulus-bundle';
|
||||
|
||||
const app = startStimulusApp();
|
||||
startStimulusApp();
|
||||
@@ -1,3 +1,5 @@
|
||||
.col-result-xs { width: 10%; }
|
||||
.col-result-sm { width: 15%; }
|
||||
.col-result-md { width: 20%; }
|
||||
|
||||
.modal-content > turbo-frame { display: contents; }
|
||||
|
||||
@@ -94,6 +94,32 @@ input.btn-check:checked + label.answer-btn {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.fullscreen-btn {
|
||||
position: fixed;
|
||||
bottom: 0.75rem;
|
||||
left: 0.75rem;
|
||||
z-index: 1040;
|
||||
width: 2.25rem;
|
||||
height: 2.25rem;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: rgba(255, 255, 255, 0.35);
|
||||
font-size: 1.25rem;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover,
|
||||
&:focus {
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
html.is-fullscreen .fullscreen-btn {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.elimination-screen {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
// Ambient declarations for the parts of the AssetMapper toolchain that Deno's
|
||||
// module resolution doesn't otherwise understand: CSS/SCSS side-effect imports
|
||||
// (handled by AssetMapper at build time, not a JS module) and the Symfony
|
||||
// stimulus-bundle loader (a local vendor/ file, not an npm package).
|
||||
|
||||
declare module '*.css';
|
||||
declare module '*.scss';
|
||||
|
||||
declare module '@symfony/stimulus-bundle' {
|
||||
export function startStimulusApp(): unknown;
|
||||
}
|
||||
+10
-5
@@ -24,15 +24,15 @@ services:
|
||||
ports:
|
||||
# HTTP
|
||||
- target: 80
|
||||
published: ${HTTP_PORT:-80}
|
||||
published: ${HTTP_PORT:-8080}
|
||||
protocol: tcp
|
||||
# HTTPS
|
||||
- target: 443
|
||||
published: ${HTTPS_PORT:-443}
|
||||
published: ${HTTPS_PORT:-8443}
|
||||
protocol: tcp
|
||||
# HTTP/3
|
||||
- target: 443
|
||||
published: ${HTTP3_PORT:-443}
|
||||
published: ${HTTPS_PORT:-8443}
|
||||
protocol: udp
|
||||
sass:
|
||||
image: ${IMAGES_PREFIX:-}app-php
|
||||
@@ -56,7 +56,7 @@ services:
|
||||
###> doctrine/doctrine-bundle ###
|
||||
database:
|
||||
ports:
|
||||
- "5432:5432"
|
||||
- "${POSTGRES_PORT:-5430}:5432"
|
||||
###< doctrine/doctrine-bundle ###
|
||||
|
||||
###> symfony/mailer ###
|
||||
@@ -64,11 +64,16 @@ services:
|
||||
image: axllent/mailpit
|
||||
ports:
|
||||
- "1025"
|
||||
- "8025:8025"
|
||||
- "${MAILPIT_PORT:-8025}:8025"
|
||||
environment:
|
||||
MP_SMTP_AUTH_ACCEPT_ANY: 1
|
||||
MP_SMTP_AUTH_ALLOW_INSECURE: 1
|
||||
###< symfony/mailer ###
|
||||
|
||||
spotlight:
|
||||
image: ghcr.io/getsentry/spotlight:latest
|
||||
ports:
|
||||
- "${SPOTLIGHT_PORT:-8969}:8969"
|
||||
|
||||
volumes:
|
||||
sass:
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
"phpdocumentor/reflection-docblock": "^6.0.3",
|
||||
"phpoffice/phpspreadsheet": "^5.5",
|
||||
"phpstan/phpdoc-parser": "^2.3.2",
|
||||
"sensiolabs/typescript-bundle": "^0.2.2",
|
||||
"sentry/sentry-symfony": "^5.9.0",
|
||||
"stof/doctrine-extensions-bundle": "^1.15.3",
|
||||
"symfony/asset": "8.1.*",
|
||||
@@ -28,18 +29,21 @@
|
||||
"symfony/form": "8.1.*",
|
||||
"symfony/framework-bundle": "8.1.*",
|
||||
"symfony/mailer": "8.1.*",
|
||||
"symfony/object-mapper": "8.1.*",
|
||||
"symfony/property-access": "8.1.*",
|
||||
"symfony/property-info": "8.1.*",
|
||||
"symfony/runtime": "8.1.*",
|
||||
"symfony/security-bundle": "8.1.*",
|
||||
"symfony/security-csrf": "8.1.*",
|
||||
"symfony/serializer": "8.1.*",
|
||||
"symfony/string": "8.1.*",
|
||||
"symfony/translation": "8.1.*",
|
||||
"symfony/twig-bundle": "8.1.*",
|
||||
"symfony/uid": "8.1.*",
|
||||
"symfony/ux-turbo": "^3.1",
|
||||
"symfony/validator": "8.1.*",
|
||||
"symfony/yaml": "8.1.*",
|
||||
"symfonycasts/reset-password-bundle": "^1.25",
|
||||
"symfonycasts/sass-bundle": "^0.10",
|
||||
"symfonycasts/verify-email-bundle": "^1.18.0",
|
||||
"thecodingmachine/safe": "^3.4.0",
|
||||
|
||||
Generated
+243
-67
@@ -4,7 +4,7 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "f8e4107825dba89eaa38d067d47856ce",
|
||||
"content-hash": "cca03585c291226d36bbeabf57a08bec",
|
||||
"packages": [
|
||||
{
|
||||
"name": "composer/pcre",
|
||||
@@ -1475,16 +1475,16 @@
|
||||
},
|
||||
{
|
||||
"name": "guzzlehttp/psr7",
|
||||
"version": "2.12.3",
|
||||
"version": "2.12.4",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/guzzle/psr7.git",
|
||||
"reference": "7ec62dc3f44aa218487dbed81a9bf9bc647be55d"
|
||||
"reference": "51e27f9e2b332ab3e72f4520d5ff4f3c68c3577c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/guzzle/psr7/zipball/7ec62dc3f44aa218487dbed81a9bf9bc647be55d",
|
||||
"reference": "7ec62dc3f44aa218487dbed81a9bf9bc647be55d",
|
||||
"url": "https://api.github.com/repos/guzzle/psr7/zipball/51e27f9e2b332ab3e72f4520d5ff4f3c68c3577c",
|
||||
"reference": "51e27f9e2b332ab3e72f4520d5ff4f3c68c3577c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -1574,7 +1574,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/guzzle/psr7/issues",
|
||||
"source": "https://github.com/guzzle/psr7/tree/2.12.3"
|
||||
"source": "https://github.com/guzzle/psr7/tree/2.12.4"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -1590,7 +1590,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-23T15:21:08+00:00"
|
||||
"time": "2026-07-08T15:56:20+00:00"
|
||||
},
|
||||
{
|
||||
"name": "jean85/pretty-package-versions",
|
||||
@@ -2253,16 +2253,16 @@
|
||||
},
|
||||
{
|
||||
"name": "phpstan/phpdoc-parser",
|
||||
"version": "2.3.2",
|
||||
"version": "2.3.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/phpstan/phpdoc-parser.git",
|
||||
"reference": "a004701b11273a26cd7955a61d67a7f1e525a45a"
|
||||
"reference": "fb19eedd2bb67ff8cf7a5502ad329e701d6398a3"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/a004701b11273a26cd7955a61d67a7f1e525a45a",
|
||||
"reference": "a004701b11273a26cd7955a61d67a7f1e525a45a",
|
||||
"url": "https://api.github.com/repos/phpstan/phpdoc-parser/zipball/fb19eedd2bb67ff8cf7a5502ad329e701d6398a3",
|
||||
"reference": "fb19eedd2bb67ff8cf7a5502ad329e701d6398a3",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -2294,9 +2294,9 @@
|
||||
"description": "PHPDoc parser with support for nullable, intersection and generic types",
|
||||
"support": {
|
||||
"issues": "https://github.com/phpstan/phpdoc-parser/issues",
|
||||
"source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.2"
|
||||
"source": "https://github.com/phpstan/phpdoc-parser/tree/2.3.3"
|
||||
},
|
||||
"time": "2026-01-25T14:56:51+00:00"
|
||||
"time": "2026-07-08T07:01:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "psr/cache",
|
||||
@@ -2751,6 +2751,62 @@
|
||||
},
|
||||
"time": "2019-03-08T08:55:37+00:00"
|
||||
},
|
||||
{
|
||||
"name": "sensiolabs/typescript-bundle",
|
||||
"version": "v0.2.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sensiolabs/AssetMapperTypeScriptBundle.git",
|
||||
"reference": "b4a498a2b1dd699fd4ea95ae9dfa30ebe77cc8ce"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sensiolabs/AssetMapperTypeScriptBundle/zipball/b4a498a2b1dd699fd4ea95ae9dfa30ebe77cc8ce",
|
||||
"reference": "b4a498a2b1dd699fd4ea95ae9dfa30ebe77cc8ce",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.1",
|
||||
"symfony/asset-mapper": "^6.3|^7.0|^8.0",
|
||||
"symfony/console": "^6.3|^7.0|^8.0",
|
||||
"symfony/http-client": "^6.3|^7.0|^8.0",
|
||||
"symfony/process": "^6.3|^7.0|^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpstan/phpstan": "^1",
|
||||
"phpstan/phpstan-symfony": "^1.3",
|
||||
"phpunit/phpunit": "^10.5",
|
||||
"symfony/filesystem": "^6.3|^7.0|^8.0",
|
||||
"symfony/framework-bundle": "^6.3|^7.0|^8.0"
|
||||
},
|
||||
"type": "symfony-bundle",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Sensiolabs\\TypeScriptBundle\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Maelan LE BORGNE",
|
||||
"homepage": "https://github.com/maelanleborgne"
|
||||
}
|
||||
],
|
||||
"description": "TypeScript support for Symfony + AssetMapper",
|
||||
"homepage": "https://github.com/sensiolabs/AssetMapperTypeScriptBundle",
|
||||
"keywords": [
|
||||
"asset-mapper",
|
||||
"typescript"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/sensiolabs/AssetMapperTypeScriptBundle/issues",
|
||||
"source": "https://github.com/sensiolabs/AssetMapperTypeScriptBundle/tree/v0.2.2"
|
||||
},
|
||||
"time": "2025-08-28T10:10:44+00:00"
|
||||
},
|
||||
{
|
||||
"name": "sentry/sentry",
|
||||
"version": "4.29.0",
|
||||
@@ -5337,6 +5393,79 @@
|
||||
],
|
||||
"time": "2026-05-29T05:06:50+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/object-mapper",
|
||||
"version": "v8.1.1",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/symfony/object-mapper.git",
|
||||
"reference": "f2d118d3ced275117b83acc5b57f6611ab38cd14"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/symfony/object-mapper/zipball/f2d118d3ced275117b83acc5b57f6611ab38cd14",
|
||||
"reference": "f2d118d3ced275117b83acc5b57f6611ab38cd14",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.4.1",
|
||||
"psr/container": "^2.0"
|
||||
},
|
||||
"conflict": {
|
||||
"symfony/property-access": "<7.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"symfony/property-access": "^7.4|^8.0",
|
||||
"symfony/var-exporter": "^7.4|^8.0"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Symfony\\Component\\ObjectMapper\\": ""
|
||||
},
|
||||
"exclude-from-classmap": [
|
||||
"/Tests/"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Fabien Potencier",
|
||||
"email": "fabien@symfony.com"
|
||||
},
|
||||
{
|
||||
"name": "Symfony Community",
|
||||
"homepage": "https://symfony.com/contributors"
|
||||
}
|
||||
],
|
||||
"description": "Provides a way to map an object to another object",
|
||||
"homepage": "https://symfony.com",
|
||||
"support": {
|
||||
"source": "https://github.com/symfony/object-mapper/tree/v8.1.1"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://symfony.com/sponsor",
|
||||
"type": "custom"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/fabpot",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://github.com/nicolas-grekas",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-17T10:12:54+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfony/options-resolver",
|
||||
"version": "v8.1.0",
|
||||
@@ -8208,6 +8337,54 @@
|
||||
],
|
||||
"time": "2026-06-09T11:06:24+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfonycasts/reset-password-bundle",
|
||||
"version": "v1.25.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SymfonyCasts/reset-password-bundle.git",
|
||||
"reference": "084aac1cc40ef75b26134c7967d1e423eeff72f4"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/SymfonyCasts/reset-password-bundle/zipball/084aac1cc40ef75b26134c7967d1e423eeff72f4",
|
||||
"reference": "084aac1cc40ef75b26134c7967d1e423eeff72f4",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": ">=8.1.10",
|
||||
"symfony/clock": "^6.3 | ^7.0 | ^8.0",
|
||||
"symfony/config": "^5.4 | ^6.0 | ^7.0 | ^8.0",
|
||||
"symfony/dependency-injection": "^5.4 | ^6.0 | ^7.0 | ^8.0",
|
||||
"symfony/deprecation-contracts": "^2.2 | ^3.0",
|
||||
"symfony/http-kernel": "^5.4 | ^6.0 | ^7.0 | ^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"doctrine/annotations": "^1.0 | ^2.0",
|
||||
"doctrine/doctrine-bundle": "^2.13 | ^3.0",
|
||||
"doctrine/orm": "^2.20 | ^3.0",
|
||||
"symfony/framework-bundle": "^5.4 | ^6.0 | ^7.0 | ^8.0",
|
||||
"symfony/phpunit-bridge": "^5.4 | ^6.0 | ^7.0 | ^8.0",
|
||||
"symfony/process": "^6.4 | ^7.0 | ^8.0",
|
||||
"symfonycasts/internal-test-helpers": "dev-main"
|
||||
},
|
||||
"type": "symfony-bundle",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"SymfonyCasts\\Bundle\\ResetPassword\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"description": "Symfony bundle that adds password reset functionality.",
|
||||
"support": {
|
||||
"issues": "https://github.com/SymfonyCasts/reset-password-bundle/issues",
|
||||
"source": "https://github.com/SymfonyCasts/reset-password-bundle/tree/v1.25.0"
|
||||
},
|
||||
"time": "2026-03-26T10:16:40+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfonycasts/sass-bundle",
|
||||
"version": "v0.10.0",
|
||||
@@ -9287,16 +9464,16 @@
|
||||
},
|
||||
{
|
||||
"name": "friendsofphp/php-cs-fixer",
|
||||
"version": "v3.95.11",
|
||||
"version": "v3.95.13",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer.git",
|
||||
"reference": "35f98e1293283397824d7f349ce5afb8747c3cd5"
|
||||
"reference": "ea941114a002eb5e5876f190223deec1066c482c"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/35f98e1293283397824d7f349ce5afb8747c3cd5",
|
||||
"reference": "35f98e1293283397824d7f349ce5afb8747c3cd5",
|
||||
"url": "https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/zipball/ea941114a002eb5e5876f190223deec1066c482c",
|
||||
"reference": "ea941114a002eb5e5876f190223deec1066c482c",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -9336,7 +9513,7 @@
|
||||
"php-coveralls/php-coveralls": "^2.9.1",
|
||||
"php-cs-fixer/phpunit-constraint-isidenticalstring": "^1.8",
|
||||
"php-cs-fixer/phpunit-constraint-xmlmatchesxsd": "^1.8",
|
||||
"phpunit/phpunit": "^9.6.34 || ^10.5.63 || ^11.5.55",
|
||||
"phpunit/phpunit": "^9.6.35 || ^10.5.64 || ^11.5.56",
|
||||
"symfony/polyfill-php85": "^1.38",
|
||||
"symfony/var-dumper": "^5.4.48 || ^6.4.36 || ^7.4.8 || ^8.1.0",
|
||||
"symfony/yaml": "^5.4.53 || ^6.4.41 || ^7.4.13 || ^8.1.0"
|
||||
@@ -9380,7 +9557,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues",
|
||||
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.11"
|
||||
"source": "https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/tree/v3.95.13"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -9388,7 +9565,7 @@
|
||||
"type": "github"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-25T14:17:04+00:00"
|
||||
"time": "2026-07-10T09:23:21+00:00"
|
||||
},
|
||||
{
|
||||
"name": "myclabs/deep-copy",
|
||||
@@ -9452,20 +9629,19 @@
|
||||
},
|
||||
{
|
||||
"name": "nikic/php-parser",
|
||||
"version": "v5.7.0",
|
||||
"version": "v5.8.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/nikic/PHP-Parser.git",
|
||||
"reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82"
|
||||
"reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/dca41cd15c2ac9d055ad70dbfd011130757d1f82",
|
||||
"reference": "dca41cd15c2ac9d055ad70dbfd011130757d1f82",
|
||||
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/044a6a392ff8ad0d61f14370a5fbbd0a0107152f",
|
||||
"reference": "044a6a392ff8ad0d61f14370a5fbbd0a0107152f",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-ctype": "*",
|
||||
"ext-json": "*",
|
||||
"ext-tokenizer": "*",
|
||||
"php": ">=7.4"
|
||||
@@ -9504,9 +9680,9 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/nikic/PHP-Parser/issues",
|
||||
"source": "https://github.com/nikic/PHP-Parser/tree/v5.7.0"
|
||||
"source": "https://github.com/nikic/PHP-Parser/tree/v5.8.0"
|
||||
},
|
||||
"time": "2025-12-06T11:56:16+00:00"
|
||||
"time": "2026-07-04T14:30:18+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phar-io/manifest",
|
||||
@@ -9676,11 +9852,11 @@
|
||||
},
|
||||
{
|
||||
"name": "phpstan/phpstan",
|
||||
"version": "2.2.4",
|
||||
"version": "2.2.5",
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/f0fe3fb03bb53ce68cc2416785b260e62226ec27",
|
||||
"reference": "f0fe3fb03bb53ce68cc2416785b260e62226ec27",
|
||||
"url": "https://api.github.com/repos/phpstan/phpstan/zipball/909c1e5fef7989ac0d0c1c5c42e32a5c4f6198a0",
|
||||
"reference": "909c1e5fef7989ac0d0c1c5c42e32a5c4f6198a0",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -9736,7 +9912,7 @@
|
||||
"type": "github"
|
||||
}
|
||||
],
|
||||
"time": "2026-07-03T07:00:23+00:00"
|
||||
"time": "2026-07-05T06:31:06+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phpstan/phpstan-doctrine",
|
||||
@@ -9817,16 +9993,16 @@
|
||||
},
|
||||
{
|
||||
"name": "phpstan/phpstan-phpunit",
|
||||
"version": "2.0.17",
|
||||
"version": "2.0.18",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/phpstan/phpstan-phpunit.git",
|
||||
"reference": "c2f977551f0736d60467b3d754b2e0cf4e337b3f"
|
||||
"reference": "f5dc20ff8082d02339b60cab68ec3eb0d859fb30"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/phpstan/phpstan-phpunit/zipball/c2f977551f0736d60467b3d754b2e0cf4e337b3f",
|
||||
"reference": "c2f977551f0736d60467b3d754b2e0cf4e337b3f",
|
||||
"url": "https://api.github.com/repos/phpstan/phpstan-phpunit/zipball/f5dc20ff8082d02339b60cab68ec3eb0d859fb30",
|
||||
"reference": "f5dc20ff8082d02339b60cab68ec3eb0d859fb30",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -9869,9 +10045,9 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/phpstan/phpstan-phpunit/issues",
|
||||
"source": "https://github.com/phpstan/phpstan-phpunit/tree/2.0.17"
|
||||
"source": "https://github.com/phpstan/phpstan-phpunit/tree/2.0.18"
|
||||
},
|
||||
"time": "2026-06-29T05:32:23+00:00"
|
||||
"time": "2026-07-04T12:16:09+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phpstan/phpstan-symfony",
|
||||
@@ -9949,16 +10125,16 @@
|
||||
},
|
||||
{
|
||||
"name": "phpunit/php-code-coverage",
|
||||
"version": "14.2.2",
|
||||
"version": "14.2.3",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
|
||||
"reference": "10d7da3628a99289cdf4c662dd7f0d73f1baec83"
|
||||
"reference": "82f6e49ff224e2cde923d74425e583a883910783"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/10d7da3628a99289cdf4c662dd7f0d73f1baec83",
|
||||
"reference": "10d7da3628a99289cdf4c662dd7f0d73f1baec83",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/82f6e49ff224e2cde923d74425e583a883910783",
|
||||
"reference": "82f6e49ff224e2cde923d74425e583a883910783",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -9966,7 +10142,7 @@
|
||||
"ext-libxml": "*",
|
||||
"ext-mbstring": "*",
|
||||
"ext-xmlwriter": "*",
|
||||
"nikic/php-parser": "^5.7.0",
|
||||
"nikic/php-parser": "^5.8.0",
|
||||
"php": ">=8.4",
|
||||
"phpunit/php-text-template": "^6.0",
|
||||
"sebastian/complexity": "^6.0",
|
||||
@@ -9977,7 +10153,7 @@
|
||||
"theseer/tokenizer": "^2.0.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^13.2.0"
|
||||
"phpunit/phpunit": "^13.2.2"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-pcov": "PHP extension that provides line coverage",
|
||||
@@ -10015,7 +10191,7 @@
|
||||
"support": {
|
||||
"issues": "https://github.com/sebastianbergmann/php-code-coverage/issues",
|
||||
"security": "https://github.com/sebastianbergmann/php-code-coverage/security/policy",
|
||||
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.2.2"
|
||||
"source": "https://github.com/sebastianbergmann/php-code-coverage/tree/14.2.3"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -10035,7 +10211,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-08T11:50:38+00:00"
|
||||
"time": "2026-07-06T15:04:02+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phpunit/php-file-iterator",
|
||||
@@ -10332,30 +10508,30 @@
|
||||
},
|
||||
{
|
||||
"name": "phpunit/phpunit",
|
||||
"version": "13.2.2",
|
||||
"version": "13.2.4",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/phpunit.git",
|
||||
"reference": "492c067e618de7b3c76105082c90f9d2833401b7"
|
||||
"reference": "8f5180f4627fc1978be2f61d8d9979dbe37e0c10"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/492c067e618de7b3c76105082c90f9d2833401b7",
|
||||
"reference": "492c067e618de7b3c76105082c90f9d2833401b7",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/8f5180f4627fc1978be2f61d8d9979dbe37e0c10",
|
||||
"reference": "8f5180f4627fc1978be2f61d8d9979dbe37e0c10",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-dom": "*",
|
||||
"ext-filter": "*",
|
||||
"ext-json": "*",
|
||||
"ext-libxml": "*",
|
||||
"ext-mbstring": "*",
|
||||
"ext-xml": "*",
|
||||
"ext-xmlwriter": "*",
|
||||
"myclabs/deep-copy": "^1.13.4",
|
||||
"phar-io/manifest": "^2.0.4",
|
||||
"phar-io/version": "^3.2.1",
|
||||
"php": ">=8.4.1",
|
||||
"phpunit/php-code-coverage": "^14.2.2",
|
||||
"phpunit/php-code-coverage": "^14.2.3",
|
||||
"phpunit/php-file-iterator": "^7.0.0",
|
||||
"phpunit/php-invoker": "^7.0.0",
|
||||
"phpunit/php-text-template": "^6.0.0",
|
||||
@@ -10412,7 +10588,7 @@
|
||||
"support": {
|
||||
"issues": "https://github.com/sebastianbergmann/phpunit/issues",
|
||||
"security": "https://github.com/sebastianbergmann/phpunit/security/policy",
|
||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/13.2.2"
|
||||
"source": "https://github.com/sebastianbergmann/phpunit/tree/13.2.4"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -10420,7 +10596,7 @@
|
||||
"type": "other"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-29T13:36:29+00:00"
|
||||
"time": "2026-07-08T08:36:51+00:00"
|
||||
},
|
||||
{
|
||||
"name": "react/cache",
|
||||
@@ -10950,16 +11126,16 @@
|
||||
},
|
||||
{
|
||||
"name": "rector/rector",
|
||||
"version": "2.5.2",
|
||||
"version": "2.5.5",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/rectorphp/rector.git",
|
||||
"reference": "49ff6339174bdbdf50b0b35ecbcff14a05ac9e24"
|
||||
"reference": "9718a72e7f1aacacbdcb6eeed07a47147bce802e"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/rectorphp/rector/zipball/49ff6339174bdbdf50b0b35ecbcff14a05ac9e24",
|
||||
"reference": "49ff6339174bdbdf50b0b35ecbcff14a05ac9e24",
|
||||
"url": "https://api.github.com/repos/rectorphp/rector/zipball/9718a72e7f1aacacbdcb6eeed07a47147bce802e",
|
||||
"reference": "9718a72e7f1aacacbdcb6eeed07a47147bce802e",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
@@ -10998,7 +11174,7 @@
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/rectorphp/rector/issues",
|
||||
"source": "https://github.com/rectorphp/rector/tree/2.5.2"
|
||||
"source": "https://github.com/rectorphp/rector/tree/2.5.5"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -11006,7 +11182,7 @@
|
||||
"type": "github"
|
||||
}
|
||||
],
|
||||
"time": "2026-06-22T11:39:33+00:00"
|
||||
"time": "2026-07-09T09:48:44+00:00"
|
||||
},
|
||||
{
|
||||
"name": "sebastian/cli-parser",
|
||||
@@ -11698,24 +11874,24 @@
|
||||
},
|
||||
{
|
||||
"name": "sebastian/lines-of-code",
|
||||
"version": "5.0.1",
|
||||
"version": "5.0.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sebastianbergmann/lines-of-code.git",
|
||||
"reference": "d2cff273a90c79b0eb590baa682d4b5c318bdbb7"
|
||||
"reference": "d1b6f8fce682505dbd048977f1abedf1b8ad3ff8"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d2cff273a90c79b0eb590baa682d4b5c318bdbb7",
|
||||
"reference": "d2cff273a90c79b0eb590baa682d4b5c318bdbb7",
|
||||
"url": "https://api.github.com/repos/sebastianbergmann/lines-of-code/zipball/d1b6f8fce682505dbd048977f1abedf1b8ad3ff8",
|
||||
"reference": "d1b6f8fce682505dbd048977f1abedf1b8ad3ff8",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"nikic/php-parser": "^5.7.0",
|
||||
"nikic/php-parser": "^5.8.0",
|
||||
"php": ">=8.4"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^13.1.10"
|
||||
"phpunit/phpunit": "^13.2.4"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
@@ -11744,7 +11920,7 @@
|
||||
"support": {
|
||||
"issues": "https://github.com/sebastianbergmann/lines-of-code/issues",
|
||||
"security": "https://github.com/sebastianbergmann/lines-of-code/security/policy",
|
||||
"source": "https://github.com/sebastianbergmann/lines-of-code/tree/5.0.1"
|
||||
"source": "https://github.com/sebastianbergmann/lines-of-code/tree/5.0.2"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
@@ -11764,7 +11940,7 @@
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2026-05-19T16:23:37+00:00"
|
||||
"time": "2026-07-09T08:42:34+00:00"
|
||||
},
|
||||
{
|
||||
"name": "sebastian/object-enumerator",
|
||||
|
||||
+5
-1
@@ -6,6 +6,7 @@ use DAMA\DoctrineTestBundle\DAMADoctrineTestBundle;
|
||||
use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
|
||||
use Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle;
|
||||
use Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle;
|
||||
use Sensiolabs\TypeScriptBundle\SensiolabsTypeScriptBundle;
|
||||
use Sentry\SentryBundle\SentryBundle;
|
||||
use Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle;
|
||||
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
|
||||
@@ -15,6 +16,7 @@ use Symfony\Bundle\TwigBundle\TwigBundle;
|
||||
use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle;
|
||||
use Symfony\UX\StimulusBundle\StimulusBundle;
|
||||
use Symfony\UX\Turbo\TurboBundle;
|
||||
use SymfonyCasts\Bundle\ResetPassword\SymfonyCastsResetPasswordBundle;
|
||||
use SymfonyCasts\Bundle\VerifyEmail\SymfonyCastsVerifyEmailBundle;
|
||||
use Symfonycasts\SassBundle\SymfonycastsSassBundle;
|
||||
use Twig\Extra\TwigExtraBundle\TwigExtraBundle;
|
||||
@@ -30,10 +32,12 @@ return [
|
||||
TwigExtraBundle::class => ['all' => true],
|
||||
DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
|
||||
SymfonyCastsVerifyEmailBundle::class => ['all' => true],
|
||||
SentryBundle::class => ['prod' => true],
|
||||
SentryBundle::class => ['dev' => true, 'prod' => true],
|
||||
SymfonycastsSassBundle::class => ['all' => true],
|
||||
StimulusBundle::class => ['all' => true],
|
||||
TurboBundle::class => ['all' => true],
|
||||
DAMADoctrineTestBundle::class => ['test' => true],
|
||||
StofDoctrineExtensionsBundle::class => ['all' => true],
|
||||
SymfonyCastsResetPasswordBundle::class => ['all' => true],
|
||||
SensiolabsTypeScriptBundle::class => ['all' => true],
|
||||
];
|
||||
|
||||
@@ -6,8 +6,12 @@ framework:
|
||||
excluded_patterns:
|
||||
- '*/assets/styles/_*.scss'
|
||||
- '*/assets/styles/**/_*.scss'
|
||||
- '*/assets/**/*_test.ts'
|
||||
- '*/assets/types/*.d.ts'
|
||||
missing_import_mode: strict
|
||||
|
||||
sensiolabs_typescript:
|
||||
source_dir: ['%kernel.project_dir%/assets']
|
||||
|
||||
when@prod:
|
||||
framework:
|
||||
|
||||
@@ -14,7 +14,7 @@ when@prod:
|
||||
# shortcut for private IP address ranges of your proxy
|
||||
trusted_proxies: 'private_ranges'
|
||||
# or, if your proxy instead uses the "Forwarded" header
|
||||
trusted_headers: [ 'forwarded' ]
|
||||
trusted_headers: [ 'x-forwarded-proto' ]
|
||||
|
||||
when@test:
|
||||
framework:
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
symfonycasts_reset_password:
|
||||
request_password_repository: Tvdt\Repository\ResetPasswordRequestRepository
|
||||
@@ -30,7 +30,7 @@ security:
|
||||
|
||||
access_control:
|
||||
- { path: ^/admin, roles: ROLE_ADMIN }
|
||||
- { path: ^/backoffice, roles: ROLE_USER }
|
||||
- { path: ^/backoffice, roles: IS_AUTHENTICATED }
|
||||
|
||||
when@test:
|
||||
security:
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
when@dev:
|
||||
sentry:
|
||||
dsn: 'https://placeholder@placeholder.ingest.sentry.io/0'
|
||||
options:
|
||||
spotlight: true
|
||||
spotlight_url: 'http://spotlight:8969/stream'
|
||||
|
||||
when@prod:
|
||||
sentry:
|
||||
dsn: '%env(SENTRY_DSN)%'
|
||||
|
||||
@@ -6,3 +6,4 @@ stof_doctrine_extensions:
|
||||
default:
|
||||
timestampable: true
|
||||
softdeleteable: true
|
||||
loggable: true
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
twig:
|
||||
file_name_pattern: '*.twig'
|
||||
form_themes: [ 'bootstrap_5_layout.html.twig' ]
|
||||
globals:
|
||||
sentry_dsn: '%env(SENTRY_DSN)%'
|
||||
|
||||
when@test:
|
||||
twig:
|
||||
|
||||
Generated
+22
@@ -1490,6 +1490,19 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* skip_translation_on_load?: bool|Param, // Default: false
|
||||
* metadata_cache_pool?: scalar|Param|null, // Default: null
|
||||
* }
|
||||
* @psalm-type SymfonycastsResetPasswordConfig = array{
|
||||
* request_password_repository?: scalar|Param|null, // A class that implements ResetPasswordRequestRepositoryInterface - usually your ResetPasswordRequestRepository.
|
||||
* lifetime?: int|Param, // The length of time in seconds that a password reset request is valid for after it is created. // Default: 3600
|
||||
* throttle_limit?: int|Param, // Another password reset cannot be made faster than this throttle time in seconds. // Default: 3600
|
||||
* enable_garbage_collection?: bool|Param, // Enable/Disable automatic garbage collection. // Default: true
|
||||
* }
|
||||
* @psalm-type SensiolabsTypescriptConfig = array{
|
||||
* source_dir?: list<scalar|Param|null>,
|
||||
* binary_download_dir?: scalar|Param|null, // The directory where the SWC binary will be downloaded // Default: "%kernel.project_dir%/var"
|
||||
* swc_binary?: scalar|Param|null, // The SWC binary to use // Default: null
|
||||
* swc_config_file?: scalar|Param|null, // Path to .swcrc configuration file to use // Default: "%kernel.project_dir%/.swcrc"
|
||||
* swc_version?: scalar|Param|null, // The SWC version to use // Default: "v1.3.92"
|
||||
* }
|
||||
* @psalm-type ConfigType = array{
|
||||
* imports?: ImportsConfig,
|
||||
* parameters?: ParametersConfig,
|
||||
@@ -1505,6 +1518,8 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* stimulus?: StimulusConfig,
|
||||
* turbo?: TurboConfig,
|
||||
* stof_doctrine_extensions?: StofDoctrineExtensionsConfig,
|
||||
* symfonycasts_reset_password?: SymfonycastsResetPasswordConfig,
|
||||
* sensiolabs_typescript?: SensiolabsTypescriptConfig,
|
||||
* "when@dev"?: array{
|
||||
* imports?: ImportsConfig,
|
||||
* parameters?: ParametersConfig,
|
||||
@@ -1518,10 +1533,13 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* web_profiler?: WebProfilerConfig,
|
||||
* twig_extra?: TwigExtraConfig,
|
||||
* symfonycasts_verify_email?: SymfonycastsVerifyEmailConfig,
|
||||
* sentry?: SentryConfig,
|
||||
* symfonycasts_sass?: SymfonycastsSassConfig,
|
||||
* stimulus?: StimulusConfig,
|
||||
* turbo?: TurboConfig,
|
||||
* stof_doctrine_extensions?: StofDoctrineExtensionsConfig,
|
||||
* symfonycasts_reset_password?: SymfonycastsResetPasswordConfig,
|
||||
* sensiolabs_typescript?: SensiolabsTypescriptConfig,
|
||||
* },
|
||||
* "when@prod"?: array{
|
||||
* imports?: ImportsConfig,
|
||||
@@ -1539,6 +1557,8 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* stimulus?: StimulusConfig,
|
||||
* turbo?: TurboConfig,
|
||||
* stof_doctrine_extensions?: StofDoctrineExtensionsConfig,
|
||||
* symfonycasts_reset_password?: SymfonycastsResetPasswordConfig,
|
||||
* sensiolabs_typescript?: SensiolabsTypescriptConfig,
|
||||
* },
|
||||
* "when@test"?: array{
|
||||
* imports?: ImportsConfig,
|
||||
@@ -1557,6 +1577,8 @@ use Symfony\Component\Config\Loader\ParamConfigurator as Param;
|
||||
* turbo?: TurboConfig,
|
||||
* dama_doctrine_test?: DamaDoctrineTestConfig,
|
||||
* stof_doctrine_extensions?: StofDoctrineExtensionsConfig,
|
||||
* symfonycasts_reset_password?: SymfonycastsResetPasswordConfig,
|
||||
* sensiolabs_typescript?: SensiolabsTypescriptConfig,
|
||||
* },
|
||||
* ...<string, ExtensionType|array{ // extra keys must follow the when@%env% pattern or match an extension alias
|
||||
* imports?: ImportsConfig,
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": ["deno.window", "dom", "dom.iterable"],
|
||||
"strict": true,
|
||||
"noImplicitOverride": false,
|
||||
"types": ["./assets/types/global.d.ts"]
|
||||
},
|
||||
"imports": {
|
||||
"@hotwired/stimulus": "npm:@hotwired/stimulus@^3.2.2",
|
||||
"@hotwired/turbo": "npm:@hotwired/turbo@^8.0.23",
|
||||
"bootstrap": "npm:bootstrap@^5.3.8",
|
||||
"@sentry/browser": "npm:@sentry/browser@^10.63.0",
|
||||
"@std/assert": "jsr:@std/assert@^1.0.19"
|
||||
},
|
||||
"fmt": {
|
||||
"include": ["assets/"],
|
||||
"exclude": ["assets/vendor/", "assets/styles/", "assets/img/"],
|
||||
"singleQuote": true,
|
||||
"indentWidth": 4
|
||||
},
|
||||
"lint": {
|
||||
"include": ["assets/"],
|
||||
"exclude": ["assets/vendor/"],
|
||||
"rules": {
|
||||
"exclude": ["no-window", "no-window-prefix"]
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"include": ["assets/"],
|
||||
"exclude": ["assets/vendor/"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"version": "5",
|
||||
"specifiers": {
|
||||
"jsr:@std/assert@*": "1.0.19",
|
||||
"jsr:@std/assert@^1.0.19": "1.0.19",
|
||||
"jsr:@std/internal@^1.0.12": "1.0.14",
|
||||
"npm:@hotwired/stimulus@^3.2.2": "3.2.2",
|
||||
"npm:@hotwired/turbo@^8.0.23": "8.0.23",
|
||||
"npm:@sentry/browser@^10.63.0": "10.65.0",
|
||||
"npm:bootstrap@^5.3.8": "5.3.8_@popperjs+core@2.11.8"
|
||||
},
|
||||
"jsr": {
|
||||
"@std/assert@1.0.19": {
|
||||
"integrity": "eaada96ee120cb980bc47e040f82814d786fe8162ecc53c91d8df60b8755991e",
|
||||
"dependencies": [
|
||||
"jsr:@std/internal"
|
||||
]
|
||||
},
|
||||
"@std/internal@1.0.14": {
|
||||
"integrity": "291516b3d4c35024d6ffbc0a9df5bf4c64116e05b50012cf846710152d2ffdf7"
|
||||
}
|
||||
},
|
||||
"npm": {
|
||||
"@hotwired/stimulus@3.2.2": {
|
||||
"integrity": "sha512-eGeIqNOQpXoPAIP7tC1+1Yc1yl1xnwYqg+3mzqxyrbE5pg5YFBZcA6YoTiByJB6DKAEsiWtl6tjTJS4IYtbB7A=="
|
||||
},
|
||||
"@hotwired/turbo@8.0.23": {
|
||||
"integrity": "sha512-GZ7cijxEZ6Ig71u7rD6LHaRv/wcE/hNsc+nEfiWOkLNqUgLOwo5MNGWOy5ZV9ZUDSiQx1no7YxjTNnT4O6//cQ=="
|
||||
},
|
||||
"@popperjs/core@2.11.8": {
|
||||
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A=="
|
||||
},
|
||||
"@sentry/browser-utils@10.65.0": {
|
||||
"integrity": "sha512-4J0mkfNJAGUOkpg1ZggizyftFTn9N20b+Jl87UnWsDUkNG0Ic1l/FIzMPTVxXrAnhBGu0ULO0TFWMoQ5s3QtZw==",
|
||||
"dependencies": [
|
||||
"@sentry/conventions",
|
||||
"@sentry/core"
|
||||
]
|
||||
},
|
||||
"@sentry/browser@10.65.0": {
|
||||
"integrity": "sha512-XUDDsx0qxzeIlcOu1fDEqTcDl0eiOqghsgV+ReuuNP4jYjZ9kUQxE3rXWM5mlT1pBi4VaQ4FHqvQZZrRXy+oDw==",
|
||||
"dependencies": [
|
||||
"@sentry/browser-utils",
|
||||
"@sentry/conventions",
|
||||
"@sentry/core",
|
||||
"@sentry/feedback",
|
||||
"@sentry/replay",
|
||||
"@sentry/replay-canvas"
|
||||
]
|
||||
},
|
||||
"@sentry/conventions@0.15.1": {
|
||||
"integrity": "sha512-ZLP8bRdMON3prWE2tJyImuYscCxdcJeIPIhrOs/rgyFm3C1nCh1B6gdvPj3AZ5zW08oSFFCsq7T+tYEW3h8MNA=="
|
||||
},
|
||||
"@sentry/core@10.65.0": {
|
||||
"integrity": "sha512-3aqtmM5NgNGo45BNaaBzi0LPQZAw//NEL4HKS5fXm12pJMa4KEkze8DEKnkTEIrGnWaOJKamecHKlnNg/Mqf/Q==",
|
||||
"dependencies": [
|
||||
"@sentry/conventions"
|
||||
]
|
||||
},
|
||||
"@sentry/feedback@10.65.0": {
|
||||
"integrity": "sha512-ck8h7wgd3F3bYNk0v1OgohmyLBeXcKxqlfBJRtQq4k6KZUq+pXimOG7ckNguVMYjCo3PEfuG+ckKc21yqotKug==",
|
||||
"dependencies": [
|
||||
"@sentry/core"
|
||||
]
|
||||
},
|
||||
"@sentry/replay-canvas@10.65.0": {
|
||||
"integrity": "sha512-A7X3RVk1Gk+knK8Ip/2EjejckNCLgCfRZo6eGlsy6qyz904KBpYmys1a0o7QkzFRjhIndjHAfcVxwt6jSLJlrQ==",
|
||||
"dependencies": [
|
||||
"@sentry/core",
|
||||
"@sentry/replay"
|
||||
]
|
||||
},
|
||||
"@sentry/replay@10.65.0": {
|
||||
"integrity": "sha512-aW988CcQBNArbOMzOFOziipHz6uQyXSa4i5CPWsu+nhVPTJHafosi5Lv9n6NM/icDX5e23VdnX6mZd8SyJuo8A==",
|
||||
"dependencies": [
|
||||
"@sentry/browser-utils",
|
||||
"@sentry/core"
|
||||
]
|
||||
},
|
||||
"bootstrap@5.3.8_@popperjs+core@2.11.8": {
|
||||
"integrity": "sha512-HP1SZDqaLDPwsNiqRqi5NcP0SSXciX2s9E+RyqJIIqGo+vJeN5AJVM98CXmW/Wux0nQ5L7jeWUdplCEf0Ee+tg==",
|
||||
"dependencies": [
|
||||
"@popperjs/core"
|
||||
]
|
||||
}
|
||||
},
|
||||
"workspace": {
|
||||
"dependencies": [
|
||||
"jsr:@std/assert@^1.0.19",
|
||||
"npm:@hotwired/stimulus@^3.2.2",
|
||||
"npm:@hotwired/turbo@^8.0.23",
|
||||
"npm:@sentry/browser@^10.63.0",
|
||||
"npm:bootstrap@^5.3.8"
|
||||
]
|
||||
}
|
||||
}
|
||||
+27
-27
@@ -12,33 +12,33 @@ declare(strict_types=1);
|
||||
* be used as an "entrypoint" (and passed to the importmap() Twig function).
|
||||
*
|
||||
* The "importmap:require" command can be used to add new entries to this file.
|
||||
*
|
||||
* @return array<string, array{ // Import name as key, description of the imported file as value
|
||||
* path: string, // Logical, relative or absolute path to the file
|
||||
* type?: 'js'|'css'|'json', // Type of the file, defaults to 'js'
|
||||
* entrypoint?: bool, // Whether the file is an entrypoint, for 'js' only
|
||||
* }|array{
|
||||
* version: string, // Version of the remote package
|
||||
* package_specifier?: string, // Remote "package-name/path" specifier, defaults to the import name
|
||||
* type?: 'js'|'css'|'json',
|
||||
* entrypoint?: bool,
|
||||
* }>
|
||||
*/
|
||||
return [
|
||||
'quiz' => [
|
||||
'path' => './assets/quiz.js',
|
||||
'entrypoint' => true,
|
||||
],
|
||||
'backoffice' => [
|
||||
'path' => './assets/backoffice.js',
|
||||
'entrypoint' => true,
|
||||
],
|
||||
'@symfony/stimulus-bundle' => [
|
||||
'path' => './vendor/symfony/stimulus-bundle/assets/dist/loader.js',
|
||||
],
|
||||
'bootstrap' => [
|
||||
'version' => '5.3.8',
|
||||
],
|
||||
'@popperjs/core' => [
|
||||
'version' => '2.11.8',
|
||||
],
|
||||
'bootstrap/dist/css/bootstrap.min.css' => [
|
||||
'version' => '5.3.8',
|
||||
'type' => 'css',
|
||||
],
|
||||
'@hotwired/stimulus' => [
|
||||
'version' => '3.2.2',
|
||||
],
|
||||
'@hotwired/turbo' => [
|
||||
'version' => '8.0.23',
|
||||
],
|
||||
'quiz' => ['path' => './assets/quiz.ts', 'entrypoint' => true],
|
||||
'backoffice' => ['path' => './assets/backoffice.ts', 'entrypoint' => true],
|
||||
'@symfony/stimulus-bundle' => ['path' => './vendor/symfony/stimulus-bundle/assets/dist/loader.js'],
|
||||
'bootstrap' => ['version' => '5.3.8'],
|
||||
'@popperjs/core' => ['version' => '2.11.8'],
|
||||
'bootstrap/dist/css/bootstrap.min.css' => ['version' => '5.3.8', 'type' => 'css'],
|
||||
'@hotwired/stimulus' => ['version' => '3.2.2'],
|
||||
'@hotwired/turbo' => ['version' => '8.0.23'],
|
||||
'bootstrap-icons/font/bootstrap-icons.min.css' => ['version' => '1.13.1', 'type' => 'css'],
|
||||
'@sentry/browser' => ['version' => '10.63.0'],
|
||||
'@sentry/feedback' => ['version' => '10.63.0'],
|
||||
'@sentry/core/browser' => ['version' => '10.63.0'],
|
||||
'@sentry/browser-utils' => ['version' => '10.63.0'],
|
||||
'@sentry/replay' => ['version' => '10.63.0'],
|
||||
'@sentry/replay-canvas' => ['version' => '10.63.0'],
|
||||
'@sentry/core' => ['version' => '10.63.0'],
|
||||
];
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/** Auto-generated Migration: Please modify to your needs! */
|
||||
final class Version20260705142647 extends AbstractMigration
|
||||
{
|
||||
#[\Override]
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add season question bank tables, quiz finalization, Gedmo Loggable log entries, and label colour/slug';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// this up() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('CREATE TABLE bank_answer (id UUID NOT NULL, ordering SMALLINT DEFAULT 0 NOT NULL, text VARCHAR(255) NOT NULL, is_right_answer BOOLEAN NOT NULL, bank_question_id UUID NOT NULL, PRIMARY KEY (id))');
|
||||
$this->addSql('CREATE INDEX IDX_FAB865583CAC40C0 ON bank_answer (bank_question_id)');
|
||||
$this->addSql('CREATE TABLE bank_question (id UUID NOT NULL, question VARCHAR(255) NOT NULL, reusable BOOLEAN DEFAULT false NOT NULL, season_id UUID NOT NULL, PRIMARY KEY (id))');
|
||||
$this->addSql('CREATE INDEX IDX_87B753C94EC001D1 ON bank_question (season_id)');
|
||||
$this->addSql('CREATE TABLE bank_question_question_label (bank_question_id UUID NOT NULL, question_label_id UUID NOT NULL, PRIMARY KEY (bank_question_id, question_label_id))');
|
||||
$this->addSql('CREATE INDEX IDX_856E26833CAC40C0 ON bank_question_question_label (bank_question_id)');
|
||||
$this->addSql('CREATE INDEX IDX_856E268350B19F35 ON bank_question_question_label (question_label_id)');
|
||||
$this->addSql('CREATE TABLE bank_question_usage (id UUID NOT NULL, created TIMESTAMP(0) WITH TIME ZONE NOT NULL, question_id UUID DEFAULT NULL, bank_question_id UUID NOT NULL, quiz_id UUID NOT NULL, PRIMARY KEY (id))');
|
||||
$this->addSql('CREATE INDEX IDX_775833AD1E27F6BF ON bank_question_usage (question_id)');
|
||||
$this->addSql('CREATE INDEX IDX_775833AD3CAC40C0 ON bank_question_usage (bank_question_id)');
|
||||
$this->addSql('CREATE INDEX IDX_775833AD853CD175 ON bank_question_usage (quiz_id)');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_775833AD3CAC40C0853CD175 ON bank_question_usage (bank_question_id, quiz_id)');
|
||||
$this->addSql('CREATE TABLE ext_log_entries (data JSON DEFAULT NULL, id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, action VARCHAR(8) NOT NULL, logged_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, object_id VARCHAR(64) DEFAULT NULL, object_class VARCHAR(191) NOT NULL, version INT NOT NULL, username VARCHAR(191) DEFAULT NULL, PRIMARY KEY (id))');
|
||||
$this->addSql('CREATE INDEX log_class_lookup_idx ON ext_log_entries (object_class)');
|
||||
$this->addSql('CREATE INDEX log_date_lookup_idx ON ext_log_entries (logged_at)');
|
||||
$this->addSql('CREATE INDEX log_user_lookup_idx ON ext_log_entries (username)');
|
||||
$this->addSql('CREATE INDEX log_version_lookup_idx ON ext_log_entries (object_id, object_class, version)');
|
||||
$this->addSql("CREATE TABLE question_label (id UUID NOT NULL, colour VARCHAR(16) DEFAULT 'secondary' NOT NULL, slug VARCHAR(64) NOT NULL, name VARCHAR(64) NOT NULL, season_id UUID NOT NULL, PRIMARY KEY (id))");
|
||||
$this->addSql('CREATE INDEX IDX_3E4C41EC4EC001D1 ON question_label (season_id)');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_3E4C41EC5E237E064EC001D1 ON question_label (name, season_id)');
|
||||
$this->addSql('CREATE UNIQUE INDEX uq_question_label_slug_season ON question_label (slug, season_id)');
|
||||
$this->addSql('ALTER TABLE bank_answer ADD CONSTRAINT FK_FAB865583CAC40C0 FOREIGN KEY (bank_question_id) REFERENCES bank_question (id) NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE bank_question ADD CONSTRAINT FK_87B753C94EC001D1 FOREIGN KEY (season_id) REFERENCES season (id) NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE bank_question_question_label ADD CONSTRAINT FK_856E26833CAC40C0 FOREIGN KEY (bank_question_id) REFERENCES bank_question (id) ON DELETE CASCADE');
|
||||
$this->addSql('ALTER TABLE bank_question_question_label ADD CONSTRAINT FK_856E268350B19F35 FOREIGN KEY (question_label_id) REFERENCES question_label (id) ON DELETE CASCADE');
|
||||
$this->addSql('ALTER TABLE bank_question_usage ADD CONSTRAINT FK_775833AD1E27F6BF FOREIGN KEY (question_id) REFERENCES question (id) ON DELETE SET NULL NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE bank_question_usage ADD CONSTRAINT FK_775833AD3CAC40C0 FOREIGN KEY (bank_question_id) REFERENCES bank_question (id) NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE bank_question_usage ADD CONSTRAINT FK_775833AD853CD175 FOREIGN KEY (quiz_id) REFERENCES quiz (id) ON DELETE CASCADE NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE question_label ADD CONSTRAINT FK_3E4C41EC4EC001D1 FOREIGN KEY (season_id) REFERENCES season (id) NOT DEFERRABLE');
|
||||
$this->addSql('ALTER TABLE quiz ADD finalized_at TIMESTAMP(0) WITH TIME ZONE DEFAULT NULL');
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// this down() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('ALTER TABLE bank_answer DROP CONSTRAINT FK_FAB865583CAC40C0');
|
||||
$this->addSql('ALTER TABLE bank_question DROP CONSTRAINT FK_87B753C94EC001D1');
|
||||
$this->addSql('ALTER TABLE bank_question_question_label DROP CONSTRAINT FK_856E26833CAC40C0');
|
||||
$this->addSql('ALTER TABLE bank_question_question_label DROP CONSTRAINT FK_856E268350B19F35');
|
||||
$this->addSql('ALTER TABLE bank_question_usage DROP CONSTRAINT FK_775833AD1E27F6BF');
|
||||
$this->addSql('ALTER TABLE bank_question_usage DROP CONSTRAINT FK_775833AD3CAC40C0');
|
||||
$this->addSql('ALTER TABLE bank_question_usage DROP CONSTRAINT FK_775833AD853CD175');
|
||||
$this->addSql('ALTER TABLE question_label DROP CONSTRAINT FK_3E4C41EC4EC001D1');
|
||||
$this->addSql('DROP TABLE bank_answer');
|
||||
$this->addSql('DROP TABLE bank_question');
|
||||
$this->addSql('DROP TABLE bank_question_question_label');
|
||||
$this->addSql('DROP TABLE bank_question_usage');
|
||||
$this->addSql('DROP TABLE ext_log_entries');
|
||||
$this->addSql('DROP TABLE question_label');
|
||||
$this->addSql('ALTER TABLE quiz DROP finalized_at');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace DoctrineMigrations;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/** Auto-generated Migration: Please modify to your needs! */
|
||||
final class Version20260707205155 extends AbstractMigration
|
||||
{
|
||||
#[\Override]
|
||||
public function getDescription(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
// this up() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('CREATE TABLE reset_password_request (id UUID NOT NULL, selector VARCHAR(20) NOT NULL, hashed_token VARCHAR(100) NOT NULL, requested_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, expires_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, user_id UUID NOT NULL, PRIMARY KEY (id))');
|
||||
$this->addSql('CREATE INDEX IDX_7CE748AA76ED395 ON reset_password_request (user_id)');
|
||||
$this->addSql('ALTER TABLE reset_password_request ADD CONSTRAINT FK_7CE748AA76ED395 FOREIGN KEY (user_id) REFERENCES "user" (id) NOT DEFERRABLE');
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
// this down() migration is auto-generated, please modify it to your needs
|
||||
$this->addSql('ALTER TABLE reset_password_request DROP CONSTRAINT FK_7CE748AA76ED395');
|
||||
$this->addSql('DROP TABLE reset_password_request');
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,9 @@ declare(strict_types=1);
|
||||
namespace Tvdt\Controller;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as AbstractBaseController;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Entity\User;
|
||||
use Tvdt\Enum\FlashType;
|
||||
|
||||
abstract class AbstractController extends AbstractBaseController
|
||||
@@ -13,6 +16,22 @@ abstract class AbstractController extends AbstractBaseController
|
||||
|
||||
protected const string CANDIDATE_HASH_REGEX = '[\w\-=]+';
|
||||
|
||||
protected User $authenticatedUser {
|
||||
get {
|
||||
$user = $this->getUser();
|
||||
\assert($user instanceof User);
|
||||
|
||||
return $user;
|
||||
}
|
||||
}
|
||||
|
||||
protected function assertSameSeason(Season $season, Season $subjectSeason): void
|
||||
{
|
||||
if ($season !== $subjectSeason) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
}
|
||||
|
||||
#[\Override]
|
||||
protected function addFlash(FlashType|string $type, mixed $message): void
|
||||
{
|
||||
|
||||
@@ -14,17 +14,19 @@ use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Routing\Requirement\Requirement;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Entity\User;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\CreateSeasonFormType;
|
||||
use Tvdt\Helpers\FilenameSanitizer;
|
||||
use Tvdt\Repository\SeasonRepository;
|
||||
use Tvdt\Security\Voter\SeasonVoter;
|
||||
use Tvdt\Service\QuizSpreadsheetService;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('ROLE_USER')]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
final class BackofficeController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
@@ -32,17 +34,15 @@ final class BackofficeController extends AbstractController
|
||||
private readonly Security $security,
|
||||
private readonly QuizSpreadsheetService $excel,
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly TranslatorInterface $translator,
|
||||
) {}
|
||||
|
||||
#[Route('/backoffice/', name: 'tvdt_backoffice_index')]
|
||||
public function index(): Response
|
||||
{
|
||||
$user = $this->getUser();
|
||||
\assert($user instanceof User);
|
||||
|
||||
$seasons = $this->security->isGranted('ROLE_ADMIN')
|
||||
? $this->seasonRepository->findAll()
|
||||
: $this->seasonRepository->getSeasonsForUser($user);
|
||||
: $this->seasonRepository->getSeasonsForUser($this->authenticatedUser);
|
||||
|
||||
return $this->render('backoffice/index.html.twig', [
|
||||
'seasons' => $seasons,
|
||||
@@ -58,10 +58,7 @@ final class BackofficeController extends AbstractController
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$user = $this->getUser();
|
||||
\assert($user instanceof User);
|
||||
|
||||
$season->addOwner($user);
|
||||
$season->addOwner($this->authenticatedUser);
|
||||
$season->generateSeasonCode();
|
||||
|
||||
$this->em->persist($season);
|
||||
@@ -90,11 +87,17 @@ final class BackofficeController extends AbstractController
|
||||
requirements: ['quiz' => Requirement::UUID],
|
||||
methods: ['GET'],
|
||||
)]
|
||||
public function exportQuiz(Quiz $quiz): StreamedResponse
|
||||
public function exportQuiz(Quiz $quiz): Response
|
||||
{
|
||||
if (!$this->authenticatedUser->isVerified) {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('Please confirm your email address before exporting a quiz.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season', ['seasonCode' => $quiz->season->seasonCode]);
|
||||
}
|
||||
|
||||
$response = new StreamedResponse($this->excel->quizToXlsx($quiz));
|
||||
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
$response->headers->set('Content-Disposition', HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $quiz->name.'.xlsx'));
|
||||
$response->headers->set('Content-Disposition', HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, FilenameSanitizer::sanitize($quiz->name).'.xlsx'));
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\Elimination;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Factory\EliminationFactory;
|
||||
|
||||
final class PrepareEliminationController extends AbstractController
|
||||
@@ -52,7 +53,7 @@ final class PrepareEliminationController extends AbstractController
|
||||
return $this->redirectToRoute('tvdt_elimination', ['elimination' => $elimination->id]);
|
||||
}
|
||||
|
||||
$this->addFlash('success', 'Elimination updated');
|
||||
$this->addFlash(FlashType::Success, 'Elimination updated');
|
||||
|
||||
return $this->redirectToRoute('tvdt_prepare_elimination_view', ['elimination' => $elimination->id]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller\Backoffice;
|
||||
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Routing\Requirement\Requirement;
|
||||
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
use Symfony\Component\String\Slugger\SluggerInterface;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\BankQuestion;
|
||||
use Tvdt\Entity\BankQuestionUsage;
|
||||
use Tvdt\Entity\QuestionLabel;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Enum\LabelColour;
|
||||
use Tvdt\Exception\BankQuestionAlreadyUsedException;
|
||||
use Tvdt\Exception\BankQuestionIncompleteException;
|
||||
use Tvdt\Exception\QuizLockedException;
|
||||
use Tvdt\Form\BankQuestionFormType;
|
||||
use Tvdt\Repository\BankQuestionRepository;
|
||||
use Tvdt\Repository\QuestionLabelRepository;
|
||||
use Tvdt\Repository\QuizRepository;
|
||||
use Tvdt\Security\Voter\SeasonVoter;
|
||||
use Tvdt\Service\QuestionBankService;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
class QuestionBankController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly BankQuestionRepository $bankQuestionRepository,
|
||||
private readonly QuestionLabelRepository $questionLabelRepository,
|
||||
private readonly QuizRepository $quizRepository,
|
||||
private readonly QuestionBankService $questionBankService,
|
||||
private readonly SluggerInterface $slugger,
|
||||
) {}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank',
|
||||
name: 'tvdt_backoffice_question_bank',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
priority: 10,
|
||||
)]
|
||||
public function index(Season $season, Request $request): Response
|
||||
{
|
||||
$label = null;
|
||||
$labelSlug = $request->query->getString('label');
|
||||
if ('' !== $labelSlug) {
|
||||
$label = $this->questionLabelRepository->findBySlugAndSeason($labelSlug, $season);
|
||||
}
|
||||
|
||||
return $this->render('backoffice/season.html.twig', [
|
||||
'season' => $season,
|
||||
'bankQuestions' => $this->bankQuestionRepository->findBySeason($season, $label),
|
||||
'assignableQuizzes' => $this->quizRepository->findAssignableForSeason($season),
|
||||
'activeLabel' => $label,
|
||||
'labelColours' => LabelColour::cases(),
|
||||
'activeTab' => 'question-bank',
|
||||
'template' => 'backoffice/season/tab_question_bank.html.twig',
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/new',
|
||||
name: 'tvdt_backoffice_question_bank_new',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
priority: 10,
|
||||
)]
|
||||
public function new(Season $season, Request $request): Response
|
||||
{
|
||||
$bankQuestion = new BankQuestion();
|
||||
|
||||
$isTurboFrame = $request->headers->has('Turbo-Frame');
|
||||
|
||||
$form = $this->createForm(BankQuestionFormType::class, $bankQuestion, [
|
||||
'season' => $season,
|
||||
'action' => $this->generateUrl('tvdt_backoffice_question_bank_new', ['seasonCode' => $season->seasonCode]),
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$season->addBankQuestion($bankQuestion);
|
||||
$this->em->persist($bankQuestion);
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question added to the question bank'));
|
||||
|
||||
if ($isTurboFrame) {
|
||||
return new Response('<turbo-frame id="bank-question-modal-frame"></turbo-frame>');
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$template = $isTurboFrame
|
||||
? 'backoffice/question_bank/_frame.html.twig'
|
||||
: 'backoffice/question_bank/form.html.twig';
|
||||
|
||||
return $this->render($template, [
|
||||
'season' => $season,
|
||||
'form' => $form,
|
||||
'bankQuestion' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/{bankQuestion}/edit',
|
||||
name: 'tvdt_backoffice_question_bank_edit',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'bankQuestion' => Requirement::UUID],
|
||||
priority: 10,
|
||||
)]
|
||||
public function edit(Season $season, BankQuestion $bankQuestion, Request $request): Response
|
||||
{
|
||||
$this->assertSameSeason($season, $bankQuestion->season);
|
||||
|
||||
$isTurboFrame = $request->headers->has('Turbo-Frame');
|
||||
|
||||
$form = $this->createForm(BankQuestionFormType::class, $bankQuestion, [
|
||||
'season' => $season,
|
||||
'action' => $this->generateUrl('tvdt_backoffice_question_bank_edit', [
|
||||
'seasonCode' => $season->seasonCode,
|
||||
'bankQuestion' => $bankQuestion->id,
|
||||
]),
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->em->flush();
|
||||
|
||||
$this->syncUsagesAfterEdit($bankQuestion);
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question updated'));
|
||||
|
||||
if ($isTurboFrame) {
|
||||
return new Response('<turbo-frame id="bank-question-modal-frame"></turbo-frame>');
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$template = $isTurboFrame
|
||||
? 'backoffice/question_bank/_frame.html.twig'
|
||||
: 'backoffice/question_bank/form.html.twig';
|
||||
|
||||
return $this->render($template, [
|
||||
'season' => $season,
|
||||
'form' => $form,
|
||||
'bankQuestion' => $bankQuestion,
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('delete_bank_question')]
|
||||
#[IsGranted(SeasonVoter::DELETE, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/{bankQuestion}/delete',
|
||||
name: 'tvdt_backoffice_question_bank_delete',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'bankQuestion' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
priority: 10,
|
||||
)]
|
||||
public function delete(Season $season, BankQuestion $bankQuestion): RedirectResponse
|
||||
{
|
||||
$this->assertSameSeason($season, $bankQuestion->season);
|
||||
|
||||
$hasLockedUsages = $bankQuestion->usages->exists(
|
||||
static fn (int $key, BankQuestionUsage $usage): bool => $usage->quiz->isLocked,
|
||||
);
|
||||
if ($hasLockedUsages) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('This question cannot be deleted because it is used in a locked or active quiz'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$this->em->remove($bankQuestion);
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question removed from the question bank'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('assign_bank_question')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/{bankQuestion}/assign',
|
||||
name: 'tvdt_backoffice_question_bank_assign',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'bankQuestion' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
priority: 10,
|
||||
)]
|
||||
public function assign(Season $season, BankQuestion $bankQuestion, Request $request): RedirectResponse
|
||||
{
|
||||
$this->assertSameSeason($season, $bankQuestion->season);
|
||||
|
||||
$quizId = $request->request->getString('quiz');
|
||||
if (!Uuid::isValid($quizId)) {
|
||||
throw new BadRequestHttpException('Invalid quiz');
|
||||
}
|
||||
|
||||
$quiz = $this->em->getRepository(Quiz::class)->find($quizId);
|
||||
if (!$quiz instanceof Quiz || $quiz->season !== $season) {
|
||||
throw new BadRequestHttpException('Invalid quiz');
|
||||
}
|
||||
|
||||
$this->denyAccessUnlessGranted(SeasonVoter::MODIFY_QUIZ_CONTENT, $quiz);
|
||||
|
||||
try {
|
||||
$this->questionBankService->assignToQuiz($bankQuestion, $quiz);
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question added to quiz %quiz%', ['%quiz%' => $quiz->name]));
|
||||
} catch (QuizLockedException) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('This quiz can no longer be altered'));
|
||||
} catch (BankQuestionAlreadyUsedException) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('This question has already been used'));
|
||||
} catch (BankQuestionIncompleteException) {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('This question is incomplete: it needs at least two answers and exactly one correct answer'));
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('add_question_label')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/labels',
|
||||
name: 'tvdt_backoffice_question_bank_labels',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
methods: ['POST'],
|
||||
priority: 15,
|
||||
)]
|
||||
public function addLabel(Season $season, Request $request): RedirectResponse
|
||||
{
|
||||
$name = mb_trim($request->request->getString('name'));
|
||||
|
||||
if ('' === $name || mb_strlen($name) > 64) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('Invalid label name'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$slug = mb_strtolower($this->slugger->slug($name)->toString());
|
||||
|
||||
$colour = LabelColour::tryFrom($request->request->getString('colour')) ?? LabelColour::Gray;
|
||||
|
||||
$exists = $season->questionLabels->exists(static fn (int $key, QuestionLabel $label): bool => $label->name === $name);
|
||||
if (!$exists) {
|
||||
if ($this->questionLabelRepository->slugExistsForSeason($slug, $season)) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('A label with a similar name already exists'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
try {
|
||||
$newLabel = new QuestionLabel($name);
|
||||
$newLabel->slug = $slug;
|
||||
$newLabel->colour = $colour;
|
||||
$season->addQuestionLabel($newLabel);
|
||||
$this->em->flush();
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Label added'));
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
// Concurrent request already inserted the same label; treat as a no-op
|
||||
}
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('delete_question_label')]
|
||||
#[IsGranted(SeasonVoter::DELETE, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/labels/{labelSlug}/delete',
|
||||
name: 'tvdt_backoffice_question_bank_label_delete',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'labelSlug' => '[a-z0-9-]+'],
|
||||
methods: ['POST'],
|
||||
priority: 15,
|
||||
)]
|
||||
public function deleteLabel(Season $season, string $labelSlug): RedirectResponse
|
||||
{
|
||||
$label = $this->questionLabelRepository->findBySlugAndSeason($labelSlug, $season);
|
||||
if (!$label instanceof QuestionLabel) {
|
||||
throw $this->createNotFoundException();
|
||||
}
|
||||
|
||||
foreach ($label->bankQuestions as $bankQuestion) {
|
||||
$bankQuestion->removeLabel($label);
|
||||
}
|
||||
|
||||
$this->em->remove($label);
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Label removed'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('unassign_bank_question')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/{bankQuestion}/unassign/{usage}',
|
||||
name: 'tvdt_backoffice_question_bank_unassign',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'bankQuestion' => Requirement::UUID, 'usage' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
priority: 10,
|
||||
)]
|
||||
public function unassign(Season $season, BankQuestion $bankQuestion, BankQuestionUsage $usage): RedirectResponse
|
||||
{
|
||||
$this->assertSameSeason($season, $bankQuestion->season);
|
||||
|
||||
if ($usage->bankQuestion !== $bankQuestion) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
if ($usage->quiz->isLocked) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('This quiz can no longer be altered'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$this->questionBankService->unassignFromQuiz($usage);
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question removed from quiz %quiz%', ['%quiz%' => $usage->quiz->name]));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('sync_bank_question')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/question-bank/{bankQuestion}/sync/{usage}',
|
||||
name: 'tvdt_backoffice_question_bank_sync',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'bankQuestion' => Requirement::UUID, 'usage' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
priority: 10,
|
||||
)]
|
||||
public function syncToQuiz(Season $season, BankQuestion $bankQuestion, BankQuestionUsage $usage): RedirectResponse
|
||||
{
|
||||
$this->assertSameSeason($season, $bankQuestion->season);
|
||||
|
||||
if ($usage->bankQuestion !== $bankQuestion) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
if ($usage->quiz->isLocked) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('This quiz can no longer be altered'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$this->questionBankService->syncToQuiz($bankQuestion, $usage);
|
||||
$this->em->flush();
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question synced to quiz %quiz%', ['%quiz%' => $usage->quiz->name]));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_question_bank', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
private function syncUsagesAfterEdit(BankQuestion $bankQuestion): void
|
||||
{
|
||||
$pendingNames = [];
|
||||
$synced = false;
|
||||
foreach ($bankQuestion->usages as $usage) {
|
||||
if (!$usage->quiz->isLocked) {
|
||||
$this->questionBankService->syncToQuiz($bankQuestion, $usage);
|
||||
$synced = true;
|
||||
} else {
|
||||
$pendingNames[] = $usage->quiz->name;
|
||||
}
|
||||
}
|
||||
|
||||
if ($synced) {
|
||||
$this->em->flush();
|
||||
}
|
||||
|
||||
if ([] !== $pendingNames) {
|
||||
$this->addFlash(
|
||||
FlashType::Warning,
|
||||
$this->translator->trans(
|
||||
'The question was not synced to finalized quiz(zes): %quizzes%. Use the Sync button to update them.',
|
||||
['%quizzes%' => implode(', ', $pendingNames)],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Tvdt\Controller\Backoffice;
|
||||
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Safe\DateTimeImmutable;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -22,19 +23,22 @@ use Tvdt\Entity\Question;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\QuizCandidate;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Exception\ErrorClearingQuizException;
|
||||
use Tvdt\Repository\GivenAnswerRepository;
|
||||
use Tvdt\Repository\QuizCandidateRepository;
|
||||
use Tvdt\Repository\QuizRepository;
|
||||
use Tvdt\Security\Voter\SeasonVoter;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('ROLE_USER')]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
class QuizController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly QuizRepository $quizRepository,
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly QuizCandidateRepository $quizCandidateRepository,
|
||||
private readonly GivenAnswerRepository $givenAnswerRepository,
|
||||
private readonly EntityManagerInterface $em,
|
||||
) {}
|
||||
|
||||
@@ -59,25 +63,7 @@ class QuizController extends AbstractController
|
||||
{
|
||||
$fetchedQuiz = $this->quizRepository->fetchWithQuestionsAndCandidates($quiz->id);
|
||||
|
||||
// Create indexed lookup for quiz candidates by candidate ID
|
||||
$quizCandidatesByCandidateId = [];
|
||||
foreach ($fetchedQuiz->candidateData as $qc) {
|
||||
$quizCandidatesByCandidateId[$qc->candidate->id->toString()] = $qc;
|
||||
}
|
||||
|
||||
// Get given answers counts efficiently via database query
|
||||
$givenAnswersCountByCandidateId = $this->quizRepository->getGivenAnswersCountPerCandidate($quiz);
|
||||
|
||||
// Pre-compute candidate data to avoid nested loops in template
|
||||
$candidateData = [];
|
||||
foreach ($season->candidates as $candidate) {
|
||||
$candidateIdString = $candidate->id->toString();
|
||||
$candidateData[] = [
|
||||
'candidate' => $candidate,
|
||||
'quizCandidate' => $quizCandidatesByCandidateId[$candidateIdString] ?? null,
|
||||
'givenAnswersCount' => $givenAnswersCountByCandidateId[$candidateIdString] ?? 0,
|
||||
];
|
||||
}
|
||||
$candidateData = $this->buildCandidateData($season, $quiz, $fetchedQuiz->candidateData);
|
||||
|
||||
return $this->render('backoffice/quiz.html.twig', [
|
||||
'season' => $season,
|
||||
@@ -116,25 +102,7 @@ class QuizController extends AbstractController
|
||||
)]
|
||||
public function candidatesTab(Season $season, Quiz $quiz): Response
|
||||
{
|
||||
// Create indexed lookup for quiz candidates by candidate ID
|
||||
$quizCandidatesByCandidateId = [];
|
||||
foreach ($quiz->candidateData as $qc) {
|
||||
$quizCandidatesByCandidateId[$qc->candidate->id->toString()] = $qc;
|
||||
}
|
||||
|
||||
// Get given answers counts efficiently via database query
|
||||
$givenAnswersCountByCandidateId = $this->quizRepository->getGivenAnswersCountPerCandidate($quiz);
|
||||
|
||||
// Pre-compute candidate data to avoid nested loops in template
|
||||
$candidateData = [];
|
||||
foreach ($season->candidates as $candidate) {
|
||||
$candidateIdString = $candidate->id->toString();
|
||||
$candidateData[] = [
|
||||
'candidate' => $candidate,
|
||||
'quizCandidate' => $quizCandidatesByCandidateId[$candidateIdString] ?? null,
|
||||
'givenAnswersCount' => $givenAnswersCountByCandidateId[$candidateIdString] ?? 0,
|
||||
];
|
||||
}
|
||||
$candidateData = $this->buildCandidateData($season, $quiz, $quiz->candidateData);
|
||||
|
||||
return $this->render('backoffice/quiz.html.twig', [
|
||||
'season' => $season,
|
||||
@@ -154,7 +122,13 @@ class QuizController extends AbstractController
|
||||
public function answerMapping(Season $season, Quiz $quiz): Response
|
||||
{
|
||||
$fetchedQuiz = $this->quizRepository->fetchWithQuestions($quiz->id);
|
||||
\assert($fetchedQuiz->questions->count() > 0);
|
||||
|
||||
if ($fetchedQuiz->questions->isEmpty()) {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('This quiz has no questions yet'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', ['seasonCode' => $season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
$firstQuestion = $fetchedQuiz->questions->first();
|
||||
\assert($firstQuestion instanceof Question);
|
||||
|
||||
@@ -233,7 +207,7 @@ class QuizController extends AbstractController
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash('success', $this->translator->trans('Candidate answers saved'));
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Candidate answers saved'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_candidates_question', [
|
||||
'seasonCode' => $season->seasonCode,
|
||||
@@ -250,13 +224,28 @@ class QuizController extends AbstractController
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID.'|null'],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function enableQuiz(Season $season, ?Quiz $quiz): RedirectResponse
|
||||
public function enableQuiz(Season $season, ?Quiz $quiz, Request $request): RedirectResponse
|
||||
{
|
||||
if ($quiz instanceof Quiz && !$quiz->isFinalized) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('The quiz must be finalized before it can be activated'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', ['seasonCode' => $season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
$season->activeQuiz = $quiz;
|
||||
$this->em->flush();
|
||||
|
||||
if ($quiz instanceof Quiz) {
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz', ['seasonCode' => $season->seasonCode, 'quiz' => $quiz->id]);
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', ['seasonCode' => $season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
// When deactivating, stay on the quiz page if one was passed
|
||||
$previousQuizId = $request->request->getString('redirect_quiz');
|
||||
if ('' !== $previousQuizId) {
|
||||
$previousQuiz = $this->em->getRepository(Quiz::class)->find($previousQuizId);
|
||||
if ($previousQuiz instanceof Quiz && $previousQuiz->season === $season) {
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', ['seasonCode' => $season->seasonCode, 'quiz' => $previousQuiz->id]);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season', ['seasonCode' => $season->seasonCode]);
|
||||
@@ -274,9 +263,55 @@ class QuizController extends AbstractController
|
||||
{
|
||||
try {
|
||||
$this->quizRepository->clearQuiz($quiz);
|
||||
$this->addFlash('success', $this->translator->trans('Quiz cleared'));
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz cleared and no longer finalized'));
|
||||
} catch (ErrorClearingQuizException) {
|
||||
$this->addFlash('error', $this->translator->trans('Error clearing quiz'));
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('Error clearing quiz'));
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('finalize_quiz')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'quiz')]
|
||||
#[Route(
|
||||
'/backoffice/quiz/{quiz}/finalize',
|
||||
name: 'tvdt_backoffice_quiz_finalize',
|
||||
requirements: ['quiz' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function finalizeQuiz(Quiz $quiz): RedirectResponse
|
||||
{
|
||||
if ($quiz->questions->isEmpty() || [] !== $quiz->getQuestionErrors()) {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('The quiz cannot be finalized while it has errors'));
|
||||
} elseif (!$quiz->isFinalized) {
|
||||
$quiz->finalizedAt = new DateTimeImmutable();
|
||||
$this->em->flush();
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz finalized'));
|
||||
} else {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('The quiz is already finalized'));
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('unfinalize_quiz')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'quiz')]
|
||||
#[Route(
|
||||
'/backoffice/quiz/{quiz}/unfinalize',
|
||||
name: 'tvdt_backoffice_quiz_unfinalize',
|
||||
requirements: ['quiz' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function unfinalizeQuiz(Quiz $quiz): RedirectResponse
|
||||
{
|
||||
if ($quiz->hasStartedCandidates) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('The quiz has already been filled in and can no longer be altered'));
|
||||
} elseif ($quiz->season->activeQuiz === $quiz) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('Deactivate the quiz before undoing the finalization'));
|
||||
} else {
|
||||
$quiz->finalizedAt = null;
|
||||
$this->em->flush();
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz is no longer finalized'));
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
|
||||
@@ -294,7 +329,7 @@ class QuizController extends AbstractController
|
||||
{
|
||||
$this->quizRepository->deleteQuiz($quiz);
|
||||
|
||||
$this->addFlash('success', $this->translator->trans('Quiz deleted'));
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz deleted'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season', ['seasonCode' => $quiz->season->seasonCode]);
|
||||
}
|
||||
@@ -359,8 +394,57 @@ class QuizController extends AbstractController
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash('success', $this->translator->trans('Candidate status updated'));
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Candidate status updated'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_candidates_tab', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('reset_candidate_progress')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'quiz')]
|
||||
#[Route(
|
||||
'/backoffice/quiz/{quiz}/candidate/{candidate}/reset',
|
||||
name: 'tvdt_backoffice_reset_candidate_progress',
|
||||
requirements: ['quiz' => Requirement::UUID, 'candidate' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function resetCandidateProgress(Quiz $quiz, Candidate $candidate): RedirectResponse
|
||||
{
|
||||
$this->em->wrapInTransaction(function () use ($quiz, $candidate): void {
|
||||
$this->givenAnswerRepository->deleteAllForCandidateInQuiz($quiz, $candidate);
|
||||
$this->quizCandidateRepository->resetProgressForCandidate($quiz, $candidate);
|
||||
});
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Candidate progress reset'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_candidates_tab', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pre-computes per-candidate data (quiz participation and given answer counts) to avoid nested loops in templates.
|
||||
*
|
||||
* @param iterable<QuizCandidate> $quizCandidates
|
||||
*
|
||||
* @return list<array{candidate: Candidate, quizCandidate: QuizCandidate|null, givenAnswersCount: int}>
|
||||
*/
|
||||
private function buildCandidateData(Season $season, Quiz $quiz, iterable $quizCandidates): array
|
||||
{
|
||||
$quizCandidatesByCandidateId = [];
|
||||
foreach ($quizCandidates as $qc) {
|
||||
$quizCandidatesByCandidateId[$qc->candidate->id->toString()] = $qc;
|
||||
}
|
||||
|
||||
$givenAnswersCountByCandidateId = $this->quizRepository->getGivenAnswersCountPerCandidate($quiz);
|
||||
|
||||
$candidateData = [];
|
||||
foreach ($season->candidates as $candidate) {
|
||||
$candidateIdString = $candidate->id->toString();
|
||||
$candidateData[] = [
|
||||
'candidate' => $candidate,
|
||||
'quizCandidate' => $quizCandidatesByCandidateId[$candidateIdString] ?? null,
|
||||
'givenAnswersCount' => $givenAnswersCountByCandidateId[$candidateIdString] ?? 0,
|
||||
];
|
||||
}
|
||||
|
||||
return $candidateData;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller\Backoffice;
|
||||
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Routing\Requirement\Requirement;
|
||||
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\Question;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\QuestionFormType;
|
||||
use Tvdt\Security\Voter\SeasonVoter;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
class QuizQuestionController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly TranslatorInterface $translator,
|
||||
) {}
|
||||
|
||||
#[IsGranted(SeasonVoter::MODIFY_QUIZ_CONTENT, subject: 'question')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/quiz/{quiz}/question/{question}/edit',
|
||||
name: 'tvdt_backoffice_quiz_question_edit',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID, 'question' => Requirement::UUID],
|
||||
)]
|
||||
public function edit(Season $season, Quiz $quiz, Question $question, Request $request): Response
|
||||
{
|
||||
if ($question->quiz !== $quiz || $quiz->season !== $season) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
$isTurboFrame = $request->headers->has('Turbo-Frame');
|
||||
|
||||
$form = $this->createForm(QuestionFormType::class, $question, [
|
||||
'action' => $this->generateUrl('tvdt_backoffice_quiz_question_edit', [
|
||||
'seasonCode' => $season->seasonCode,
|
||||
'quiz' => $quiz->id,
|
||||
'question' => $question->id,
|
||||
]),
|
||||
]);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Question updated'));
|
||||
|
||||
if ($isTurboFrame) {
|
||||
return new Response('<turbo-frame id="question-modal-frame"></turbo-frame>');
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', [
|
||||
'seasonCode' => $season->seasonCode,
|
||||
'quiz' => $quiz->id,
|
||||
]);
|
||||
}
|
||||
|
||||
$template = $isTurboFrame
|
||||
? 'backoffice/quiz/_question_frame.html.twig'
|
||||
: 'backoffice/quiz/question_form.html.twig';
|
||||
|
||||
return $this->render($template, [
|
||||
'season' => $season,
|
||||
'quiz' => $quiz,
|
||||
'question' => $question,
|
||||
'form' => $form,
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/quiz/{quiz}/question/{question}/view',
|
||||
name: 'tvdt_backoffice_quiz_question_view',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID, 'question' => Requirement::UUID],
|
||||
)]
|
||||
public function view(Season $season, Quiz $quiz, Question $question): Response
|
||||
{
|
||||
if ($question->quiz !== $quiz || $quiz->season !== $season) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
return $this->render('backoffice/quiz/_question_detail_frame.html.twig', [
|
||||
'question' => $question,
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('question_reorder')]
|
||||
#[IsGranted(SeasonVoter::MODIFY_QUIZ_CONTENT, subject: 'quiz')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/quiz/{quiz}/questions/reorder',
|
||||
name: 'tvdt_backoffice_quiz_questions_reorder',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function reorder(Season $season, Quiz $quiz, Request $request): Response
|
||||
{
|
||||
if ($quiz->season !== $season) {
|
||||
throw new NotFoundHttpException();
|
||||
}
|
||||
|
||||
/** @var list<string> $ordering */
|
||||
$ordering = $request->request->all('ordering');
|
||||
|
||||
$questionsById = [];
|
||||
foreach ($quiz->questions as $question) {
|
||||
$questionsById[$question->id->toString()] = $question;
|
||||
}
|
||||
|
||||
foreach ($ordering as $questionId) {
|
||||
if (!isset($questionsById[$questionId])) {
|
||||
throw new BadRequestHttpException(\sprintf('Unknown question id: %s', $questionId));
|
||||
}
|
||||
}
|
||||
|
||||
if (\count(array_unique($ordering)) !== \count($questionsById)) {
|
||||
throw new BadRequestHttpException('Ordering must include every question exactly once');
|
||||
}
|
||||
|
||||
$position = 1;
|
||||
foreach ($ordering as $questionId) {
|
||||
$questionsById[$questionId]->ordering = $position++;
|
||||
}
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
return new Response('', Response::HTTP_NO_CONTENT);
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,22 @@ declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller\Backoffice;
|
||||
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormError;
|
||||
use Symfony\Component\HttpFoundation\File\UploadedFile;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpKernel\Attribute\AsController;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Routing\Requirement\Requirement;
|
||||
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
|
||||
use Symfony\Component\Security\Http\Attribute\IsGranted;
|
||||
use Symfony\Component\Validator\Constraints\Length;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\Candidate;
|
||||
@@ -20,17 +29,19 @@ use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\AddCandidatesFormType;
|
||||
use Tvdt\Form\SettingsForm;
|
||||
use Tvdt\Form\UploadQuizFormType;
|
||||
use Tvdt\Repository\CandidateRepository;
|
||||
use Tvdt\Security\Voter\SeasonVoter;
|
||||
use Tvdt\Service\QuizSpreadsheetService;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('ROLE_USER')]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
class SeasonController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly EntityManagerInterface $em,
|
||||
private readonly QuizSpreadsheetService $quizSpreadsheet,
|
||||
private readonly CandidateRepository $candidateRepository,
|
||||
) {}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
@@ -39,7 +50,39 @@ class SeasonController extends AbstractController
|
||||
name: 'tvdt_backoffice_season',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
)]
|
||||
public function index(Season $season, Request $request): Response
|
||||
public function index(Season $season): Response
|
||||
{
|
||||
return $this->render('backoffice/season.html.twig', [
|
||||
'season' => $season,
|
||||
'activeTab' => 'tests',
|
||||
'template' => 'backoffice/season/tab_tests.html.twig',
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/candidates',
|
||||
name: 'tvdt_backoffice_season_candidates',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
priority: 10,
|
||||
)]
|
||||
public function candidatesTab(Season $season): Response
|
||||
{
|
||||
return $this->render('backoffice/season.html.twig', [
|
||||
'season' => $season,
|
||||
'activeTab' => 'candidates',
|
||||
'template' => 'backoffice/season/tab_candidates.html.twig',
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/settings',
|
||||
name: 'tvdt_backoffice_season_settings',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
priority: 10,
|
||||
)]
|
||||
public function settingsTab(Season $season, Request $request): Response
|
||||
{
|
||||
$form = $this->createForm(SettingsForm::class, $season->settings);
|
||||
|
||||
@@ -47,14 +90,36 @@ class SeasonController extends AbstractController
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->em->flush();
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_settings', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
return $this->render('backoffice/season.html.twig', [
|
||||
'season' => $season,
|
||||
'form' => $form,
|
||||
'activeTab' => 'settings',
|
||||
'template' => 'backoffice/season/tab_settings.html.twig',
|
||||
]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('regenerate_season_code')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/settings/regenerate-code',
|
||||
name: 'tvdt_backoffice_season_regenerate_code',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function regenerateSeasonCode(Season $season): RedirectResponse
|
||||
{
|
||||
$season->generateSeasonCode();
|
||||
$this->em->flush();
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Season code regenerated'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_settings', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/add-candidate',
|
||||
@@ -64,6 +129,8 @@ class SeasonController extends AbstractController
|
||||
)]
|
||||
public function addCandidates(Season $season, Request $request): Response
|
||||
{
|
||||
$isTurboFrame = $request->headers->has('Turbo-Frame');
|
||||
|
||||
$form = $this->createForm(AddCandidatesFormType::class);
|
||||
$form->handleRequest($request);
|
||||
|
||||
@@ -75,10 +142,68 @@ class SeasonController extends AbstractController
|
||||
|
||||
$this->em->flush();
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season', ['seasonCode' => $season->seasonCode]);
|
||||
if ($isTurboFrame) {
|
||||
return new Response('<turbo-frame id="add-candidates-modal-frame"></turbo-frame>');
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_candidates', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
return $this->render('backoffice/season_add_candidates.html.twig', ['form' => $form]);
|
||||
$template = $isTurboFrame
|
||||
? 'backoffice/season/_add_candidates_frame.html.twig'
|
||||
: 'backoffice/season_add_candidates.html.twig';
|
||||
|
||||
return $this->render($template, ['form' => $form, 'season' => $season]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('rename_candidate')]
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'candidate')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/candidate/{candidate}/rename',
|
||||
name: 'tvdt_backoffice_candidate_rename',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'candidate' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function renameCandidate(Season $season, Candidate $candidate, Request $request): RedirectResponse
|
||||
{
|
||||
$name = mb_trim($request->request->getString('name'));
|
||||
|
||||
if ('' === $name || mb_strlen($name) > 16) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('The candidate name must be between 1 and 16 characters'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_candidates', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$candidate->name = $name;
|
||||
|
||||
try {
|
||||
$this->em->flush();
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('A candidate with this name already exists in this season'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_candidates', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Candidate renamed'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_candidates', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('delete_candidate')]
|
||||
#[IsGranted(SeasonVoter::DELETE, subject: 'candidate')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/candidate/{candidate}/delete',
|
||||
name: 'tvdt_backoffice_candidate_delete',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'candidate' => Requirement::UUID],
|
||||
methods: ['POST'],
|
||||
)]
|
||||
public function deleteCandidate(Season $season, Candidate $candidate): RedirectResponse
|
||||
{
|
||||
$this->candidateRepository->deleteCandidate($candidate);
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Candidate deleted'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_season_candidates', ['seasonCode' => $season->seasonCode]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
@@ -112,4 +237,52 @@ class SeasonController extends AbstractController
|
||||
|
||||
return $this->render('/backoffice/quiz_add.html.twig', ['form' => $form, 'season' => $season]);
|
||||
}
|
||||
|
||||
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
|
||||
#[Route(
|
||||
'/backoffice/season/{seasonCode:season}/add-blank-quiz',
|
||||
name: 'tvdt_backoffice_quiz_add_blank',
|
||||
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
|
||||
priority: 10,
|
||||
)]
|
||||
public function addBlankQuiz(Request $request, Season $season): Response
|
||||
{
|
||||
$form = $this->createFormBuilder(new Quiz())
|
||||
->add('name', TextType::class, [
|
||||
'label' => $this->translator->trans('Quiz name'),
|
||||
'translation_domain' => false,
|
||||
'constraints' => [
|
||||
new NotBlank(),
|
||||
new Length(max: 64),
|
||||
],
|
||||
])
|
||||
->add('save', SubmitType::class, ['label' => 'Create'])
|
||||
->getForm();
|
||||
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
/** @var Quiz $quiz */
|
||||
$quiz = $form->getData();
|
||||
$quiz->season = $season;
|
||||
$this->em->persist($quiz);
|
||||
|
||||
try {
|
||||
$this->em->flush();
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
$form->get('name')->addError(new FormError($this->translator->trans('A quiz with this name already exists in this season')));
|
||||
|
||||
return $this->render('/backoffice/quiz_add_blank.html.twig', ['form' => $form, 'season' => $season]);
|
||||
}
|
||||
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz Added!'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_quiz_overview', [
|
||||
'seasonCode' => $season->seasonCode,
|
||||
'quiz' => $quiz->id,
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->render('/backoffice/quiz_add_blank.html.twig', ['form' => $form, 'season' => $season]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller\Backoffice;
|
||||
|
||||
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Safe\DateTimeImmutable;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\Form\FormError;
|
||||
use Symfony\Component\Form\FormInterface;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\HeaderUtils;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Controller\AbstractController;
|
||||
use Tvdt\Entity\User;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\ChangeEmailFormType;
|
||||
use Tvdt\Form\ChangeUserPasswordFormType;
|
||||
use Tvdt\Helpers\FilenameSanitizer;
|
||||
use Tvdt\Repository\UserRepository;
|
||||
use Tvdt\Security\EmailVerifier;
|
||||
use Tvdt\Service\DataExportService;
|
||||
|
||||
final class SettingsController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly UserPasswordHasherInterface $passwordHasher,
|
||||
private readonly UserRepository $userRepository,
|
||||
private readonly EmailVerifier $emailVerifier,
|
||||
private readonly Security $security,
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly DataExportService $dataExportService,
|
||||
) {}
|
||||
|
||||
#[Route('/backoffice/settings', name: 'tvdt_backoffice_settings', methods: ['GET'])]
|
||||
public function index(): Response
|
||||
{
|
||||
return $this->renderSettings();
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('settings_language')]
|
||||
#[Route('/backoffice/settings/language', name: 'tvdt_backoffice_settings_language', methods: ['POST'])]
|
||||
public function saveLanguage(): RedirectResponse
|
||||
{
|
||||
// Only Dutch is available for now, so saving is a noop.
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Language saved'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
#[Route('/backoffice/settings/password', name: 'tvdt_backoffice_settings_password', methods: ['POST'])]
|
||||
public function changePassword(Request $request): Response
|
||||
{
|
||||
$user = $this->authenticatedUser;
|
||||
$form = $this->createForm(ChangeUserPasswordFormType::class);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
/** @var string $plainPassword */
|
||||
$plainPassword = $form->get('plainPassword')->getData();
|
||||
|
||||
$user->password = $this->passwordHasher->hashPassword($user, $plainPassword);
|
||||
$this->entityManager->flush();
|
||||
$this->userRepository->invalidateResetPasswordRequests($user);
|
||||
|
||||
$this->security->login($user, 'form_login', 'main');
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Your password has been changed.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
return $this->renderSettings(passwordForm: $form);
|
||||
}
|
||||
|
||||
#[Route('/backoffice/settings/email', name: 'tvdt_backoffice_settings_email', methods: ['POST'])]
|
||||
public function changeEmail(Request $request): Response
|
||||
{
|
||||
$user = $this->authenticatedUser;
|
||||
$form = $this->createForm(ChangeEmailFormType::class);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
/** @var string $email */
|
||||
$email = $form->get('email')->getData();
|
||||
|
||||
$found = $this->userRepository->findOneBy(['email' => $email]);
|
||||
if ($found instanceof User && $found !== $user) {
|
||||
$form->get('email')->addError(new FormError($this->translator->trans('There is already an account with this email')));
|
||||
|
||||
return $this->renderSettings(emailForm: $form);
|
||||
}
|
||||
|
||||
$originalEmail = $user->email;
|
||||
$originalIsVerified = $user->isVerified;
|
||||
|
||||
$user->email = $email;
|
||||
$user->isVerified = false;
|
||||
|
||||
try {
|
||||
$this->entityManager->flush();
|
||||
} catch (UniqueConstraintViolationException) {
|
||||
// A concurrent request can claim the email between the uniqueness check above and the flush
|
||||
$user->email = $originalEmail;
|
||||
$user->isVerified = $originalIsVerified;
|
||||
$form->get('email')->addError(new FormError($this->translator->trans('There is already an account with this email')));
|
||||
|
||||
return $this->renderSettings(emailForm: $form);
|
||||
}
|
||||
|
||||
$this->userRepository->invalidateResetPasswordRequests($user);
|
||||
|
||||
if ($this->emailVerifier->sendDefaultConfirmation($user)) {
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Your email address has been changed. Please check your inbox to confirm it.'));
|
||||
} else {
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('Your email address has been changed.'));
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('The confirmation email could not be sent. Please use the resend button to try again.'));
|
||||
}
|
||||
|
||||
$this->security->login($user, 'form_login', 'main');
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
return $this->renderSettings(emailForm: $form);
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('resend_confirmation')]
|
||||
#[Route('/backoffice/settings/resend-confirmation', name: 'tvdt_backoffice_settings_resend_confirmation', methods: ['POST'])]
|
||||
public function resendConfirmationEmail(): RedirectResponse
|
||||
{
|
||||
$user = $this->authenticatedUser;
|
||||
|
||||
if ($user->isVerified) {
|
||||
$this->addFlash(FlashType::Info, $this->translator->trans('Your email address is already confirmed.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
if ($this->emailVerifier->sendDefaultConfirmation($user)) {
|
||||
$this->addFlash(FlashType::Success, $this->translator->trans('A new confirmation email has been sent. Please check your inbox.'));
|
||||
} else {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('The confirmation email could not be sent. Please try again later.'));
|
||||
}
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
#[Route('/backoffice/settings/download-data', name: 'tvdt_backoffice_settings_download_data', methods: ['GET'])]
|
||||
public function downloadData(): Response
|
||||
{
|
||||
if (!$this->authenticatedUser->isVerified) {
|
||||
$this->addFlash(FlashType::Warning, $this->translator->trans('Please confirm your email address before downloading your data.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
$zipPath = $this->dataExportService->exportForUser($this->authenticatedUser);
|
||||
|
||||
$filename = \sprintf(
|
||||
'tijd-voor-de-test-data-%s-%s.zip',
|
||||
FilenameSanitizer::sanitize($this->authenticatedUser->email),
|
||||
new DateTimeImmutable()->format('Y-m-d_H-i-s'),
|
||||
);
|
||||
|
||||
$response = new BinaryFileResponse($zipPath);
|
||||
$response->deleteFileAfterSend(true);
|
||||
$response->headers->set('Content-Type', 'application/zip');
|
||||
$response->headers->set(
|
||||
'Content-Disposition',
|
||||
HeaderUtils::makeDisposition(HeaderUtils::DISPOSITION_ATTACHMENT, $filename),
|
||||
);
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
#[IsCsrfTokenValid('delete_account')]
|
||||
#[Route('/backoffice/settings/delete', name: 'tvdt_backoffice_settings_delete', methods: ['POST'])]
|
||||
public function deleteAccount(Request $request): Response
|
||||
{
|
||||
$user = $this->authenticatedUser;
|
||||
$password = (string) $request->request->get('password', '');
|
||||
|
||||
if (!$this->passwordHasher->isPasswordValid($user, $password)) {
|
||||
$this->addFlash(FlashType::Danger, $this->translator->trans('Wrong password, your account has not been deleted.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
$this->userRepository->deleteUser($user);
|
||||
|
||||
return $this->security->logout(false) ?? $this->redirectToRoute('tvdt_login_login');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param FormInterface<array{currentPassword: string, plainPassword: string}|null>|null $passwordForm
|
||||
* @param FormInterface<array{email: string}|null>|null $emailForm
|
||||
*/
|
||||
private function renderSettings(?FormInterface $passwordForm = null, ?FormInterface $emailForm = null): Response
|
||||
{
|
||||
return $this->render('backoffice/settings/index.html.twig', [
|
||||
'passwordForm' => $passwordForm ?? $this->createForm(ChangeUserPasswordFormType::class),
|
||||
'emailForm' => $emailForm ?? $this->createForm(ChangeEmailFormType::class),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ use Tvdt\Security\Voter\SeasonVoter;
|
||||
use function Symfony\Component\Translation\t;
|
||||
|
||||
#[AsController]
|
||||
#[IsGranted('ROLE_USER')]
|
||||
#[IsGranted('IS_AUTHENTICATED')]
|
||||
final class EliminationController extends AbstractController
|
||||
{
|
||||
public function __construct(private readonly TranslatorInterface $translator, private readonly CandidateRepository $candidateRepository) {}
|
||||
|
||||
@@ -5,27 +5,25 @@ declare(strict_types=1);
|
||||
namespace Tvdt\Controller;
|
||||
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Component\Security\Core\User\UserInterface;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
|
||||
use Tvdt\Entity\User;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\RegistrationFormType;
|
||||
use Tvdt\Repository\UserRepository;
|
||||
use Tvdt\Security\EmailVerifier;
|
||||
|
||||
final class RegistrationController extends AbstractController
|
||||
{
|
||||
public function __construct(private readonly EmailVerifier $emailVerifier, private readonly TranslatorInterface $translator, private readonly UserPasswordHasherInterface $userPasswordHasher, private readonly Security $security, private readonly LoggerInterface $logger, private readonly UserRepository $userRepository, private readonly EntityManagerInterface $entityManager) {}
|
||||
public function __construct(private readonly EmailVerifier $emailVerifier, private readonly TranslatorInterface $translator, private readonly UserPasswordHasherInterface $userPasswordHasher, private readonly Security $security, private readonly UserRepository $userRepository, private readonly EntityManagerInterface $entityManager) {}
|
||||
|
||||
#[Route('/register', name: 'tvdt_register')]
|
||||
public function register(
|
||||
@@ -48,17 +46,8 @@ final class RegistrationController extends AbstractController
|
||||
$this->entityManager->persist($user);
|
||||
$this->entityManager->flush();
|
||||
|
||||
try {
|
||||
// generate a signed url and email it to the user
|
||||
$this->emailVerifier->sendEmailConfirmation('tvdt_verify_email', $user,
|
||||
new TemplatedEmail()
|
||||
->to($user->email)
|
||||
->subject($this->translator->trans('Please Confirm your Email'))
|
||||
->htmlTemplate('backoffice/registration/confirmation_email.html.twig'),
|
||||
);
|
||||
} catch (TransportExceptionInterface $e) {
|
||||
$this->logger->error($e->getMessage());
|
||||
}
|
||||
// generate a signed url and email it to the user
|
||||
$this->emailVerifier->sendDefaultConfirmation($user);
|
||||
|
||||
$response = $this->security->login($user, 'form_login', 'main');
|
||||
\assert($response instanceof Response);
|
||||
@@ -95,7 +84,7 @@ final class RegistrationController extends AbstractController
|
||||
return $this->redirectToRoute('tvdt_register');
|
||||
}
|
||||
|
||||
$this->addFlash('success', $this->translator->trans('Your email address has been verified.'));
|
||||
$this->addFlash(FlashType::Success->value, $this->translator->trans('Your email address has been verified.'));
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_index');
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller;
|
||||
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Mailer\MailerInterface;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
|
||||
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
|
||||
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordToken;
|
||||
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
|
||||
use Tvdt\Entity\User;
|
||||
use Tvdt\Enum\FlashType;
|
||||
use Tvdt\Form\ChangePasswordFormType;
|
||||
use Tvdt\Form\ResetPasswordRequestFormType;
|
||||
|
||||
final class ResetPasswordController extends AbstractController
|
||||
{
|
||||
use ResetPasswordControllerTrait;
|
||||
|
||||
public function __construct(
|
||||
private readonly ResetPasswordHelperInterface $resetPasswordHelper,
|
||||
private readonly EntityManagerInterface $entityManager,
|
||||
private readonly MailerInterface $mailer,
|
||||
private readonly TranslatorInterface $translator,
|
||||
private readonly UserPasswordHasherInterface $passwordHasher,
|
||||
) {}
|
||||
|
||||
#[Route('/reset-password', name: 'tvdt_forgot_password_request')]
|
||||
public function request(Request $request): Response
|
||||
{
|
||||
$form = $this->createForm(ResetPasswordRequestFormType::class);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
/** @var string $email */
|
||||
$email = $form->get('email')->getData();
|
||||
|
||||
return $this->processSendingPasswordResetEmail($email, $this->mailer, $this->translator);
|
||||
}
|
||||
|
||||
return $this->render('reset_password/request.html.twig', [
|
||||
'requestForm' => $form,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/reset-password/check-email', name: 'tvdt_check_email')]
|
||||
public function checkEmail(): Response
|
||||
{
|
||||
if (!($resetToken = $this->getTokenObjectFromSession()) instanceof ResetPasswordToken) {
|
||||
$resetToken = $this->resetPasswordHelper->generateFakeResetToken();
|
||||
}
|
||||
|
||||
return $this->render('reset_password/check_email.html.twig', [
|
||||
'resetToken' => $resetToken,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/reset-password/reset/{token}', name: 'tvdt_reset_password')]
|
||||
public function reset(Request $request, ?string $token = null): Response
|
||||
{
|
||||
if ($token) {
|
||||
$this->storeTokenInSession($token);
|
||||
|
||||
return $this->redirectToRoute('tvdt_reset_password');
|
||||
}
|
||||
|
||||
$token = $this->getTokenFromSession();
|
||||
if (null === $token) {
|
||||
throw $this->createNotFoundException('No reset password token found in the URL or in the session.');
|
||||
}
|
||||
|
||||
try {
|
||||
/** @var User $user */
|
||||
$user = $this->resetPasswordHelper->validateTokenAndFetchUser($token);
|
||||
} catch (ResetPasswordExceptionInterface $resetPasswordException) {
|
||||
$this->addFlash(FlashType::Danger->value, \sprintf(
|
||||
'%s - %s',
|
||||
$this->translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, [], 'ResetPasswordBundle'),
|
||||
$this->translator->trans($resetPasswordException->getReason(), [], 'ResetPasswordBundle'),
|
||||
));
|
||||
|
||||
return $this->redirectToRoute('tvdt_forgot_password_request');
|
||||
}
|
||||
|
||||
$form = $this->createForm(ChangePasswordFormType::class);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
$this->resetPasswordHelper->removeResetRequest($token);
|
||||
|
||||
/** @var string $plainPassword */
|
||||
$plainPassword = $form->get('plainPassword')->getData();
|
||||
|
||||
$user->password = $this->passwordHasher->hashPassword($user, $plainPassword);
|
||||
$this->entityManager->flush();
|
||||
|
||||
$this->cleanSessionAfterReset();
|
||||
|
||||
return $this->redirectToRoute('tvdt_backoffice_index');
|
||||
}
|
||||
|
||||
return $this->render('reset_password/reset.html.twig', [
|
||||
'resetForm' => $form,
|
||||
]);
|
||||
}
|
||||
|
||||
private function processSendingPasswordResetEmail(string $emailFormData, MailerInterface $mailer, TranslatorInterface $translator): RedirectResponse
|
||||
{
|
||||
$user = $this->entityManager->getRepository(User::class)->findOneBy([
|
||||
'email' => $emailFormData,
|
||||
]);
|
||||
|
||||
if (!$user instanceof User) {
|
||||
return $this->redirectToRoute('tvdt_check_email');
|
||||
}
|
||||
|
||||
try {
|
||||
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
|
||||
} catch (ResetPasswordExceptionInterface) {
|
||||
return $this->redirectToRoute('tvdt_check_email');
|
||||
}
|
||||
|
||||
$email = new TemplatedEmail()
|
||||
->to($user->getUserIdentifier())
|
||||
->subject($translator->trans('Your password reset request'))
|
||||
->htmlTemplate('reset_password/email.html.twig')
|
||||
->context([
|
||||
'resetToken' => $resetToken,
|
||||
]);
|
||||
|
||||
$mailer->send($email);
|
||||
|
||||
$this->setTokenObjectInSession($resetToken);
|
||||
|
||||
return $this->redirectToRoute('tvdt_check_email');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Controller;
|
||||
|
||||
use Safe\DateTimeImmutable;
|
||||
use Safe\Exceptions\DatetimeException;
|
||||
use Symfony\Component\DependencyInjection\Attribute\Autowire;
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
|
||||
/** Serves well-known URIs (https://www.rfc-editor.org/rfc/rfc8615). */
|
||||
final class WellKnownController extends AbstractController
|
||||
{
|
||||
public function __construct(
|
||||
#[Autowire(env: 'default::BUILD_TIME')]
|
||||
private readonly ?string $buildTime,
|
||||
#[Autowire(env: 'APP_ENV')]
|
||||
private readonly string $appEnv,
|
||||
) {}
|
||||
|
||||
/** @see https://w3c.github.io/webappsec-change-password-url/ */
|
||||
#[Route('/.well-known/change-password', name: 'tvdt_well_known_change_password', methods: ['GET'])]
|
||||
public function changePassword(): RedirectResponse
|
||||
{
|
||||
return $this->redirectToRoute('tvdt_backoffice_settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* @see https://www.rfc-editor.org/rfc/rfc9116
|
||||
*
|
||||
* @throws DatetimeException
|
||||
* @throws \Exception
|
||||
*/
|
||||
#[Route('/.well-known/security.txt', name: 'tvdt_well_known_security_txt', methods: ['GET'])]
|
||||
public function securityTxt(): Response
|
||||
{
|
||||
// One year after the container build, so the file goes stale when deployments stop.
|
||||
// In prod the build arg must be set; falling back to 'now' would renew Expires on every request,
|
||||
// defeating the go-stale purpose. In dev/test 'now' is fine — no build bake happens there.
|
||||
if ((null === $this->buildTime || '' === $this->buildTime) && 'prod' === $this->appEnv) {
|
||||
throw new \LogicException('BUILD_TIME env var must be set in production (baked in during Docker build).');
|
||||
}
|
||||
|
||||
$buildTime = (null !== $this->buildTime && '' !== $this->buildTime) ? $this->buildTime : 'now';
|
||||
$expires = new DateTimeImmutable($buildTime)->modify('+1 year')->format(\DATE_RFC3339);
|
||||
|
||||
$content = <<<TXT
|
||||
Contact: https://github.com/MarijnDoeve/TijdVoorDeTest/security/advisories/new
|
||||
Expires: {$expires}
|
||||
Preferred-Languages: nl, en
|
||||
|
||||
TXT;
|
||||
|
||||
return new Response($content, headers: ['Content-Type' => 'text/plain; charset=UTF-8']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\DataFixtures;
|
||||
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Tvdt\Entity\User;
|
||||
|
||||
final class DevFixtures extends Fixture implements FixtureGroupInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly UserPasswordHasherInterface $passwordHasher,
|
||||
) {}
|
||||
|
||||
public static function getGroups(): array
|
||||
{
|
||||
return ['dev'];
|
||||
}
|
||||
|
||||
public function load(ObjectManager $manager): void
|
||||
{
|
||||
$user = new User();
|
||||
$user->email = 'admin@tijdvoordetest.nl';
|
||||
$user->password = $this->passwordHasher->hashPassword($user, '12345678');
|
||||
$user->roles = ['ROLE_ADMIN'];
|
||||
|
||||
$manager->persist($user);
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,14 @@ namespace Tvdt\DataFixtures;
|
||||
use Doctrine\Bundle\FixturesBundle\Fixture;
|
||||
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
use Safe\DateTimeImmutable;
|
||||
use Tvdt\Entity\Answer;
|
||||
use Tvdt\Entity\BankAnswer;
|
||||
use Tvdt\Entity\BankQuestion;
|
||||
use Tvdt\Entity\BankQuestionUsage;
|
||||
use Tvdt\Entity\Candidate;
|
||||
use Tvdt\Entity\Question;
|
||||
use Tvdt\Entity\QuestionLabel;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Entity\SeasonSettings;
|
||||
@@ -18,6 +23,16 @@ final class KrtekFixtures extends Fixture implements FixtureGroupInterface
|
||||
{
|
||||
public const string KRTEK_SEASON = 'krtek-seaspm';
|
||||
|
||||
public const string KRTEK_QUIZ_1 = 'krtek-quiz-1';
|
||||
|
||||
public const string KRTEK_QUIZ_2 = 'krtek-quiz-2';
|
||||
|
||||
public const string BANK_QUESTION_REUSABLE = 'bank-question-reusable';
|
||||
|
||||
public const string BANK_QUESTION_USED = 'bank-question-used';
|
||||
|
||||
public const string BANK_QUESTION_UNUSED = 'bank-question-unused';
|
||||
|
||||
public static function getGroups(): array
|
||||
{
|
||||
return ['test', 'dev'];
|
||||
@@ -47,16 +62,68 @@ final class KrtekFixtures extends Fixture implements FixtureGroupInterface
|
||||
$quiz1 = $this->createQuiz1($season);
|
||||
$season->addQuiz($quiz1);
|
||||
$season->activeQuiz = $quiz1;
|
||||
$season->addQuiz($this->createQuiz2($season));
|
||||
|
||||
$quiz1->finalizedAt = new DateTimeImmutable();
|
||||
$quiz2 = $this->createQuiz2($season);
|
||||
$season->addQuiz($quiz2);
|
||||
|
||||
\assert($season->settings instanceof SeasonSettings);
|
||||
|
||||
$season->settings->confirmAnswers = true;
|
||||
$season->settings->showNumbers = true;
|
||||
|
||||
$this->createQuestionBank($season, $quiz2);
|
||||
|
||||
$manager->flush();
|
||||
|
||||
$this->addReference(self::KRTEK_SEASON, $season);
|
||||
$this->addReference(self::KRTEK_QUIZ_1, $quiz1);
|
||||
$this->addReference(self::KRTEK_QUIZ_2, $quiz2);
|
||||
}
|
||||
|
||||
private function createQuestionBank(Season $season, Quiz $usedInQuiz): void
|
||||
{
|
||||
$location = new QuestionLabel('Locatie');
|
||||
$location->slug = 'locatie';
|
||||
|
||||
$season->addQuestionLabel($location);
|
||||
$finale = new QuestionLabel('Finale');
|
||||
$finale->slug = 'finale';
|
||||
|
||||
$season->addQuestionLabel($finale);
|
||||
|
||||
$reusable = new BankQuestion();
|
||||
$reusable->question = 'Wie is de Krtek?';
|
||||
$reusable->reusable = true;
|
||||
$reusable->addLabel($finale);
|
||||
$reusable->addAnswer(new BankAnswer('Claudia', true));
|
||||
$reusable->addAnswer(new BankAnswer('Eelco'));
|
||||
$reusable->addAnswer(new BankAnswer('Elise'));
|
||||
|
||||
$season->addBankQuestion($reusable);
|
||||
|
||||
$used = new BankQuestion();
|
||||
$used->question = 'Waar sliep de Krtek?';
|
||||
$used->addLabel($location);
|
||||
$used->addAnswer(new BankAnswer('Boven', true));
|
||||
$used->addAnswer(new BankAnswer('Beneden'));
|
||||
$used->addUsage(new BankQuestionUsage($used, $usedInQuiz));
|
||||
|
||||
$season->addBankQuestion($used);
|
||||
|
||||
$unused = new BankQuestion();
|
||||
$unused->question = 'Wat at de Krtek als ontbijt?';
|
||||
$unused->addLabel($location);
|
||||
$unused->addLabel($finale);
|
||||
$unused->addAnswer(new BankAnswer('Brood', true));
|
||||
$unused->addAnswer(new BankAnswer('Yoghurt'));
|
||||
$unused->addAnswer(new BankAnswer('Niks'));
|
||||
|
||||
$season->addBankQuestion($unused);
|
||||
|
||||
$this->addReference(self::BANK_QUESTION_REUSABLE, $reusable);
|
||||
$this->addReference(self::BANK_QUESTION_USED, $used);
|
||||
$this->addReference(self::BANK_QUESTION_UNUSED, $unused);
|
||||
}
|
||||
|
||||
private function createQuiz1(Season $season): Quiz
|
||||
|
||||
@@ -9,6 +9,10 @@ use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
|
||||
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Tvdt\Entity\Answer;
|
||||
use Tvdt\Entity\Candidate;
|
||||
use Tvdt\Entity\Question;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Entity\User;
|
||||
|
||||
@@ -70,6 +74,33 @@ final class TestFixtures extends Fixture implements FixtureGroupInterface, Depen
|
||||
$krtek->addOwner($user);
|
||||
$anotherSeason->addOwner($user);
|
||||
|
||||
$soleOwner = new User();
|
||||
$soleOwner->email = 'sole-owner@example.org';
|
||||
$soleOwner->password = $this->passwordHasher->hashPassword($soleOwner, self::PASSWORD);
|
||||
|
||||
$manager->persist($soleOwner);
|
||||
|
||||
$doomedSeason = new Season();
|
||||
$doomedSeason->name = 'Doomed Season';
|
||||
$doomedSeason->seasonCode = 'doomd';
|
||||
$doomedSeason->addCandidate(new Candidate('Vera'));
|
||||
|
||||
$quiz = new Quiz();
|
||||
$quiz->name = 'Doomed Quiz';
|
||||
|
||||
$question = new Question();
|
||||
$question->question = 'Wie is de Krtek?';
|
||||
$question->ordering = 1;
|
||||
$question->addAnswer(new Answer('Vera', true));
|
||||
|
||||
$quiz->addQuestion($question);
|
||||
$doomedSeason->addQuiz($quiz);
|
||||
|
||||
$manager->persist($doomedSeason);
|
||||
|
||||
$doomedSeason->addOwner($soleOwner);
|
||||
$anotherSeason->addOwner($soleOwner);
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
|
||||
#[ORM\MappedSuperclass]
|
||||
abstract class AbstractBaseAnswer implements \Stringable
|
||||
{
|
||||
#[ORM\Column(type: Types::SMALLINT, options: ['default' => 0])]
|
||||
public int $ordering = 0;
|
||||
|
||||
public function __construct(
|
||||
#[ORM\Column(length: 255)]
|
||||
public string $text,
|
||||
#[ORM\Column]
|
||||
public bool $isRightAnswer = false,
|
||||
) {}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->text;
|
||||
}
|
||||
}
|
||||
+4
-16
@@ -6,14 +6,13 @@ namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Tvdt\Repository\AnswerRepository;
|
||||
|
||||
#[ORM\Entity(repositoryClass: AnswerRepository::class)]
|
||||
class Answer implements \Stringable
|
||||
class Answer extends AbstractBaseAnswer
|
||||
{
|
||||
#[ORM\Column(type: UuidType::NAME)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
@@ -21,9 +20,6 @@ class Answer implements \Stringable
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
#[ORM\Column(type: Types::SMALLINT, options: ['default' => 0])]
|
||||
public int $ordering = 0;
|
||||
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne(inversedBy: 'answers')]
|
||||
public Question $question;
|
||||
@@ -36,12 +32,9 @@ class Answer implements \Stringable
|
||||
#[ORM\OneToMany(targetEntity: GivenAnswer::class, mappedBy: 'answer', orphanRemoval: true)]
|
||||
public private(set) Collection $givenAnswers;
|
||||
|
||||
public function __construct(
|
||||
#[ORM\Column(length: 255)]
|
||||
public string $text,
|
||||
#[ORM\Column]
|
||||
public bool $isRightAnswer = false,
|
||||
) {
|
||||
public function __construct(string $text, bool $isRightAnswer = false)
|
||||
{
|
||||
parent::__construct($text, $isRightAnswer);
|
||||
$this->candidates = new ArrayCollection();
|
||||
$this->givenAnswers = new ArrayCollection();
|
||||
}
|
||||
@@ -57,9 +50,4 @@ class Answer implements \Stringable
|
||||
{
|
||||
$this->candidates->removeElement($candidate);
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->text;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\ObjectMapper\Attribute\Map;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity]
|
||||
class BankAnswer extends AbstractBaseAnswer
|
||||
{
|
||||
#[Map(if: false)]
|
||||
#[ORM\Column(type: UuidType::NAME)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
#[Map(if: false)]
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne(inversedBy: 'answers')]
|
||||
public BankQuestion $bankQuestion;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\ObjectMapper\Attribute\Map;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Symfony\Component\Validator\Constraints as Assert;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
use Tvdt\Repository\BankQuestionRepository;
|
||||
|
||||
#[Gedmo\Loggable(logEntryClass: LogEntry::class)]
|
||||
#[ORM\Entity(repositoryClass: BankQuestionRepository::class)]
|
||||
class BankQuestion implements \Stringable
|
||||
{
|
||||
#[Map(if: false)]
|
||||
#[ORM\Column(type: UuidType::NAME)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
#[Gedmo\Versioned]
|
||||
#[ORM\Column(length: 255)]
|
||||
public string $question;
|
||||
|
||||
#[Map(if: false)]
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne(inversedBy: 'bankQuestions')]
|
||||
public Season $season;
|
||||
|
||||
#[Gedmo\Versioned]
|
||||
#[Map(if: false)]
|
||||
#[ORM\Column(options: ['default' => false])]
|
||||
public bool $reusable = false;
|
||||
|
||||
/** @var Collection<int, QuestionLabel> */
|
||||
#[Map(if: false)]
|
||||
#[ORM\ManyToMany(targetEntity: QuestionLabel::class, inversedBy: 'bankQuestions')]
|
||||
public private(set) Collection $labels;
|
||||
|
||||
/** @var Collection<int, BankAnswer> */
|
||||
#[Map(if: false)]
|
||||
#[ORM\OneToMany(targetEntity: BankAnswer::class, mappedBy: 'bankQuestion', cascade: ['persist'], orphanRemoval: true)]
|
||||
#[ORM\OrderBy(['ordering' => 'ASC'])]
|
||||
public private(set) Collection $answers;
|
||||
|
||||
/** @var Collection<int, BankQuestionUsage> */
|
||||
#[Map(if: false)]
|
||||
#[ORM\OneToMany(targetEntity: BankQuestionUsage::class, mappedBy: 'bankQuestion', cascade: ['persist'], orphanRemoval: true)]
|
||||
public private(set) Collection $usages;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->labels = new ArrayCollection();
|
||||
$this->answers = new ArrayCollection();
|
||||
$this->usages = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function addAnswer(BankAnswer $answer): static
|
||||
{
|
||||
if (!$this->answers->contains($answer)) {
|
||||
$this->answers->add($answer);
|
||||
$answer->bankQuestion = $this;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeAnswer(BankAnswer $answer): static
|
||||
{
|
||||
$this->answers->removeElement($answer);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addLabel(QuestionLabel $label): static
|
||||
{
|
||||
if (!$this->labels->contains($label)) {
|
||||
$this->labels->add($label);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeLabel(QuestionLabel $label): static
|
||||
{
|
||||
$this->labels->removeElement($label);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addUsage(BankQuestionUsage $usage): static
|
||||
{
|
||||
if (!$this->usages->contains($usage)) {
|
||||
$this->usages->add($usage);
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public bool $isUsed {
|
||||
get => !$this->usages->isEmpty();
|
||||
}
|
||||
|
||||
public bool $canBeAssigned {
|
||||
get => $this->reusable || !$this->isUsed;
|
||||
}
|
||||
|
||||
/** True when the question is fully complete and can be assigned to a quiz. */
|
||||
public bool $isCompleteForQuiz {
|
||||
get => $this->answers->count() >= 2
|
||||
&& 1 === $this->answers->filter(static fn (BankAnswer $answer): bool => $answer->isRightAnswer)->count();
|
||||
}
|
||||
|
||||
public function isUsedInQuiz(Quiz $quiz): bool
|
||||
{
|
||||
return $this->usages->exists(static fn (int $key, BankQuestionUsage $usage): bool => $usage->quiz === $quiz);
|
||||
}
|
||||
|
||||
#[Assert\Callback]
|
||||
public function validateAnswers(ExecutionContextInterface $context): void
|
||||
{
|
||||
if ($this->answers->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->answers->filter(static fn (BankAnswer $answer): bool => $answer->isRightAnswer)->count();
|
||||
|
||||
if ($this->answers->count() < 2) {
|
||||
$context->buildViolation('A question needs at least two answers')
|
||||
->atPath('answers')
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->question;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Mapping\Annotation as Gedmo;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
#[ORM\Entity]
|
||||
#[ORM\UniqueConstraint(fields: ['bankQuestion', 'quiz'])]
|
||||
class BankQuestionUsage
|
||||
{
|
||||
#[ORM\Column(type: UuidType::NAME)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
#[Gedmo\Timestampable(on: 'create')]
|
||||
#[ORM\Column(type: Types::DATETIMETZ_IMMUTABLE, nullable: false)]
|
||||
public private(set) \DateTimeImmutable $created;
|
||||
|
||||
#[ORM\JoinColumn(nullable: true, onDelete: 'SET NULL')]
|
||||
#[ORM\ManyToOne]
|
||||
public ?Question $question = null;
|
||||
|
||||
public function __construct(
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne(inversedBy: 'usages')]
|
||||
public private(set) BankQuestion $bankQuestion,
|
||||
|
||||
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
|
||||
#[ORM\ManyToOne]
|
||||
public private(set) Quiz $quiz,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Gedmo\Loggable\Entity\MappedSuperclass\AbstractLogEntry;
|
||||
use Gedmo\Loggable\Entity\Repository\LogEntryRepository;
|
||||
|
||||
/**
|
||||
* Custom LogEntry that stores change data as JSON (instead of serialized `array`)
|
||||
* so it works with the PostgreSQL-only DBAL setup in this project.
|
||||
*
|
||||
* @extends AbstractLogEntry<object>
|
||||
*/
|
||||
#[ORM\Entity(repositoryClass: LogEntryRepository::class)]
|
||||
#[ORM\Index(name: 'log_class_lookup_idx', columns: ['object_class'])]
|
||||
#[ORM\Index(name: 'log_date_lookup_idx', columns: ['logged_at'])]
|
||||
#[ORM\Index(name: 'log_user_lookup_idx', columns: ['username'])]
|
||||
#[ORM\Index(name: 'log_version_lookup_idx', columns: ['object_id', 'object_class', 'version'])]
|
||||
#[ORM\Table(name: 'ext_log_entries')]
|
||||
class LogEntry extends AbstractLogEntry
|
||||
{
|
||||
#[ORM\Column(type: Types::JSON, nullable: true)]
|
||||
#[\Override]
|
||||
protected $data;
|
||||
}
|
||||
@@ -54,6 +54,13 @@ class Question implements \Stringable
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function removeAnswer(Answer $answer): static
|
||||
{
|
||||
$this->answers->removeElement($answer);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->question ?? '';
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Tvdt\Enum\LabelColour;
|
||||
use Tvdt\Repository\QuestionLabelRepository;
|
||||
|
||||
#[ORM\Entity(repositoryClass: QuestionLabelRepository::class)]
|
||||
#[ORM\UniqueConstraint(fields: ['name', 'season'])]
|
||||
#[ORM\UniqueConstraint(name: 'uq_question_label_slug_season', fields: ['slug', 'season'])]
|
||||
class QuestionLabel implements \Stringable
|
||||
{
|
||||
#[ORM\Column(type: UuidType::NAME)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne(inversedBy: 'questionLabels')]
|
||||
public Season $season;
|
||||
|
||||
/** @var Collection<int, BankQuestion> */
|
||||
#[ORM\ManyToMany(targetEntity: BankQuestion::class, mappedBy: 'labels')]
|
||||
public private(set) Collection $bankQuestions;
|
||||
|
||||
#[ORM\Column(length: 16, enumType: LabelColour::class, options: ['default' => 'secondary'])]
|
||||
public LabelColour $colour = LabelColour::Gray;
|
||||
|
||||
#[ORM\Column(length: 64)]
|
||||
public string $slug = '';
|
||||
|
||||
public function __construct(
|
||||
#[ORM\Column(length: 64)]
|
||||
public string $name,
|
||||
) {
|
||||
$this->bankQuestions = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function __toString(): string
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\Common\Collections\ArrayCollection;
|
||||
use Doctrine\Common\Collections\Collection;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
@@ -40,6 +41,9 @@ class Quiz
|
||||
#[ORM\Column(nullable: false, options: ['default' => 1])]
|
||||
public int $dropouts = 1;
|
||||
|
||||
#[ORM\Column(type: Types::DATETIMETZ_IMMUTABLE, nullable: true)]
|
||||
public ?\DateTimeImmutable $finalizedAt = null;
|
||||
|
||||
/** @var Collection<int, Elimination> */
|
||||
#[ORM\OneToMany(targetEntity: Elimination::class, mappedBy: 'quiz', cascade: ['persist'], orphanRemoval: true)]
|
||||
#[ORM\OrderBy(['createdAt' => 'DESC'])]
|
||||
@@ -62,6 +66,19 @@ class Quiz
|
||||
return $this;
|
||||
}
|
||||
|
||||
public bool $isFinalized {
|
||||
get => $this->finalizedAt instanceof \DateTimeImmutable;
|
||||
}
|
||||
|
||||
public bool $hasStartedCandidates {
|
||||
get => $this->candidateData->exists(static fn (int $key, QuizCandidate $quizCandidate): bool => $quizCandidate->started instanceof \DateTimeImmutable);
|
||||
}
|
||||
|
||||
/** A locked quiz can no longer be altered: it is either explicitly finalized or a candidate has already started filling it in. */
|
||||
public bool $isLocked {
|
||||
get => $this->isFinalized || $this->hasStartedCandidates;
|
||||
}
|
||||
|
||||
public function addElimination(Elimination $elimination): self
|
||||
{
|
||||
$this->eliminations->add($elimination);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Entity;
|
||||
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Bridge\Doctrine\Types\UuidType;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
|
||||
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait;
|
||||
use Tvdt\Repository\ResetPasswordRequestRepository;
|
||||
|
||||
#[ORM\Entity(repositoryClass: ResetPasswordRequestRepository::class)]
|
||||
class ResetPasswordRequest implements ResetPasswordRequestInterface
|
||||
{
|
||||
use ResetPasswordRequestTrait;
|
||||
|
||||
#[ORM\Column(type: UuidType::NAME, unique: true)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
#[ORM\Id]
|
||||
public private(set) Uuid $id;
|
||||
|
||||
public function __construct(#[ORM\JoinColumn(nullable: false)]
|
||||
#[ORM\ManyToOne]
|
||||
private User $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken)
|
||||
{
|
||||
$this->initialize($expiresAt, $selector, $hashedToken);
|
||||
}
|
||||
|
||||
public function getUser(): User
|
||||
{
|
||||
return $this->user;
|
||||
}
|
||||
}
|
||||
@@ -51,12 +51,24 @@ class Season
|
||||
#[ORM\OneToOne(cascade: ['persist', 'remove'])]
|
||||
public ?SeasonSettings $settings = null;
|
||||
|
||||
/** @var Collection<int, BankQuestion> */
|
||||
#[ORM\OneToMany(targetEntity: BankQuestion::class, mappedBy: 'season', cascade: ['persist'], orphanRemoval: true)]
|
||||
#[ORM\OrderBy(['question' => 'ASC'])]
|
||||
public private(set) Collection $bankQuestions;
|
||||
|
||||
/** @var Collection<int, QuestionLabel> */
|
||||
#[ORM\OneToMany(targetEntity: QuestionLabel::class, mappedBy: 'season', cascade: ['persist'], orphanRemoval: true)]
|
||||
#[ORM\OrderBy(['name' => 'ASC'])]
|
||||
public private(set) Collection $questionLabels;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->settings = new SeasonSettings();
|
||||
$this->quizzes = new ArrayCollection();
|
||||
$this->candidates = new ArrayCollection();
|
||||
$this->owners = new ArrayCollection();
|
||||
$this->bankQuestions = new ArrayCollection();
|
||||
$this->questionLabels = new ArrayCollection();
|
||||
}
|
||||
|
||||
public function addQuiz(Quiz $quiz): static
|
||||
@@ -79,6 +91,26 @@ class Season
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addBankQuestion(BankQuestion $bankQuestion): static
|
||||
{
|
||||
if (!$this->bankQuestions->contains($bankQuestion)) {
|
||||
$this->bankQuestions->add($bankQuestion);
|
||||
$bankQuestion->season = $this;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addQuestionLabel(QuestionLabel $questionLabel): static
|
||||
{
|
||||
if (!$this->questionLabels->contains($questionLabel)) {
|
||||
$this->questionLabels->add($questionLabel);
|
||||
$questionLabel->season = $this;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function addOwner(User $owner): static
|
||||
{
|
||||
if (!$this->owners->contains($owner)) {
|
||||
|
||||
@@ -21,6 +21,10 @@ use Tvdt\Repository\UserRepository;
|
||||
#[UniqueEntity(fields: ['email'], message: 'There is already an account with this email')]
|
||||
class User implements UserInterface, PasswordAuthenticatedUserInterface
|
||||
{
|
||||
public const int PASSWORD_MIN_LENGTH = 8;
|
||||
|
||||
public const int PASSWORD_MAX_LENGTH = 4096;
|
||||
|
||||
#[ORM\Column(type: UuidType::NAME, unique: true)]
|
||||
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
|
||||
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Enum;
|
||||
|
||||
use Symfony\Component\Translation\TranslatableMessage;
|
||||
|
||||
enum LabelColour: string
|
||||
{
|
||||
case Blue = 'primary';
|
||||
case Gray = 'secondary';
|
||||
case Green = 'success';
|
||||
case Red = 'danger';
|
||||
case Yellow = 'warning';
|
||||
case Cyan = 'info';
|
||||
case White = 'light';
|
||||
|
||||
public function label(): TranslatableMessage
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blue => new TranslatableMessage('Blue'),
|
||||
self::Gray => new TranslatableMessage('Gray'),
|
||||
self::Green => new TranslatableMessage('Green'),
|
||||
self::Red => new TranslatableMessage('Red'),
|
||||
self::Yellow => new TranslatableMessage('Yellow'),
|
||||
self::Cyan => new TranslatableMessage('Cyan'),
|
||||
self::White => new TranslatableMessage('White'),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Exception;
|
||||
|
||||
class BankQuestionAlreadyUsedException extends \Exception {}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Exception;
|
||||
|
||||
class BankQuestionIncompleteException extends \Exception {}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Exception;
|
||||
|
||||
class QuizLockedException extends \Exception {}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
|
||||
/**
|
||||
* @template TAnswer of object
|
||||
*
|
||||
* @extends AbstractType<TAnswer>
|
||||
*/
|
||||
abstract class AbstractBaseAnswerFormType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('ordering', HiddenType::class, ['empty_data' => '0'])
|
||||
->add('text', TextType::class, [
|
||||
'label' => false,
|
||||
'attr' => ['placeholder' => 'Answer', 'maxlength' => 255],
|
||||
])
|
||||
->add('isRightAnswer', CheckboxType::class, [
|
||||
'label' => 'Correct',
|
||||
'required' => false,
|
||||
])
|
||||
;
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,9 @@ class AddCandidatesFormType extends AbstractType
|
||||
{
|
||||
$builder
|
||||
->add('candidates', TextareaType::class, [
|
||||
'label' => $this->translator->trans('Candidates'), 'translation_domain' => false,
|
||||
'label' => $this->translator->trans('Candidates'),
|
||||
'help' => $this->translator->trans('One candidate per line'),
|
||||
'translation_domain' => false,
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Tvdt\Entity\Answer;
|
||||
|
||||
/** @extends AbstractBaseAnswerFormType<Answer> */
|
||||
class AnswerFormType extends AbstractBaseAnswerFormType
|
||||
{
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => Answer::class,
|
||||
'empty_data' => static fn (): Answer => new Answer(''),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Tvdt\Entity\BankAnswer;
|
||||
|
||||
/** @extends AbstractBaseAnswerFormType<BankAnswer> */
|
||||
class BankAnswerFormType extends AbstractBaseAnswerFormType
|
||||
{
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => BankAnswer::class,
|
||||
'empty_data' => static fn (): BankAnswer => new BankAnswer(''),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Tvdt\Entity\BankQuestion;
|
||||
use Tvdt\Entity\QuestionLabel;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Repository\QuestionLabelRepository;
|
||||
|
||||
/** @extends AbstractType<BankQuestion> */
|
||||
class BankQuestionFormType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
/** @var Season $season */
|
||||
$season = $options['season'];
|
||||
|
||||
$builder
|
||||
->add('question', TextType::class, [
|
||||
'label' => 'Question',
|
||||
'attr' => ['maxlength' => 255],
|
||||
])
|
||||
->add('reusable', CheckboxType::class, [
|
||||
'label' => 'Reusable',
|
||||
'required' => false,
|
||||
'label_attr' => ['class' => 'checkbox-switch'],
|
||||
'attr' => ['role' => 'switch', 'switch' => null],
|
||||
])
|
||||
->add('labels', EntityType::class, [
|
||||
'label' => 'Labels',
|
||||
'class' => QuestionLabel::class,
|
||||
'multiple' => true,
|
||||
'expanded' => true,
|
||||
'required' => false,
|
||||
'choice_attr' => static fn (QuestionLabel $label): array => ['data-colour' => $label->colour->value],
|
||||
'query_builder' => static fn (QuestionLabelRepository $repository): QueryBuilder => $repository
|
||||
->createQueryBuilder('l')
|
||||
->where('l.season = :season')
|
||||
->orderBy('l.name', 'ASC')
|
||||
->setParameter('season', $season),
|
||||
])
|
||||
->add('answers', CollectionType::class, [
|
||||
'label' => 'Answers',
|
||||
'entry_type' => BankAnswerFormType::class,
|
||||
'entry_options' => ['label' => false],
|
||||
'allow_add' => true,
|
||||
'allow_delete' => true,
|
||||
'by_reference' => false,
|
||||
'prototype' => true,
|
||||
])
|
||||
->add('save', SubmitType::class, [
|
||||
'label' => 'Save',
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => BankQuestion::class,
|
||||
]);
|
||||
$resolver->setRequired('season');
|
||||
$resolver->setAllowedTypes('season', Season::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EmailType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Validator\Constraints\Email;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/** @extends AbstractType<array{email: string}> */
|
||||
final class ChangeEmailFormType extends AbstractType
|
||||
{
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('email', EmailType::class, [
|
||||
'label' => $this->translator->trans('New email address'),
|
||||
'attr' => ['autocomplete' => 'email'],
|
||||
'mapped' => false,
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter an email address'),
|
||||
new Email(),
|
||||
],
|
||||
'translation_domain' => false,
|
||||
])
|
||||
->add('save', SubmitType::class, [
|
||||
'label' => $this->translator->trans('Change email'),
|
||||
'translation_domain' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Validator\Constraints\Length;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Entity\User;
|
||||
|
||||
/** @extends AbstractType<array{plainPassword: string}> */
|
||||
final class ChangePasswordFormType extends AbstractType
|
||||
{
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('plainPassword', RepeatedType::class, [
|
||||
'type' => PasswordType::class,
|
||||
'options' => [
|
||||
'attr' => ['autocomplete' => 'new-password'],
|
||||
],
|
||||
'first_options' => [
|
||||
'label' => $this->translator->trans('New password'),
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter a password'),
|
||||
new Length(
|
||||
min: User::PASSWORD_MIN_LENGTH,
|
||||
max: User::PASSWORD_MAX_LENGTH,
|
||||
minMessage: 'Your password should be at least {{ limit }} characters',
|
||||
),
|
||||
],
|
||||
],
|
||||
'second_options' => [
|
||||
'label' => $this->translator->trans('Repeat Password'),
|
||||
],
|
||||
'invalid_message' => $this->translator->trans('The password fields must match.'),
|
||||
'mapped' => false,
|
||||
'translation_domain' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
|
||||
use Symfony\Component\Validator\Constraints\Length;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use Tvdt\Entity\User;
|
||||
|
||||
/** @extends AbstractType<array{currentPassword: string, plainPassword: string}> */
|
||||
final class ChangeUserPasswordFormType extends AbstractType
|
||||
{
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('currentPassword', PasswordType::class, [
|
||||
'label' => $this->translator->trans('Current password'),
|
||||
'attr' => ['autocomplete' => 'current-password'],
|
||||
'mapped' => false,
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter your current password'),
|
||||
new UserPassword(message: 'This is not your current password.'),
|
||||
],
|
||||
'translation_domain' => false,
|
||||
])
|
||||
->add('plainPassword', RepeatedType::class, [
|
||||
'type' => PasswordType::class,
|
||||
'options' => [
|
||||
'attr' => ['autocomplete' => 'new-password'],
|
||||
],
|
||||
'first_options' => [
|
||||
'label' => $this->translator->trans('New password'),
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter a password'),
|
||||
new Length(
|
||||
min: User::PASSWORD_MIN_LENGTH,
|
||||
max: User::PASSWORD_MAX_LENGTH,
|
||||
minMessage: 'Your password should be at least {{ limit }} characters',
|
||||
),
|
||||
],
|
||||
],
|
||||
'second_options' => [
|
||||
'label' => $this->translator->trans('Repeat Password'),
|
||||
],
|
||||
'invalid_message' => $this->translator->trans('The password fields must match.'),
|
||||
'mapped' => false,
|
||||
'translation_domain' => false,
|
||||
])
|
||||
->add('save', SubmitType::class, [
|
||||
'label' => $this->translator->trans('Change password'),
|
||||
'translation_domain' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Tvdt\Entity\Question;
|
||||
|
||||
/** @extends AbstractType<Question> */
|
||||
class QuestionFormType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('question', TextType::class, [
|
||||
'label' => 'Question',
|
||||
'attr' => ['maxlength' => 255],
|
||||
])
|
||||
->add('answers', CollectionType::class, [
|
||||
'label' => 'Answers',
|
||||
'entry_type' => AnswerFormType::class,
|
||||
'entry_options' => ['label' => false],
|
||||
'allow_add' => true,
|
||||
'allow_delete' => true,
|
||||
'by_reference' => false,
|
||||
'prototype' => true,
|
||||
])
|
||||
->add('save', SubmitType::class, [
|
||||
'label' => 'Save',
|
||||
])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => Question::class,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ class RegistrationFormType extends AbstractType
|
||||
'mapped' => false,
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter a password'),
|
||||
new Length(min: 8, max: 4096, minMessage: 'Your password should be at least {{ limit }} characters'),
|
||||
new Length(min: User::PASSWORD_MIN_LENGTH, max: User::PASSWORD_MAX_LENGTH, minMessage: 'Your password should be at least {{ limit }} characters'),
|
||||
],
|
||||
'translation_domain' => false,
|
||||
])
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Form;
|
||||
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EmailType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Validator\Constraints\NotBlank;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
|
||||
/** @extends AbstractType<array{email: string}> */
|
||||
final class ResetPasswordRequestFormType extends AbstractType
|
||||
{
|
||||
public function __construct(private readonly TranslatorInterface $translator) {}
|
||||
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('email', EmailType::class, [
|
||||
'label' => $this->translator->trans('Email'),
|
||||
'attr' => ['autocomplete' => 'email'],
|
||||
'translation_domain' => false,
|
||||
'constraints' => [
|
||||
new NotBlank(message: 'Please enter your email'),
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Helpers;
|
||||
|
||||
use Symfony\Component\String\Slugger\AsciiSlugger;
|
||||
|
||||
class FilenameSanitizer
|
||||
{
|
||||
/** Slugs user-supplied text (e.g. a season/quiz name) into a string safe to use as a zip entry path segment or a downloaded filename. */
|
||||
public static function sanitize(string $value): string
|
||||
{
|
||||
$slug = new AsciiSlugger()->slug($value)->toString();
|
||||
|
||||
return '' === $slug ? 'unnamed' : $slug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Repository;
|
||||
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Tvdt\Entity\BankQuestion;
|
||||
use Tvdt\Entity\QuestionLabel;
|
||||
use Tvdt\Entity\Season;
|
||||
|
||||
/** @extends ServiceEntityRepository<BankQuestion> */
|
||||
class BankQuestionRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, BankQuestion::class);
|
||||
}
|
||||
|
||||
/** @return list<BankQuestion> */
|
||||
public function findBySeason(Season $season, ?QuestionLabel $label = null): array
|
||||
{
|
||||
$queryBuilder = $this->createQueryBuilder('bq')
|
||||
->where('bq.season = :season')
|
||||
->orderBy('bq.question', 'ASC')
|
||||
->setParameter('season', $season);
|
||||
|
||||
if ($label instanceof QuestionLabel) {
|
||||
$queryBuilder
|
||||
->andWhere(':label member of bq.labels')
|
||||
->setParameter('label', $label);
|
||||
}
|
||||
|
||||
/** @var list<BankQuestion> $questions */
|
||||
$questions = $queryBuilder->getQuery()->getResult();
|
||||
|
||||
if ([] === $questions) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// Load each many-to-many/one-to-many collection in a separate query to avoid
|
||||
// the Cartesian-product row explosion that occurs when joining multiple collections at once.
|
||||
$this->createQueryBuilder('bq')
|
||||
->select('partial bq.{id}', 'ba')
|
||||
->leftJoin('bq.answers', 'ba')
|
||||
->where('bq.season = :season')
|
||||
->setParameter('season', $season)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$this->createQueryBuilder('bq')
|
||||
->select('partial bq.{id}', 'l')
|
||||
->leftJoin('bq.labels', 'l')
|
||||
->where('bq.season = :season')
|
||||
->setParameter('season', $season)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
$this->createQueryBuilder('bq')
|
||||
->select('partial bq.{id}', 'u', 'uq')
|
||||
->leftJoin('bq.usages', 'u')
|
||||
->leftJoin('u.quiz', 'uq')
|
||||
->where('bq.season = :season')
|
||||
->setParameter('season', $season)
|
||||
->getQuery()
|
||||
->getResult();
|
||||
|
||||
return $questions;
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@ class CandidateRepository extends ServiceEntityRepository
|
||||
parent::__construct($registry, Candidate::class);
|
||||
}
|
||||
|
||||
public function deleteCandidate(Candidate $candidate): void
|
||||
{
|
||||
$this->getEntityManager()->remove($candidate);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
public function getCandidateByHash(Season $season, string $hash): ?Candidate
|
||||
{
|
||||
try {
|
||||
|
||||
@@ -6,7 +6,9 @@ namespace Tvdt\Repository;
|
||||
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Tvdt\Entity\Candidate;
|
||||
use Tvdt\Entity\GivenAnswer;
|
||||
use Tvdt\Entity\Quiz;
|
||||
|
||||
/** @extends ServiceEntityRepository<GivenAnswer> */
|
||||
class GivenAnswerRepository extends ServiceEntityRepository
|
||||
@@ -15,4 +17,15 @@ class GivenAnswerRepository extends ServiceEntityRepository
|
||||
{
|
||||
parent::__construct($registry, GivenAnswer::class);
|
||||
}
|
||||
|
||||
public function deleteAllForCandidateInQuiz(Quiz $quiz, Candidate $candidate): void
|
||||
{
|
||||
$givenAnswers = $this->findBy(['quiz' => $quiz, 'candidate' => $candidate]);
|
||||
|
||||
foreach ($givenAnswers as $givenAnswer) {
|
||||
$this->getEntityManager()->remove($givenAnswer);
|
||||
}
|
||||
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tvdt\Repository;
|
||||
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Tvdt\Entity\QuestionLabel;
|
||||
use Tvdt\Entity\Season;
|
||||
|
||||
/** @extends ServiceEntityRepository<QuestionLabel> */
|
||||
class QuestionLabelRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, QuestionLabel::class);
|
||||
}
|
||||
|
||||
public function findBySlugAndSeason(string $slug, Season $season): ?QuestionLabel
|
||||
{
|
||||
return $this->findOneBy(['slug' => $slug, 'season' => $season]);
|
||||
}
|
||||
|
||||
public function slugExistsForSeason(string $slug, Season $season, ?QuestionLabel $excluding = null): bool
|
||||
{
|
||||
$qb = $this->createQueryBuilder('l')
|
||||
->where('l.slug = :slug')
|
||||
->andWhere('l.season = :season')
|
||||
->setParameter('slug', $slug)
|
||||
->setParameter('season', $season);
|
||||
|
||||
if ($excluding instanceof QuestionLabel) {
|
||||
$qb->andWhere('l.id != :id')->setParameter('id', $excluding->id);
|
||||
}
|
||||
|
||||
return (int) $qb->select('COUNT(l.id)')->getQuery()->getSingleScalarResult() > 0;
|
||||
}
|
||||
}
|
||||
@@ -68,4 +68,15 @@ class QuizCandidateRepository extends ServiceEntityRepository
|
||||
$quizCandidate->penaltySeconds = $penalty;
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
public function resetProgressForCandidate(Quiz $quiz, Candidate $candidate): void
|
||||
{
|
||||
$quizCandidate = $this->findOneBy(['candidate' => $candidate, 'quiz' => $quiz]);
|
||||
if (!$quizCandidate instanceof QuizCandidate) {
|
||||
return;
|
||||
}
|
||||
|
||||
$quizCandidate->started = null;
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use Safe\Exceptions\DatetimeException;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
use Tvdt\Dto\Result;
|
||||
use Tvdt\Entity\Quiz;
|
||||
use Tvdt\Entity\Season;
|
||||
use Tvdt\Exception\ErrorClearingQuizException;
|
||||
|
||||
/** @extends ServiceEntityRepository<Quiz> */
|
||||
@@ -22,6 +23,29 @@ class QuizRepository extends ServiceEntityRepository
|
||||
parent::__construct($registry, Quiz::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quizzes of the season that can still receive bank questions:
|
||||
* not finalized and not started by any candidate.
|
||||
*
|
||||
* @return list<Quiz>
|
||||
*/
|
||||
public function findAssignableForSeason(Season $season): array
|
||||
{
|
||||
/* @var list<Quiz> */
|
||||
return $this->getEntityManager()->createQuery(<<<DQL
|
||||
select q from Tvdt\Entity\Quiz q
|
||||
where q.season = :season
|
||||
and q.finalizedAt is null
|
||||
and not exists (
|
||||
select 1 from Tvdt\Entity\QuizCandidate qc
|
||||
where qc.quiz = q and qc.started is not null
|
||||
)
|
||||
order by q.id asc
|
||||
DQL)
|
||||
->setParameter('season', $season)
|
||||
->getResult();
|
||||
}
|
||||
|
||||
/** @throws ErrorClearingQuizException */
|
||||
public function clearQuiz(Quiz $quiz): void
|
||||
{
|
||||
@@ -48,6 +72,20 @@ class QuizRepository extends ServiceEntityRepository
|
||||
DQL)
|
||||
->setParameter('quiz', $quiz)
|
||||
->execute();
|
||||
|
||||
$em->createQuery(<<<DQL
|
||||
delete from Tvdt\Entity\BankQuestionUsage bqu
|
||||
where bqu.quiz = :quiz
|
||||
DQL)
|
||||
->setParameter('quiz', $quiz)
|
||||
->execute();
|
||||
|
||||
$em->createQuery(<<<DQL
|
||||
update Tvdt\Entity\Quiz q set q.finalizedAt = null
|
||||
where q = :quiz
|
||||
DQL)
|
||||
->setParameter('quiz', $quiz)
|
||||
->execute();
|
||||
}
|
||||
// @codeCoverageIgnoreStart
|
||||
catch (\Throwable $throwable) {
|
||||
@@ -113,8 +151,8 @@ class QuizRepository extends ServiceEntityRepository
|
||||
{
|
||||
return $this->getEntityManager()->createQuery(<<<dql
|
||||
select q, qz, a from Tvdt\Entity\Quiz q
|
||||
join q.questions qz
|
||||
join qz.answers a
|
||||
left join q.questions qz
|
||||
left join qz.answers a
|
||||
where q.id = :id
|
||||
dql)->setParameter('id', $id)->getSingleResult();
|
||||
}
|
||||
@@ -127,8 +165,8 @@ class QuizRepository extends ServiceEntityRepository
|
||||
{
|
||||
return $this->getEntityManager()->createQuery(<<<dql
|
||||
select q, qz, a, ac, s, sc, qc from Tvdt\Entity\Quiz q
|
||||
join q.questions qz
|
||||
join qz.answers a
|
||||
left join q.questions qz
|
||||
left join qz.answers a
|
||||
left join a.candidates ac
|
||||
join q.season s
|
||||
left join s.candidates sc
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user