<?php
namespace App\Controller\v1\Survey;
use App\Form\SurveyResultFormType;
use App\Repository\Survey\AnswerRepository;
use App\Repository\Survey\QuestionRepository;
use App\Repository\Survey\SurveyRepository;
use App\Services\Survey\SurveyResultDataService;
use App\Services\Survey\SurveyResultService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use OpenApi\Annotations as OA;
/**
* @Route("/api/v1/surveyResult/", name="create.surveyResult", methods={"POST"})
* @OA\Post(
* summary="Сохранить результаты опроса",
* description="",
* operationId="create.surveyResult",
* @OA\RequestBody(
* required=true,
* description="Результаты опроса",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="survey_id", type="integer", example="1"),
* @OA\Property(property="user_ip", type="string", example="127.0.0.1"),
* @OA\Property(property="user_agent", type="string", example="Yandex Browser"),
* @OA\Property(property="user_email", type="string", example="email@mail.ru"),
* @OA\Property(property="elapsedTime", type="integer", example="161085433"),
* @OA\Property(
* property="questions",
* type="array",
* @OA\Items(
* type="object",
* @OA\Property(
* property="question_id",
* type="integer",
* example="1"
* ),
* @OA\Property(
* property="question_data",
* type="string",
* example="1,2,3"
* ),
* @OA\Property(
* property="isPasted",
* type="boolean",
* example="false"
* )
* )
* )
* )
* )
* )
* @OA\Response(
* response=200,
* description="Результаты опроса сохранены"
* )
* @OA\Tag(name="Survey")
*/
class CreateSurveyResultController extends AbstractController
{
public function __construct(
public SurveyResultDataService $surveyResultDataService
) {
}
/**
* @param Request $request
* @return JsonResponse
*/
public function __invoke(Request $request): JsonResponse
{
$dataCollections = json_decode($request->getContent(), true);
$form = $this->createForm(SurveyResultFormType::class);
$form->submit($dataCollections);
if ($form->isSubmitted() && !$form->isValid()) {
return $this->json([
'success' => false,
'errors' => $this->getErrorMessages($form)
], Response::HTTP_BAD_REQUEST);
}
$this->surveyResultDataService->createResultData($form->getData());
return $this->json([
'success' => true,
'message' => 'Результат опроса успешно сохранен'
], Response::HTTP_OK);
}
protected function getErrorMessages(FormInterface $form): array
{
$errors = array();
foreach ($form->getErrors() as $key => $error) {
$errors[] = $error->getMessage();
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessages($child);
}
}
return $errors;
}
}