src/Controller/TranslateController.php line 44

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Component\String\UnicodeString;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpClient\HttpClient;
  7. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  8. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  9. use Symfony\Component\HttpFoundation\HeaderUtils;
  10. use Symfony\Component\Filesystem\Filesystem;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  12. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  13. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  14. use App\Entity\DocumentDictionary as DocumentDictionary;
  15. use App\Entity\TranslationDictionary;
  16. use App\Entity\User;
  17. use Exception;
  18. use Doctrine\ORM\EntityManagerInterface;
  19. use App\Service\utiltranslate;
  20. use App\Service\requestTranslation;
  21. use App\Message\Notify;
  22. use deeplcom\deepl;
  23. class TranslateController extends AbstractController
  24. {
  25.     private $em;
  26.     private $utiltranslate;
  27.     private $requestTranslation;
  28.     public function __construct(EntityManagerInterface $emutiltranslate $utiltranslaterequestTranslation $requestTranslation)
  29.     {
  30.         $this->em $em;
  31.         $this->utiltranslate$utiltranslate;
  32.         $this->requestTranslation=$requestTranslation;
  33.     }
  34.     /**
  35.      * @Route("/translate/show/{id}", name="showTranslate")
  36.      * @Template("dictionary/translate.html.twig")
  37.      */
  38.     public function showAction($id null)
  39.     {
  40.         
  41.         list($documents$projects) = $this->utiltranslate->getProjectsyDocuments();
  42.         if ($id) {
  43.             $em $this->getDoctrine()->getManager();
  44.             $document $em->getRepository(DocumentDictionary::class)->find($id);
  45.             if ($document) {
  46.                 $original $document->getBaseText();
  47.                 $documentName $document->getName();
  48.                 $projectName $document->getProject()->getName();
  49.             } else {
  50.                 throw $this->createNotFoundException('El documento no existe');
  51.             }
  52.         } else {
  53.             $original "";
  54.             $documentName "";
  55.             $projectName "";
  56.         }
  57.         return array(
  58.             'documents' => $documents,
  59.             'projects' => $projects,
  60.             'original' => $original,
  61.             'documentName' => $documentName,
  62.             'projectName' => $projectName
  63.         );
  64.     }
  65.     /**
  66.      * @Route("/translate/getDocumentsOfProject", name="getDocumentsOfProject")
  67.      */
  68.     public function getDocumentsOfProject()
  69.     {
  70.         
  71.         $result $this->utiltranslate->getDocumentsEntitiesOfProject($_POST['project']);
  72.         $documents = array();
  73.         if ($result) {
  74.             $documents $result[0]['documents'];
  75.             foreach ($documents as $key => $document) {
  76.                 if ($document['deadLine']) $date $document['deadLine']->format('d/m/Y');
  77.                 else $date "";
  78.                 $documents[$key]['date'] = $date;
  79.             }
  80.         } else {
  81.             $documents[] = array("name"=>"","date"=>"");
  82.         }
  83.         return new Response(json_encode($documents));
  84.     }
  85.     private function formatJumpLines($subject)
  86.     {
  87.         $search = array("</li>""</p>""</td>""}}""<br />""<br/>","<br>");
  88.         $replace = array("</li>\n""</p>\n""</td>\n""}}\n""\n""\n","\n");
  89.         $textReturn str_replace($search$replace$subject);
  90.         return $textReturn;
  91.     }
  92.     /**
  93.      * Recoge los datos recibidos por post y modifica las variables por referencia con los valores obtenidos.
  94.      * @param type $languages
  95.      * @param type $originalText
  96.      */
  97.     private function getDataPostTranslate($DDBBLanguages, &$languages, &$isArticle, &$originalText)
  98.     {
  99.         $originalText $_POST['original'];
  100.         foreach ($DDBBLanguages as $DDBBLaguage) {
  101.             $check ucfirst($DDBBLaguage) . "Check";
  102.             if ((isset($_POST[$check])) && ($_POST[$check]) !== "false")
  103.                 $languages[$DDBBLaguage] = $DDBBLaguage;
  104.         }
  105.         if (isset($_POST["isArticle"]))  $isArticle filter_var($_POST["isArticle"], FILTER_VALIDATE_BOOLEAN);
  106.         else $isArticle false;
  107.     }
  108.     private function getDataPostCreate()
  109.     {
  110.         if (isset($_POST['original'])) $fullText $_POST['original'];
  111.         else $fullText "";
  112.         if (isset($_POST['project'])) $projectName $_POST['project'];
  113.         else $projectName "No hay proyecto";
  114.         if (isset($_POST['documento'])) $documentName $_POST['documento'];
  115.         else $documentName "No hay documento";
  116.         if (isset($_POST['datepicker']))
  117.             $date = \DateTime::createFromFormat('d/m/Y'$_POST['datepicker']);
  118.         else
  119.             $date null;
  120.         if (isset($_POST["isArticle"]))  $isArticle $_POST["isArticle"];
  121.         else $isArticle false;
  122.         $langs=$this->getLanguajesFromPost();
  123.         $userId $this->getUser()->getId();
  124.         $data = array(  "fullText"=>$fullText,
  125.                         "deadLine"=>$date,
  126.                         "projectName"=>$projectName,
  127.                         "documentName"=>$documentName,
  128.                         "langs"=>$langs,
  129.                         "userId"=>$userId);
  130.         return array($data$isArticle);
  131.     }
  132.     private function getLanguajesFromPost(){
  133.         $langsToTranslate=array();
  134.         $languajes=$this->requestTranslation->getLanguajes();
  135.         //Obtenemos los lenguajes de la base de datos y comporbamos en los que se ha solicitado la traducción.
  136.         foreach ($languajes as $languaje) {
  137.             $check ucfirst($languaje) . "Check";
  138.             if ((isset($_POST[$check])) && ($_POST[$check]) !== "false")
  139.                 $langsToTranslate[] = $languaje;
  140.         }
  141.         return $langsToTranslate;
  142.     }
  143.   
  144.     /**
  145.      * @Route("/translate/translate", name="translateAction") 
  146.      * Recoge los datos de la vista de traducciones y las procesa devolviendo
  147.      * las que estén traducidas, en las que no, indica naranja si la traducción está
  148.      * pendiente, rojo si la traducción no se ha creado o gris si ha habido algún error.
  149.      */
  150.     public function translateAction()
  151.     {
  152.         //Si no se envían datos por post no se hace nada.
  153.         if (isset($_POST['original'])) {
  154.             $DDBBLanguages $this->em->getRepository(TranslationDictionary::class)->getLanguages();
  155.             $languages = array();
  156.             $fullText "";
  157.             //Obtenemos los valores de POST y modificamos las variables por referencia.
  158.             $this->getDataPostTranslate($DDBBLanguages$languages$isArticle$fullText);
  159.             //Quitamos las etiquetas HTML y sustituimos los br por saltos de linea.
  160.             if ($isArticle) {
  161.                 $response $this->requestTranslation->translateArticle($fullText$languagesNULLNULL);
  162.             } else {
  163.                 if (isset($_POST['project']) && is_string($_POST['project'])) $projectName$_POST['project'];
  164.                 else $projectName "Project no definido";
  165.                 if (isset($_POST['document']) && is_string($_POST['document'])) $documentName$_POST['document'];
  166.                 else $documentName "Documento no definido";
  167.                 $response $this->requestTranslation->translateSentences($fullText$languages$DDBBLanguagesnulltrue$projectName$documentName);
  168.             }
  169.             $json_response json_encode($response);
  170.             return new Response($json_response);
  171.         } else {
  172.             return new Response("Error");
  173.         }
  174.     }
  175.     
  176.     /**
  177.      * @Route("/falang/translate", name="translateFalang") 
  178.      * 
  179.      */
  180.     public function translateFalang()
  181.     {
  182.         //$textPrueba =  '{"falangData":{"lang":"de","data":{"virtuemart_product_id":"325","product_name":"A11","reference_field":"product_desc","product_desc":"<ul><li> Grabador NVR para cámaras IP<br /></li><li> 4 CH vídeo IP<br /></li><li> Resolución máxima grabación 5 Mpx<br /></li><li> Ancho de banda 80 Mbps<br /></li><li> Salida VGA y HDMI Full HD<br /></li><li> Admite 1 disco duro</ul>","language_id":"1"}}}';
  183.         //$input = json_decode($textPrueba,true);
  184.         //Si no se envían datos por post no se hace nada.       
  185.         $input json_decode(file_get_contents("php://input"), true);
  186.         //var_dump($input);
  187.         if (isset($input['falangData'])) {
  188.             $em $this->getDoctrine()->getManager();
  189.             
  190.             $DDBBLanguages $em->getRepository(TranslationDictionary::class)->getLanguages();
  191.             //Obtenemos los valores de POST.
  192.             $falangData $input['falangData'];
  193.             $data $falangData["data"];
  194.             $lang $falangData["lang"];
  195.             $response = array();
  196.             foreach ($data as $datum) {
  197.                 $referenceField $datum["reference_field"];
  198.                 //Si la traducción es el nombre, se envía la traducción directamente.
  199.                 if ($referenceField == "product_name") {
  200.                     $response[] = $this->getReferenceResponse($datum);
  201.                 } else {
  202.                     $response[] = $this->translateFalangText($datum[$referenceField], $datum["product_name"], $referenceField$lang$this->utiltranslate$datum["virtuemart_product_id"], $em);
  203.                 }
  204.             }
  205.             $fullResponse["response"] = $response;
  206.             $fullResponse["lang"] = $lang;
  207.             $countryCode $falangData["country_code"];
  208.             $curl $this->sendResponse(json_encode($fullResponse), $countryCode);
  209.             //Enviamos a la nueva herramienta las traducciones
  210.             //$this->createNewTTTranslation($data, $lang);
  211.             if (!$curl) {
  212.                 return new Response("Problema al enviar la respuesta " json_encode($fullResponse));
  213.             } else {
  214.                 return new Response("Terminado con éxito en intranet");
  215.             }
  216.         } else {
  217.             return new Response("No se han enviado datos por POST");
  218.         }
  219.     }
  220.     /**
  221.      * @Route("/falang/translate/category", name="translateFalangCategory") 
  222.      * Función para gestionar las traducciones de categorías de la web
  223.      */
  224.     public function translateFalangCategory()
  225.     {
  226.         //$textPrueba =  '{"falangData":{"lang":"de","data":{"virtuemart_product_id":"325","product_name":"A11","reference_field":"product_desc","product_desc":"<ul><li> Grabador NVR para cámaras IP<br /></li><li> 4 CH vídeo IP<br /></li><li> Resolución máxima grabación 5 Mpx<br /></li><li> Ancho de banda 80 Mbps<br /></li><li> Salida VGA y HDMI Full HD<br /></li><li> Admite 1 disco duro</ul>","language_id":"1"}}}';
  227.         //$input = json_decode($textPrueba,true);
  228.         //Si no se envían datos por post no se hace nada.               
  229.         $input json_decode(file_get_contents("php://input"), true);
  230.         //var_dump($input);
  231.         if (isset($input['falangData'])) {
  232.                 
  233.             $DDBBLanguages $this->em->getRepository(TranslationDictionary::class)->getLanguages();
  234.             ob_start();
  235.             //Obtenemos los valores de POST.
  236.             $falangData $input['falangData'];
  237.             $categoryName $falangData["categoryName"];
  238.             $categoryId $falangData["categoryId"];
  239.             //echo "La categoria es: ".$categoryName;
  240.             $response = array();
  241.             $user =  $this->em->getRepository(User::class)->find(5);
  242.             $fullResponse = array();
  243.             foreach ($DDBBLanguages as $lang) {
  244.                 $response $this->translateFalangCategoryName($categoryName$categoryId$lang$this->utiltranslate$DDBBLanguages$user$em);
  245.                 $fullResponse[$lang] = $response;
  246.             }
  247.             //$curl = $this->sendResponse(json_encode($fullResponse));
  248.             ob_end_clean();
  249.             return new Response(json_encode($fullResponse));
  250.         } else {
  251.             return new Response("No se han enviado datos por POST");
  252.         }
  253.     }
  254.     private function getReferenceResponse($datum)
  255.     {
  256.         $reference =  $datum["product_name"];
  257.         $fullResponse["response"] = $reference;
  258.         $fullResponse["reference_field"] = $datum["reference_field"];
  259.         $fullResponse["state"] = "ready";
  260.         $fullResponse["reference"] = $reference;
  261.         $fullResponse["productId"] = $datum["virtuemart_product_id"];
  262.         $fullResponse["originalValue"] = $reference;
  263.         return $fullResponse;
  264.     }
  265.     /**
  266.      * @param $fullText
  267.      * @param $reference
  268.      * @param $referenceField
  269.      * @param $lang
  270.      * @param $this->utiltranslate
  271.      * @param $productId
  272.      * @param $em
  273.      * @return mixed
  274.      * Traduce las fichas de productos de la web
  275.      */
  276.     private function translateFalangText($fullText$reference$referenceField$lang$productId$em)
  277.     {
  278.         $formated $this->formatJumpLines($fullText);
  279.         $noTags strip_tags($formated);
  280.         $response "";
  281.         //Comprobamos que sin las etiquetas HTMl no se quede sin contenido.
  282.         if (trim($noTags) !== "") {
  283.             $user =  $this->em->getRepository(User::class)->find(5);
  284.             //Inicializamos la posisicion de reemplazo.
  285.             $posGlobal 0;
  286.             //separamos el texto en frases.
  287.             $splittedText $this->requestTranslation->splitText($noTags);
  288.             //Eliminamos el espacio en blanco maligno
  289.             $noEvilSpaces str_replace(array(" ""&nbsp;"), " "$splittedText);
  290.             //if($referenceField =="product_s_desc") echo $referenceField." | ".  var_dump($splittedText);
  291.             $response html_entity_decode($fullTextENT_QUOTES"UTF-8");
  292.             //cogemos el proyecto y creamos el documento si es necesario.
  293.             $project $this->utiltranslate->createProject("Web");
  294.             $document $this->utiltranslate->createDocument($reference$project$user);
  295.             $send false;
  296.             $DDBBLangs null;
  297.             $state "ready";
  298.             //Procesamos cada frase.
  299.             foreach ($noEvilSpaces as $originalText) {
  300.                 //quitamos los espacios en blanco normales el principio y al final de las frases.
  301.                 $originalText html_entity_decode(trim($originalText" ."), ENT_QUOTES"UTF-8");
  302.                 // echo "el original es: ".$originalText."<br>";
  303.                 if ($originalText !== "") {
  304.                     usleep(300);
  305.                     list($encontrado$matches) = $this->utiltranslate->encontrarOriginal($originalText);
  306.                     //$encontrado = $this->utiltranslate->findOriginal($originalText);
  307.                     if ($encontrado//Si el orgininal está registrado
  308.                     {
  309.                         //Obtiene las traducciones si están traducidas. Si no, devuelve -1 o -2.
  310.                         $translation $this->utiltranslate->getTranslation(
  311.                             $originalText,
  312.                             $lang,
  313.                             $encontrado,
  314.                             $matches
  315.                         );
  316.                         //Si falta por crear la traducción la añadimos al original.
  317.                         if ($translation === -3) {
  318.                             $this->utiltranslate->createDictionary(
  319.                                 $originalText,
  320.                                 "Web",
  321.                                 $reference,
  322.                                 array($lang),
  323.                                 $project,
  324.                                 $document,
  325.                                 $user
  326.                             );
  327.                             $send true;
  328.                             $state "pending";
  329.                             echo "Faltaba por crear la traducción para el original es: " $originalText " (" $reference ") <br/>";
  330.                         } else if ($translation === -2) {
  331.                             $state "pending";
  332.                             echo "Traducción pendiente para: " $originalText "(" $reference "). Estado: " $translation "<br>";
  333.                         }
  334.                         //echo "La traducción ".$translation." <br>";
  335.                         //Marcamos la respuesta con el color correspondiente
  336.                         $translation =  $this->requestTranslation->manageTranslation($originalText$translation);
  337.                         $response $this->requestTranslation->replace($originalText$translation$response$posGlobal$reference);
  338.                         //Función para formatear el estado de la traducción.
  339.                         $posGlobal += strlen($translation) - 1;
  340.                     } else {
  341.                         //si el original no existe, lo tenemos que crear y mandamos la respuesta vacia.
  342.                         $send true;
  343.                         $state "pending";
  344.                         echo "Creamos el original (" $originalText ")  (" $reference ")<br>";
  345.                         $DDBBLangs $this->utiltranslate->getLanguagesAction();
  346.                         //Función para crear el original y la traducción en TODOS los idiomas.
  347.                         $this->utiltranslate->createDictionary(
  348.                             $originalText,
  349.                             "Web",
  350.                             $reference,
  351.                             $DDBBLangs,
  352.                             $project,
  353.                             $document,
  354.                             $user
  355.                         );
  356.                         $error $this->requestTranslation->marcarError($originalText);
  357.                         $response $this->requestTranslation->replace($originalText$error$response$posGlobal$reference);
  358.                         $posGlobal += strlen($error) - 1;
  359.                     }
  360.                 }
  361.             }
  362.             //Si hay idiomas es que se ha creado un original.
  363.             if ($DDBBLangs) {
  364.                 $this->utiltranslate->sendNewTranslations($DDBBLangs);
  365.             }
  366.             //Si no hay idiomas y se ha marcado el send se manda en el idioma en concreto.
  367.             else if ($send) {
  368.                 $this->utiltranslate->sendNewTranslations(array($lang));
  369.             }
  370.         } else { // Si el texto enviado está vacío no se hace nada.
  371.             $response "El POST no contiene mensaje";
  372.             $state "pending";
  373.         }
  374.         $fullResponse["response"] = $response;
  375.         $fullResponse["reference_field"] = $referenceField;
  376.         $fullResponse["state"] = $state;
  377.         $fullResponse["reference"] = $reference;
  378.         $fullResponse["productId"] = $productId;
  379.         $fullResponse["originalValue"] = $fullText;
  380.         return $fullResponse;
  381.     }
  382.     private function translateFalangCategoryName($categoryName$categoryId$lang$DDBBLangs$user$em)
  383.     {
  384.         $categoryName trim($categoryName);
  385.         $response "";
  386.         $documentName $categoryName "-" $categoryId;
  387.         if ($categoryName !== "") {
  388.             $project $this->utiltranslate->createProject("WebCategories");
  389.             $document $this->utiltranslate->createDocument($documentName$project$user);
  390.             $send false;
  391.             $DDBBLangs null;
  392.             $state "ready";
  393.             list($encontrado$matches) = $this->utiltranslate->encontrarOriginal($categoryName);
  394.             //$encontrado = $this->utiltranslate->findOriginal($originalText);
  395.             if ($encontrado//Si el orgininal está registrado
  396.             {
  397.                 //Obtiene las traducciones si están traducidas. Si no, devuelve -1 o -2.
  398.                 $translation $this->utiltranslate->getTranslation(
  399.                     $categoryName,
  400.                     $lang,
  401.                     $encontrado,
  402.                     $matches,
  403.                     $document
  404.                 );
  405.                 //Si falta por crear la traducción la añadimos al original.
  406.                 if ($translation === -3) {
  407.                     $this->utiltranslate->createDictionary(
  408.                         $categoryName,
  409.                         "WebCategories",
  410.                         $categoryName,
  411.                         array($lang),
  412.                         $project,
  413.                         $document,
  414.                         $user
  415.                     );
  416.                     $send true;
  417.                     $state "pending";
  418.                     $this->utiltranslate->sendNewTranslations(array($lang));
  419.                     echo "El original es: " $categoryName "  (EN -3)<br/>";
  420.                 } else if ($translation === -2) {
  421.                     $state "pending";
  422.                     echo "El original es: " $categoryName ". Estado: " $translation "<br>";
  423.                 }
  424.                 //echo "La traducción ".$translation." <br>";
  425.                 //Marcamos la respuesta con el color correspondiente
  426.                 $translation =  $this->requestTranslation->manageTranslation($categoryName$translation);
  427.                 $response $translation;
  428.             } else {
  429.                 //si el original no existe, lo tenemos que crear y mandamos la respuesta vacia.
  430.                 $send true;
  431.                 $state "pending";
  432.                 echo "Creamos el original (" $categoryName ")  <br>";
  433.                 //Función para crear el original y la traducción en TODOS los idiomas.
  434.                 $this->utiltranslate->createDictionary(
  435.                     $categoryName,
  436.                     "WebCategories",
  437.                     $categoryName,
  438.                     $DDBBLangs,
  439.                     $project,
  440.                     $document,
  441.                     $user
  442.                 );
  443.                 $error $this->requestTranslation->marcarError($categoryName);
  444.                 $response $error;
  445.                 $this->utiltranslate->sendNewTranslations($DDBBLangs);
  446.             }
  447.         } else { // Si el texto enviado está vacío no se hace nada.
  448.             $response "El POST no contiene mensaje";
  449.             $state "pending";
  450.         }
  451.         $fullResponse["response"] = $response;
  452.         $fullResponse["state"] = $state;
  453.         return $fullResponse;
  454.     }
  455.     private function sendResponse($response$countryCode "ES")
  456.     {
  457.         if ($countryCode == "ES") {
  458.             $url "localhost/es?option=com_sync&task=syncTranslations.receiveResponse";
  459.         } else {
  460.             $url "localhost/es?option=com_sync&task=syncTranslations.receiveResponse";
  461.         }
  462.         $ch curl_init($url);
  463.         # Setup request to send json via POST.
  464.         curl_setopt($chCURLOPT_POSTFIELDS$response);
  465.         curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type:application/json'));
  466.         //Añadido para no tener problema con el certificado propio
  467.         curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  468.         # Return response instead of printing.
  469.         curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  470.         # Send request.
  471.         $result curl_exec($ch);
  472.         curl_close($ch);
  473.         //var_dump($result);
  474.         return $result;
  475.     }
  476.     private function cleanArray($array)
  477.     {
  478.         foreach ($array as $key => $element) {
  479.             if (strpos($element"class='errorDiv'") !== false) {
  480.                 unset($array[$key]);
  481.             } else $array[$key] = strip_tags($element);
  482.         }
  483.         return $array;
  484.     }
  485.     /**
  486.      * @Route("/translate/createEntities", name="createEntities")
  487.      */
  488.     public function createEntitiesAction(){
  489.     
  490.        list($data,$isArticle) = $this->getDataPostCreate();
  491.         if ($data["fullText"] !== "") {
  492.             $this->dispatchMessage(new Notify($data,$isArticle));
  493.         }
  494.         return $this->redirectToRoute('showTranslate');
  495.     }
  496.     /**
  497.      * @Route("/translate/file", name="translateFile")
  498.      */
  499.     public function translateFile(Request $request){
  500.         $authKey "62beb388-21eb-bd33-2106-853293519c50";
  501.         $translator = new \DeepL\Translator($authKey);
  502.         $langMapping = array("ES"=>"ES","PT"=>"PT-PT","EN"=>"EN-GB","FR"=>"FR","DE"=>"DE","IT"=>"IT""NL"=>"NL");
  503.         $lang$langMapping[$request->get('lang')];
  504.         $tmpRoot $this->getParameter('kernel.project_dir') .'/src/tmp/';
  505.         $requestFile $request->files->get('document');
  506.         $fullFileName $requestFile->getClientOriginalName();
  507.         list($fromFileName$fileExtension)=$this->splitExtension($fullFileName);
  508.         $fromFilePath =  $tmpRoot.$fullFileName;
  509.         $fromFileName = new UnicodeString($fromFileName);
  510.         $toFileName $fromFileName->ascii() ."_".$lang.".".$fileExtension;
  511.         $toFilePath $tmpRoot$toFileName;
  512.         if (file_exists($toFilePath)) {
  513.             unlink($toFilePath);
  514.         }
  515.         rename($requestFile,$fromFilePath);
  516.         try {
  517.             $translator->translateDocument(
  518.                 $fromFilePath,
  519.                 $toFilePath ,null,
  520.                 $lang
  521.             );
  522.             $response = new BinaryFileResponse($toFilePath);
  523.             $disposition HeaderUtils::makeDisposition(
  524.                 HeaderUtils::DISPOSITION_ATTACHMENT,
  525.                 $toFileName
  526.             );
  527.             
  528.             $response->headers->set('Content-Disposition'$disposition);
  529.         } catch (\DeepL\DocumentTranslationException $error) {
  530.             $response = new response ('Error occurred while translating document: ' . ($error->getMessage() ?? 'unknown error'));
  531.         }
  532.        return $response;
  533.      }
  534.      private function splitExtension($file){
  535.         $splitFile=explode(".",$file);
  536.         $lastIndex=count($splitFile)-1;
  537.         $fileExtension $splitFile[$lastIndex];
  538.         unset($splitFile[$lastIndex]);
  539.         $fileName implode(".",$splitFile);
  540.         return array($fileName,$fileExtension);
  541.      }
  542.  
  543. }