110 lines
2.9 KiB
PHP
110 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Controller\Api;
|
|
|
|
use App\Entity\Rating;
|
|
use App\Entity\User;
|
|
use App\Presenter\RatingPresenter;
|
|
use App\Repository\RatingRepository;
|
|
use App\Repository\SubjectRepository;
|
|
use App\Services\OutputService;
|
|
use Doctrine\ORM\EntityManagerInterface;
|
|
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
|
use Symfony\Component\HttpFoundation\JsonResponse;
|
|
use Symfony\Component\HttpFoundation\Request;
|
|
use Symfony\Component\Routing\Attribute\Route;
|
|
use Symfony\Component\Security\Http\Attribute\CurrentUser;
|
|
|
|
class RatingController extends AbstractController
|
|
{
|
|
#[Route('/api/ratings', methods: ['GET'])]
|
|
public function index(
|
|
RatingRepository $repo,
|
|
OutputService $output,
|
|
RatingPresenter $ratingPresenter,
|
|
): JsonResponse {
|
|
return $this->json($output->success([
|
|
'ratings' => $ratingPresenter->presentMany($repo->findAll()),
|
|
]), 200);
|
|
}
|
|
|
|
#[Route('/api/ratings', methods: ['POST'])]
|
|
public function create(
|
|
Request $request,
|
|
EntityManagerInterface $em,
|
|
OutputService $output,
|
|
SubjectRepository $subjectRepository,
|
|
#[CurrentUser]
|
|
User $user
|
|
): JsonResponse {
|
|
$subject = $subjectRepository->find($request->getPayload()->get('subject_id'));
|
|
|
|
if ($subject === null) {
|
|
return $this->json(
|
|
$output->error(["UNKNOWN_SUBJECT"])
|
|
);
|
|
}
|
|
|
|
$rating = new Rating();
|
|
$rating->setSubject($subject);
|
|
$rating->setUser($user);
|
|
$rating->setScore($request->getPayload()->get('score'));
|
|
|
|
$em->persist($rating);
|
|
$em->flush();
|
|
|
|
return $this->json(null, 201);
|
|
}
|
|
|
|
#[Route('/api/ratings/{id}', methods: ['PATCH'])]
|
|
public function update(
|
|
int $id,
|
|
Request $request,
|
|
EntityManagerInterface $em,
|
|
OutputService $output,
|
|
RatingRepository $ratingRepository,
|
|
): JsonResponse {
|
|
$rating = $ratingRepository->find($id);
|
|
|
|
if ($rating === null) {
|
|
return $this->json(
|
|
$output->error(["UNKNOWN_RATING"])
|
|
);
|
|
}
|
|
|
|
$payload = $request->getPayload();
|
|
|
|
if ($payload->has('score')) {
|
|
$rating->setScore($payload->getInt('score'));
|
|
}
|
|
|
|
if ($payload->has('note')) {
|
|
$rating->setNote($payload->getString('note'));
|
|
}
|
|
|
|
$em->flush();
|
|
|
|
return $this->json(null, 202);
|
|
}
|
|
|
|
#[Route('/api/ratings/{id}', methods: ['DELETE'])]
|
|
public function delete(
|
|
int $id,
|
|
EntityManagerInterface $em,
|
|
OutputService $output,
|
|
RatingRepository $ratingRepository,
|
|
): JsonResponse {
|
|
$rating = $ratingRepository->find($id);
|
|
|
|
if ($rating === null) {
|
|
return $this->json(
|
|
$output->error(["UNKNOWN_RATING"])
|
|
);
|
|
}
|
|
|
|
$em->remove($rating);
|
|
$em->flush();
|
|
|
|
return $this->json(null, 204);
|
|
}
|
|
}
|