src/Domains/Word/Application/Controller/TranslateController.php line 36

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Domains\Word\Application\Controller;
  4. use App\Domains\Shared\Response\UnifiedResponse;
  5. use App\Domains\Word\Application\UseCase\TranslateUseCase;
  6. use App\Domains\Word\Application\Request\TranslateWordRequest;
  7. use App\Domains\Word\Application\Response\TranslateResponse;
  8. use DomainException;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\Finder\Exception\AccessDeniedException;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Component\Validator\Validator\ValidatorInterface;
  14. class TranslateController extends AbstractController
  15. {
  16.     public function __construct(
  17.         private readonly TranslateUseCase $translateUseCase,
  18.         private readonly ValidatorInterface $validator,
  19.     ) {
  20.     }
  21.     #[Route('/api/translate'name'translate'methods: ['POST'])]
  22.     public function index(TranslateWordRequest $request): JsonResponse
  23.     {
  24.         // This will automatically check if the user is authenticated
  25.         $user $this->getUser();
  26.         if (!$user) {
  27.             throw new AccessDeniedException('Token is invalid or expired');
  28.         }
  29.         try {
  30.             $word $this->translateUseCase->execute(
  31.                 $request->getWord(),
  32.                 $request->getLanguageFrom(),
  33.                 $request->getLanguageTo(),
  34.                 $user,
  35.             );
  36.             // Create controlled domain response
  37.             $translateResponse = new TranslateResponse(
  38.                 word$word->getWord(),
  39.                 translation$word->getTranslation(),
  40.                 meaning$word->getMeaning(),
  41.                 synonyms$word->getSynonyms(),
  42.                 usage$word->getUsage(),
  43.                 examples$word->getExamples(),
  44.                 imageFilename$word->getImageFilename(),
  45.             );
  46.             // Return custom response object directly for success
  47.             return $this->json($translateResponse->toArray());
  48.         } catch (DomainException $e) {
  49.             $response UnifiedResponse::failure($e->getMessage());
  50.         } catch (\Exception $e) {
  51.             $response UnifiedResponse::failure('An unexpected error occurred while translating the word.');
  52.         }
  53.         return $this->json($response->toArray());
  54.     }
  55. }