Create Testcoverage and upgrade Symfomy and PHP
Some checks failed
CI / Tests (push) Failing after 1m8s
CI / Build and deploy to ${{ startsWith(github.ref, 'refs/tags/') && 'production' || (github.ref == 'refs/heads/main' && 'acceptance' || '') }} (push) Has been skipped

* Some tests

* More tests!

* Tests 3

* Move getScores from Candidate to Quiz

* Add some suggestions for future refactoring

* - **Add Gedmo doctrine-extensions and Stof bundle integration**
  - Added `stof/doctrine-extensions-bundle` and `gedmo/doctrine-extensions` dependencies.
  - Integrated `Timestampable` behavior for `Created` fields in entities.
  - Updated `bundles.php` to register StofDoctrineExtensionsBundle.
  - Added configuration for the Stof bundle.
  - Simplified `SeasonVoter` with `match` expression and added new tests.
  - Minor fixes and adjustments across various files.

* WIP

* All the tests

* Base64 tests

* Symfomny 7.4.0

* Update

* Update recipe

* PHP 8.5

* Rector changes

* More 8.5

* Things
This commit is contained in:
2025-11-28 22:56:09 +01:00
committed by GitHub
parent fc273638ad
commit bcd6a157a8
56 changed files with 4324 additions and 1424 deletions

View File

@@ -1,41 +0,0 @@
<?php
declare(strict_types=1);
namespace Tvdt\Command;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Tvdt\Entity\SeasonSettings;
use Tvdt\Repository\SeasonRepository;
#[AsCommand(
name: 'tvdt:add-settings',
description: 'Add a short description for your command',
)]
readonly class AddSettingsCommand
{
public function __construct(private SeasonRepository $seasonRepository, private EntityManagerInterface $entityManager) {}
public function __invoke(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
foreach ($this->seasonRepository->findAll() as $season) {
if (null !== $season->settings) {
continue;
}
$io->text('Adding settings to season : '.$season->seasonCode);
$season->settings = new SeasonSettings();
}
$this->entityManager->flush();
return Command::SUCCESS;
}
}

View File

@@ -8,9 +8,8 @@ use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Tvdt\Entity\Season;
use Tvdt\Repository\SeasonRepository;
use Tvdt\Repository\UserRepository;
@@ -18,7 +17,7 @@ use Tvdt\Repository\UserRepository;
name: 'tvdt:claim-season',
description: 'Give a user owner rights on a season',
)]
readonly class ClaimSeasonCommand
final readonly class ClaimSeasonCommand
{
public function __construct(private UserRepository $userRepository, private SeasonRepository $seasonRepository, private EntityManagerInterface $entityManager) {}
@@ -27,14 +26,11 @@ readonly class ClaimSeasonCommand
string $seasonCode,
#[Argument]
string $email,
InputInterface $input,
OutputInterface $output,
SymfonyStyle $io,
): int {
$io = new SymfonyStyle($input, $output);
try {
$season = $this->seasonRepository->findOneBy(['seasonCode' => $seasonCode]);
if (null === $season) {
$season = $this->seasonRepository->findOneBySeasonCode($seasonCode);
if (!$season instanceof Season) {
throw new \InvalidArgumentException('Season not found');
}

View File

@@ -7,8 +7,6 @@ namespace Tvdt\Command;
use Symfony\Component\Console\Attribute\Argument;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Tvdt\Repository\UserRepository;
@@ -16,17 +14,15 @@ use Tvdt\Repository\UserRepository;
name: 'tvdt:make-admin',
description: 'Give a user the role admin',
)]
readonly class MakeAdminCommand
final readonly class MakeAdminCommand
{
public function __construct(private UserRepository $userRepository) {}
public function __invoke(
#[Argument]
string $email,
InputInterface $input,
OutputInterface $output,
SymfonyStyle $io,
): int {
$io = new SymfonyStyle($input, $output);
try {
$this->userRepository->makeAdmin($email);
} catch (\InvalidArgumentException) {

View File

@@ -26,6 +26,7 @@ final class BackofficeController extends AbstractController
public function __construct(
private readonly SeasonRepository $seasonRepository,
private readonly Security $security,
private readonly QuizSpreadsheetService $excel,
) {}
#[Route('/backoffice/', name: 'tvdt_backoffice_index')]
@@ -68,9 +69,9 @@ final class BackofficeController extends AbstractController
}
#[Route('/backoffice/template', name: 'tvdt_backoffice_template', priority: 10)]
public function getTemplate(QuizSpreadsheetService $excel): Response
public function getTemplate(): StreamedResponse
{
$response = new StreamedResponse($excel->generateTemplate());
$response = new StreamedResponse($this->excel->generateTemplate());
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment; filename="template.xlsx"');

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tvdt\Controller\Backoffice;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
@@ -17,14 +18,16 @@ use Tvdt\Factory\EliminationFactory;
final class PrepareEliminationController extends AbstractController
{
public function __construct(private readonly EliminationFactory $eliminationFactory) {}
#[Route(
'/backoffice/season/{seasonCode:season}/quiz/{quiz}/elimination/prepare',
name: 'tvdt_prepare_elimination',
requirements: ['seasonCode' => self::SEASON_CODE_REGEX, 'quiz' => Requirement::UUID],
)]
public function index(Season $season, Quiz $quiz, EliminationFactory $eliminationFactory): Response
public function index(Season $season, Quiz $quiz): RedirectResponse
{
$elimination = $eliminationFactory->createEliminationFromQuiz($quiz);
$elimination = $this->eliminationFactory->createEliminationFromQuiz($quiz);
return $this->redirectToRoute('tvdt_prepare_elimination_view', ['elimination' => $elimination->id]);
}

View File

@@ -19,7 +19,6 @@ use Tvdt\Entity\Candidate;
use Tvdt\Entity\Quiz;
use Tvdt\Entity\Season;
use Tvdt\Exception\ErrorClearingQuizException;
use Tvdt\Repository\CandidateRepository;
use Tvdt\Repository\QuizCandidateRepository;
use Tvdt\Repository\QuizRepository;
use Tvdt\Security\Voter\SeasonVoter;
@@ -29,8 +28,9 @@ use Tvdt\Security\Voter\SeasonVoter;
class QuizController extends AbstractController
{
public function __construct(
private readonly CandidateRepository $candidateRepository,
private readonly QuizRepository $quizRepository,
private readonly TranslatorInterface $translator,
private readonly QuizCandidateRepository $quizCandidateRepository,
) {}
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
@@ -44,7 +44,7 @@ class QuizController extends AbstractController
return $this->render('backoffice/quiz.html.twig', [
'season' => $season,
'quiz' => $quiz,
'result' => $this->candidateRepository->getScores($quiz),
'result' => $this->quizRepository->getScores($quiz),
]);
}
@@ -72,10 +72,10 @@ class QuizController extends AbstractController
name: 'tvdt_backoffice_quiz_clear',
requirements: ['quiz' => Requirement::UUID],
)]
public function clearQuiz(Quiz $quiz, QuizRepository $quizRepository): RedirectResponse
public function clearQuiz(Quiz $quiz): RedirectResponse
{
try {
$quizRepository->clearQuiz($quiz);
$this->quizRepository->clearQuiz($quiz);
$this->addFlash('success', $this->translator->trans('Quiz cleared'));
} catch (ErrorClearingQuizException) {
$this->addFlash('error', $this->translator->trans('Error clearing quiz'));
@@ -90,9 +90,9 @@ class QuizController extends AbstractController
name: 'tvdt_backoffice_quiz_delete',
requirements: ['quiz' => Requirement::UUID],
)]
public function deleteQuiz(Quiz $quiz, QuizRepository $quizRepository): RedirectResponse
public function deleteQuiz(Quiz $quiz): RedirectResponse
{
$quizRepository->deleteQuiz($quiz);
$this->quizRepository->deleteQuiz($quiz);
$this->addFlash('success', $this->translator->trans('Quiz deleted'));
@@ -105,7 +105,7 @@ class QuizController extends AbstractController
name: 'tvdt_backoffice_modify_correction',
requirements: ['quiz' => Requirement::UUID, 'candidate' => Requirement::UUID],
)]
public function modifyCorrection(Quiz $quiz, Candidate $candidate, QuizCandidateRepository $quizCandidateRepository, Request $request): RedirectResponse
public function modifyCorrection(Quiz $quiz, Candidate $candidate, Request $request): RedirectResponse
{
if (!$request->isMethod('POST')) {
throw new MethodNotAllowedHttpException(['POST']);
@@ -113,7 +113,7 @@ class QuizController extends AbstractController
$corrections = (float) $request->request->get('corrections');
$quizCandidateRepository->setCorrectionsForCandidate($quiz, $candidate, $corrections);
$this->quizCandidateRepository->setCorrectionsForCandidate($quiz, $candidate, $corrections);
return $this->redirectToRoute('tvdt_backoffice_quiz', ['seasonCode' => $quiz->season->seasonCode, 'quiz' => $quiz->id]);
}

View File

@@ -30,6 +30,7 @@ class SeasonController extends AbstractController
public function __construct(
private readonly TranslatorInterface $translator,
private readonly EntityManagerInterface $em,
private readonly QuizSpreadsheetService $quizSpreadsheet,
) {}
#[IsGranted(SeasonVoter::EDIT, subject: 'season')]
@@ -87,7 +88,7 @@ class SeasonController extends AbstractController
requirements: ['seasonCode' => self::SEASON_CODE_REGEX],
priority: 10,
)]
public function addQuiz(Request $request, Season $season, QuizSpreadsheetService $quizSpreadsheet): Response
public function addQuiz(Request $request, Season $season): Response
{
$quiz = new Quiz();
$form = $this->createForm(UploadQuizFormType::class, $quiz);
@@ -98,7 +99,7 @@ class SeasonController extends AbstractController
/* @var UploadedFile $sheet */
$sheet = $form->get('sheet')->getData();
$quizSpreadsheet->xlsxToQuiz($quiz, $sheet);
$this->quizSpreadsheet->xlsxToQuiz($quiz, $sheet);
$quiz->season = $season;
$this->em->persist($quiz);

View File

@@ -26,7 +26,7 @@ use function Symfony\Component\Translation\t;
#[IsGranted('ROLE_USER')]
final class EliminationController extends AbstractController
{
public function __construct(private readonly TranslatorInterface $translator) {}
public function __construct(private readonly TranslatorInterface $translator, private readonly CandidateRepository $candidateRepository) {}
#[IsGranted(SeasonVoter::ELIMINATION, 'elimination')]
#[Route('/elimination/{elimination}', name: 'tvdt_elimination', requirements: ['elimination' => Requirement::UUID])]
@@ -50,9 +50,9 @@ final class EliminationController extends AbstractController
#[IsGranted(SeasonVoter::ELIMINATION, 'elimination')]
#[Route('/elimination/{elimination}/{candidateHash}', name: 'tvdt_elimination_candidate', requirements: ['elimination' => Requirement::UUID, 'candidateHash' => self::CANDIDATE_HASH_REGEX])]
public function candidateScreen(Elimination $elimination, string $candidateHash, CandidateRepository $candidateRepository): Response
public function candidateScreen(Elimination $elimination, string $candidateHash): Response
{
$candidate = $candidateRepository->getCandidateByHash($elimination->quiz->season, $candidateHash);
$candidate = $this->candidateRepository->getCandidateByHash($elimination->quiz->season, $candidateHash);
if (!$candidate instanceof Candidate) {
$this->addFlash(FlashType::Warning,
t('Cound not find candidate with name %name%', ['%name%' => Base64::base64UrlDecode($candidateHash)])->trans($this->translator),

View File

@@ -15,17 +15,17 @@ use Tvdt\Enum\FlashType;
#[AsController]
final class LoginController extends AbstractController
{
public function __construct(private readonly AuthenticationUtils $authenticationUtils, private readonly TranslatorInterface $translator) {}
#[Route(path: '/login', name: 'tvdt_login_login')]
public function login(AuthenticationUtils $authenticationUtils, TranslatorInterface $translator): Response
public function login(): Response
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
$error = $this->authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$lastUsername = $this->authenticationUtils->getLastUsername();
if ($error instanceof AuthenticationException) {
$this->addFlash(FlashType::Danger, $translator->trans($error->getMessageKey(), $error->getMessageData(), 'security'));
$this->addFlash(FlashType::Danger, $this->translator->trans($error->getMessageKey(), $error->getMessageData(), 'security'));
}
return $this->render('backoffice/login/login.html.twig', [

View File

@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Tvdt\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
@@ -22,7 +23,6 @@ use Tvdt\Form\SelectSeasonType;
use Tvdt\Helpers\Base64;
use Tvdt\Repository\AnswerRepository;
use Tvdt\Repository\CandidateRepository;
use Tvdt\Repository\GivenAnswerRepository;
use Tvdt\Repository\QuestionRepository;
use Tvdt\Repository\QuizCandidateRepository;
use Tvdt\Repository\SeasonRepository;
@@ -30,10 +30,10 @@ use Tvdt\Repository\SeasonRepository;
#[AsController]
final class QuizController extends AbstractController
{
public function __construct(private readonly TranslatorInterface $translator) {}
public function __construct(private readonly TranslatorInterface $translator, private readonly EntityManagerInterface $entityManager, private readonly SeasonRepository $seasonRepository, private readonly CandidateRepository $candidateRepository, private readonly QuestionRepository $questionRepository, private readonly AnswerRepository $answerRepository, private readonly QuizCandidateRepository $quizCandidateRepository) {}
#[Route(path: '/', name: 'tvdt_quiz_select_season', methods: ['GET', 'POST'])]
public function selectSeason(Request $request, SeasonRepository $seasonRepository): Response
public function selectSeason(Request $request): Response
{
$form = $this->createForm(SelectSeasonType::class);
$form->handleRequest($request);
@@ -41,7 +41,7 @@ final class QuizController extends AbstractController
if ($form->isSubmitted() && $form->isValid()) {
$seasonCode = $form->get('season_code')->getData();
if ([] === $seasonRepository->findBy(['seasonCode' => $seasonCode])) {
if ([] === $this->seasonRepository->findBy(['seasonCode' => $seasonCode])) {
$this->addFlash(FlashType::Warning, $this->translator->trans('Invalid season code'));
return $this->redirectToRoute('tvdt_quiz_select_season');
@@ -80,13 +80,8 @@ final class QuizController extends AbstractController
Season $season,
string $nameHash,
Request $request,
CandidateRepository $candidateRepository,
QuestionRepository $questionRepository,
AnswerRepository $answerRepository,
GivenAnswerRepository $givenAnswerRepository,
QuizCandidateRepository $quizCandidateRepository,
): Response {
$candidate = $candidateRepository->getCandidateByHash($season, $nameHash);
$candidate = $this->candidateRepository->getCandidateByHash($season, $nameHash);
if (!$candidate instanceof Candidate) {
$this->addFlash(FlashType::Danger, $this->translator->trans('Candidate not found'));
@@ -103,28 +98,34 @@ final class QuizController extends AbstractController
}
if ('POST' === $request->getMethod()) {
$answer = $answerRepository->findOneBy(['id' => $request->request->get('answer')]);
// TODO: Extract saving answer logic to a service
$answer = $this->answerRepository->findOneBy(['id' => $request->request->get('answer')]);
if (!$answer instanceof Answer) {
throw new BadRequestHttpException('Invalid Answer ID');
}
$givenAnswer = new GivenAnswer($candidate, $answer->question->quiz, $answer);
$givenAnswerRepository->save($givenAnswer);
$this->entityManager->persist($givenAnswer);
$this->entityManager->flush();
// end of extarcting saving answer logic
return $this->redirectToRoute('tvdt_quiz_quiz_page', ['seasonCode' => $season->seasonCode, 'nameHash' => $nameHash]);
}
$question = $questionRepository->findNextQuestionForCandidate($candidate);
// TODO: Extract getting next question logic to a service
$question = $this->questionRepository->findNextQuestionForCandidate($candidate);
// Keep creating flash here based on the return type of service call
if (!$question instanceof Question) {
$this->addFlash(FlashType::Success, $this->translator->trans('Quiz completed'));
return $this->redirectToRoute('tvdt_quiz_enter_name', ['seasonCode' => $season->seasonCode]);
}
$quizCandidateRepository->createIfNotExist($quiz, $candidate);
$this->quizCandidateRepository->createIfNotExist($quiz, $candidate);
// end of extracting getting next question logic
return $this->render('quiz/question.twig', ['candidate' => $candidate, 'question' => $question, 'season' => $season]);
}
}

View File

@@ -9,6 +9,7 @@ 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;
@@ -23,15 +24,12 @@ use Tvdt\Security\EmailVerifier;
final class RegistrationController extends AbstractController
{
public function __construct(private readonly EmailVerifier $emailVerifier, private readonly TranslatorInterface $translator) {}
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) {}
#[Route('/register', name: 'tvdt_register')]
public function register(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
Security $security,
EntityManagerInterface $entityManager,
LoggerInterface $logger,
): Response {
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
@@ -41,7 +39,7 @@ final class RegistrationController extends AbstractController
/** @var string $plainPassword */
$plainPassword = $form->get('plainPassword')->getData();
$user->password = $userPasswordHasher->hashPassword($user, $plainPassword);
$user->password = $this->userPasswordHasher->hashPassword($user, $plainPassword);
$entityManager->persist($user);
$entityManager->flush();
@@ -55,10 +53,10 @@ final class RegistrationController extends AbstractController
->htmlTemplate('backoffice/registration/confirmation_email.html.twig'),
);
} catch (TransportExceptionInterface $e) {
$logger->error($e->getMessage());
$this->logger->error($e->getMessage());
}
$response = $security->login($user, 'form_login', 'main');
$response = $this->security->login($user, 'form_login', 'main');
\assert($response instanceof Response);
return $response;
@@ -70,7 +68,7 @@ final class RegistrationController extends AbstractController
}
#[Route('/verify/email', name: 'tvdt_verify_email')]
public function verifyUserEmail(Request $request, TranslatorInterface $translator, UserRepository $userRepository): Response
public function verifyUserEmail(Request $request): RedirectResponse
{
$id = $request->query->get('id');
@@ -78,7 +76,7 @@ final class RegistrationController extends AbstractController
return $this->redirectToRoute('tvdt_register');
}
$user = $userRepository->find($id);
$user = $this->userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('tvdt_register');
@@ -88,7 +86,7 @@ final class RegistrationController extends AbstractController
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $verifyEmailException) {
$this->addFlash('verify_email_error', $translator->trans($verifyEmailException->getReason(), [], 'VerifyEmailBundle'));
$this->addFlash('verify_email_error', $this->translator->trans($verifyEmailException->getReason(), [], 'VerifyEmailBundle'));
return $this->redirectToRoute('tvdt_register');
}

View File

@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace Tvdt\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Doctrine\Persistence\ObjectManager;
use Tvdt\Entity\Answer;
use Tvdt\Entity\Candidate;
@@ -12,8 +13,15 @@ use Tvdt\Entity\Question;
use Tvdt\Entity\Quiz;
use Tvdt\Entity\Season;
class KrtekFixtures extends Fixture
final class KrtekFixtures extends Fixture implements FixtureGroupInterface
{
public const string KRTEK_SEASON = 'krtek-seaspm';
public static function getGroups(): array
{
return ['test', 'dev'];
}
public function load(ObjectManager $manager): void
{
$season = new Season();
@@ -41,6 +49,8 @@ class KrtekFixtures extends Fixture
$season->addQuiz($this->createQuiz2($season));
$manager->flush();
$this->addReference(self::KRTEK_SEASON, $season);
}
private function createQuiz1(Season $season): Quiz

View File

@@ -0,0 +1,75 @@
<?php
declare(strict_types=1);
namespace Tvdt\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Tvdt\Entity\Season;
use Tvdt\Entity\User;
final class TestFixtures extends Fixture implements FixtureGroupInterface, DependentFixtureInterface
{
public const string PASSWORD = 'test1234';
public function __construct(
private readonly UserPasswordHasherInterface $passwordHasher,
) {}
public static function getGroups(): array
{
return ['test'];
}
public function getDependencies(): array
{
return [KrtekFixtures::class];
}
public function load(ObjectManager $manager): void
{
$user = new User();
$user->email = 'test@example.org';
$user->password = $this->passwordHasher->hashPassword($user, self::PASSWORD);
$manager->persist($user);
$user = new User();
$user->email = 'krtek-admin@example.org';
$user->password = $this->passwordHasher->hashPassword($user, self::PASSWORD);
$manager->persist($user);
$krtek = $this->getReference(KrtekFixtures::KRTEK_SEASON, Season::class);
$krtek->addOwner($user);
$anotherSeason = new Season();
$anotherSeason->name = 'Another Season';
$anotherSeason->seasonCode = 'bbbbb';
$manager->persist($anotherSeason);
$this->addReference('another-season', $anotherSeason);
$user = new User();
$user->email = 'user1@example.org';
$user->password = $this->passwordHasher->hashPassword($user, self::PASSWORD);
$manager->persist($user);
$user->addSeason($anotherSeason);
$user = new User();
$user->email = 'user2@example.org';
$user->password = $this->passwordHasher->hashPassword($user, self::PASSWORD);
$manager->persist($user);
$krtek->addOwner($user);
$anotherSeason->addOwner($user);
$manager->flush();
}
}

View File

@@ -6,7 +6,7 @@ namespace Tvdt\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Safe\DateTimeImmutable;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\Uid\Uuid;
@@ -30,6 +30,7 @@ class Elimination
#[ORM\Column(type: Types::JSONB)]
public array $data = [];
#[Gedmo\Timestampable(on: 'create')]
#[ORM\Column(type: Types::DATETIMETZ_IMMUTABLE, nullable: false)]
public private(set) \DateTimeImmutable $created;
@@ -54,12 +55,10 @@ class Elimination
public function getScreenColour(?string $name): ?string
{
if (null === $name) {
return null;
}
return $this->data[$name] ?? null;
}
#[ORM\PrePersist]
public function setCreatedAtValue(): void
{
$this->created = new DateTimeImmutable();
}
}

View File

@@ -6,13 +6,12 @@ namespace Tvdt\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Safe\DateTimeImmutable;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\Uuid;
use Tvdt\Repository\GivenAnswerRepository;
#[ORM\Entity(repositoryClass: GivenAnswerRepository::class)]
#[ORM\HasLifecycleCallbacks]
class GivenAnswer
{
#[ORM\Column(type: UuidType::NAME, unique: true)]
@@ -21,6 +20,7 @@ class GivenAnswer
#[ORM\Id]
public private(set) Uuid $id;
#[Gedmo\Timestampable(on: 'create')]
#[ORM\Column(type: Types::DATETIMETZ_IMMUTABLE, nullable: false)]
public private(set) \DateTimeImmutable $created;
@@ -37,10 +37,4 @@ class GivenAnswer
#[ORM\ManyToOne(inversedBy: 'givenAnswers')]
private(set) Answer $answer,
) {}
#[ORM\PrePersist]
public function setCreatedAtValue(): void
{
$this->created = new DateTimeImmutable();
}
}

View File

@@ -6,13 +6,12 @@ namespace Tvdt\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Safe\DateTimeImmutable;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Bridge\Doctrine\Types\UuidType;
use Symfony\Component\Uid\Uuid;
use Tvdt\Repository\QuizCandidateRepository;
#[ORM\Entity(repositoryClass: QuizCandidateRepository::class)]
#[ORM\HasLifecycleCallbacks]
#[ORM\UniqueConstraint(columns: ['candidate_id', 'quiz_id'])]
class QuizCandidate
{
@@ -25,6 +24,7 @@ class QuizCandidate
#[ORM\Column]
public float $corrections = 0;
#[Gedmo\Timestampable(on: 'create')]
#[ORM\Column(type: Types::DATETIMETZ_IMMUTABLE)]
public private(set) \DateTimeImmutable $created;
@@ -37,10 +37,4 @@ class QuizCandidate
#[ORM\ManyToOne(inversedBy: 'quizData')]
public Candidate $candidate,
) {}
#[ORM\PrePersist]
public function setCreatedAtValue(): void
{
$this->created = new DateTimeImmutable();
}
}

View File

@@ -98,7 +98,7 @@ class Season
return $this->owners->contains($user);
}
public function generateSeasonCode(): self
public function generateSeasonCode(): void
{
$code = '';
$len = mb_strlen(self::SEASON_CODE_CHARACTERS) - 1;
@@ -108,7 +108,5 @@ class Season
}
$this->seasonCode = $code;
return $this;
}
}

View File

@@ -7,11 +7,18 @@ namespace Tvdt\Enum;
enum FlashType: string
{
case Primary = 'primary';
case Secondary = 'secondary';
case Success = 'success';
case Danger = 'danger';
case Warning = 'warning';
case Info = 'info';
case Light = 'light';
case Dark = 'dark';
}

View File

@@ -7,12 +7,12 @@ namespace Tvdt\Factory;
use Doctrine\ORM\EntityManagerInterface;
use Tvdt\Entity\Elimination;
use Tvdt\Entity\Quiz;
use Tvdt\Repository\CandidateRepository;
use Tvdt\Repository\QuizRepository;
final readonly class EliminationFactory
{
public function __construct(
private CandidateRepository $candidateRepository,
private QuizRepository $quizRepository,
private EntityManagerInterface $em,
) {}
@@ -21,7 +21,7 @@ final readonly class EliminationFactory
$elimination = new Elimination($quiz);
$this->em->persist($elimination);
$scores = $this->candidateRepository->getScores($quiz);
$scores = $this->quizRepository->getScores($quiz);
$simpleScores = [];

View File

@@ -6,12 +6,8 @@ namespace Tvdt\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Safe\DateTimeImmutable;
use Safe\Exceptions\DatetimeException;
use Safe\Exceptions\UrlException;
use Tvdt\Dto\Result;
use Tvdt\Entity\Candidate;
use Tvdt\Entity\Quiz;
use Tvdt\Entity\Season;
use Tvdt\Helpers\Base64;
@@ -42,49 +38,4 @@ class CandidateRepository extends ServiceEntityRepository
->setParameter('name', $name)
->getOneOrNullResult();
}
public function save(Candidate $candidate, bool $flush = true): void
{
$this->getEntityManager()->persist($candidate);
if ($flush) {
$this->getEntityManager()->flush();
}
}
/**
* @throws DatetimeException
*
* @return list<Result>
*/
public function getScores(Quiz $quiz): array
{
$result = $this->getEntityManager()->createQuery(<<<DQL
select
c.id,
c.name,
sum(case when a.isRightAnswer = true then 1 else 0 end) as correct,
qc.corrections,
max(ga.created) as end_time,
qc.created as start_time,
(sum(case when a.isRightAnswer = true then 1 else 0 end) + qc.corrections) as score
from Tvdt\Entity\Candidate c
join c.givenAnswers ga
join ga.answer a
join c.quizData qc
where qc.quiz = :quiz and ga.quiz = :quiz
group by ga.quiz, c.id, qc.id
order by score desc, max(ga.created) - qc.created asc
DQL
)->setParameter('quiz', $quiz)->getResult();
return array_map(static fn (array $row): Result => new Result(
id: $row['id'],
name: $row['name'],
correct: (int) $row['correct'],
corrections: $row['corrections'],
time: new DateTimeImmutable($row['end_time'])->diff($row['start_time']),
score: $row['score'],
), $result);
}
}

View File

@@ -17,13 +17,4 @@ class GivenAnswerRepository extends ServiceEntityRepository
{
parent::__construct($registry, GivenAnswer::class);
}
public function save(GivenAnswer $givenAnswer, bool $flush = true): void
{
$this->getEntityManager()->persist($givenAnswer);
if ($flush) {
$this->getEntityManager()->flush();
}
}
}

View File

@@ -7,10 +7,10 @@ namespace Tvdt\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Psr\Log\LoggerInterface;
use Tvdt\Entity\Elimination;
use Tvdt\Entity\GivenAnswer;
use Safe\DateTimeImmutable;
use Safe\Exceptions\DatetimeException;
use Tvdt\Dto\Result;
use Tvdt\Entity\Quiz;
use Tvdt\Entity\QuizCandidate;
use Tvdt\Exception\ErrorClearingQuizException;
/**
@@ -29,28 +29,36 @@ class QuizRepository extends ServiceEntityRepository
$em = $this->getEntityManager();
$em->beginTransaction();
try {
$em->createQueryBuilder()
->delete()->from(QuizCandidate::class, 'qc')
->where('qc.quiz = :quiz')
$em->createQuery(<<<DQL
delete from Tvdt\Entity\QuizCandidate qc
where qc.quiz = :quiz
DQL)
->setParameter('quiz', $quiz)
->getQuery()->execute();
->execute();
$em->createQueryBuilder()
->delete()->from(GivenAnswer::class, 'ga')
->where('ga.quiz = :quiz')
$em->createQuery(<<<DQL
delete from Tvdt\Entity\GivenAnswer ga
where ga.quiz = :quiz
DQL)
->setParameter('quiz', $quiz)
->getQuery()->execute();
$em->createQueryBuilder()
->delete()->from(Elimination::class, 'e')
->where('e.quiz = :quiz')
->execute();
$em->createQuery(<<<DQL
delete from Tvdt\Entity\Elimination e
where e.quiz = :quiz
DQL)
->setParameter('quiz', $quiz)
->getQuery()->execute();
} catch (\Throwable $throwable) {
->execute();
}
// @codeCoverageIgnoreStart
catch (\Throwable $throwable) {
$this->logger->error($throwable->getMessage());
$em->rollback();
throw new ErrorClearingQuizException(previous: $throwable);
}
// @codeCoverageIgnoreEnd
$em->commit();
}
@@ -59,4 +67,40 @@ class QuizRepository extends ServiceEntityRepository
$this->getEntityManager()->remove($quiz);
$this->getEntityManager()->flush();
}
/**
* @throws DatetimeException
*
* @return list<Result>
*/
public function getScores(Quiz $quiz): array
{
$result = $this->getEntityManager()->createQuery(<<<DQL
select
c.id,
c.name,
sum(case when a.isRightAnswer = true then 1 else 0 end) as correct,
qd.corrections,
max(ga.created) as end_time,
qd.created as start_time,
(sum(case when a.isRightAnswer = true then 1 else 0 end) + qd.corrections) as score
from Tvdt\Entity\Candidate c
join c.givenAnswers ga
join ga.answer a
join c.quizData qd
where qd.quiz = :quiz and ga.quiz = :quiz
group by ga.quiz, c.id, qd.id
order by score desc, max(ga.created) - qd.created asc
DQL
)->setParameter('quiz', $quiz)->getResult();
return array_map(static fn (array $row): Result => new Result(
id: $row['id'],
name: $row['name'],
correct: (int) $row['correct'],
corrections: $row['corrections'],
time: $row['start_time']->diff(new DateTimeImmutable($row['end_time'])),
score: $row['score'],
), $result);
}
}

View File

@@ -19,6 +19,17 @@ class SeasonRepository extends ServiceEntityRepository
parent::__construct($registry, Season::class);
}
public function findOneBySeasonCode(string $seasonCode): ?Season
{
return $this->getEntityManager()->createQuery(<<<DQL
select s from Tvdt\Entity\Season s
where s.seasonCode = :seasonCode
DQL)
->setParameter('seasonCode', $seasonCode)
->setMaxResults(1)
->getOneOrNullResult();
}
/** @return list<Season> Returns an array of Season objects */
public function getSeasonsForUser(User $user): array
{

View File

@@ -48,24 +48,14 @@ final class SeasonVoter extends Voter
return true;
}
switch (true) {
case $subject instanceof Answer:
$season = $subject->question->quiz->season;
break;
case $subject instanceof Elimination:
case $subject instanceof Question:
$season = $subject->quiz->season;
break;
case $subject instanceof Candidate:
case $subject instanceof Quiz:
$season = $subject->season;
break;
case $subject instanceof Season:
$season = $subject;
break;
default:
return false;
}
$season = match (true) {
$subject instanceof Answer => $subject->question->quiz->season,
$subject instanceof Elimination,
$subject instanceof Question => $subject->quiz->season,
$subject instanceof Candidate,
$subject instanceof Quiz => $subject->season,
$subject instanceof Season => $subject,
};
return match ($attribute) {
self::EDIT, self::DELETE, self::ELIMINATION => $season->isOwner($user),

View File

@@ -55,6 +55,10 @@ class QuizSpreadsheetService
/** @throws SpreadsheetDataException */
public function xlsxToQuiz(Quiz $quiz, File $file): void
{
if (!$this->isSpreadsheetFile($file)) {
throw new \InvalidArgumentException('File must be a valid XLSX spreadsheet');
}
$spreadsheet = $this->readSheet($file);
$sheet = $spreadsheet->getSheet($spreadsheet->getFirstSheetIndex());
@@ -112,7 +116,10 @@ class QuizSpreadsheetService
}
}
public function quizToXlsx(Quiz $quiz): void {}
public function quizToXlsx(Quiz $quiz): void
{
throw new \Exception('Not implemented');
}
private function toXlsx(Spreadsheet $spreadsheet): \Closure
{
@@ -120,4 +127,9 @@ class QuizSpreadsheetService
return static fn () => $writer->save('php://output');
}
private function isSpreadsheetFile(File $file): bool
{
return 'xlsx' === $file->getExtension();
}
}