<?php
namespace App\EventSubscriber;
use App\Entity\ElCourseJoin;
use App\Entity\ElExamAnswer;
use App\Entity\ElExamAttempt;
use App\Entity\ElExamQuestion;
use Doctrine\ORM\EntityManagerInterface;
use App\Event\ElExamAnswerPreUpdateEvent;
use App\Event\ElExamAnswerPostPersistEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ElExamAnswerSubscriber implements EventSubscriberInterface
{
public function __construct(
private EntityManagerInterface $_em
) {
}
public static function getSubscribedEvents(): array
{
return [
ElExamAnswerPostPersistEvent::NAME => 'onPostPersist',
ElExamAnswerPreUpdateEvent::NAME => 'onPreUpdate'
];
}
public function onPostPersist(ElExamAnswerPostPersistEvent $event)
{
$object = $event->getObject();
$elExamAttempt = $object->getElExamAttempt();
if ($elExamAttempt) {
$elExamAttempt->setCurrentQuestionId($object->getElExamQuestion()->getId());
$this->_em->persist($elExamAttempt);
$this->_em->flush();
}
}
public function onPreUpdate(ElExamAnswerPreUpdateEvent $event)
{
$data = $event->getObject();
$elExamAttempt = $data->getElExamAttempt();
if ($elExamAttempt->getStatus() === ElExamAttempt::STATUSEXAMATTEMPT_STARTED) {
$elExamQuestion = $data->getElExamQuestion();
$elExam = $elExamQuestion->getElExam();
if ($elExamQuestion->getQuestionType() === ElExamQuestion::QUESTIONTYPE_SINGLE) {
$options = $elExamQuestion->getElExamOptions();
$data->setIsCorrect(false);
foreach ($options as $option) {
if ($option->getIsCorrect() && $option->getId() == $data->getAnswer()) {
$data->setIsCorrect(true);
break;
}
}
if ($elExam->getIsOnlyChoiceQuestion()) {
$data->setGivenPoint($data->getIsCorrect() ? $elExamQuestion->getCorrectPoint() : $elExamQuestion->getWrongPoint());
}
} elseif ($elExamQuestion->getQuestionType() === ElExamQuestion::QUESTIONTYPE_MULTI) {
$options = $elExamQuestion->getElExamOptions();
$answers = $data->getAnswer();
$correctOptions = [];
if ($answers) {
$answers = explode(",", $answers);
sort($answers);
foreach ($options as $option) {
if ($option->getIsCorrect()) {
$correctOptions[] = $option->getId();
}
}
sort($correctOptions);
}
$data->setIsCorrect($answers == $correctOptions);
if ($elExam->getIsOnlyChoiceQuestion()) {
$data->setGivenPoint($data->getIsCorrect() ? $elExamQuestion->getCorrectPoint() : $elExamQuestion->getWrongPoint());
}
}
}
}
}