/**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $this->init($input->getOption('address'), $input->getOption('port'));
     $config = $this->getContainer()->getParameter('translations_api');
     $managedLocales = $config['managed_locales'];
     $this->output->writeln(PHP_EOL . '<info>*** Syncing documents ***</info>');
     $config = $this->getContainer()->getParameter('jlaso_translations');
     $managedLocales = $config['managed_locales'];
     $finder = new Finder();
     $finder->files()->in($this->rootDir)->name('jlaso_translations.yml');
     $this->output->writeln($this->rootDir);
     $transDocs = array();
     foreach ($finder as $file) {
         $yml = $file->getRealpath();
         $relativePath = $file->getRelativePath();
         $fileName = $file->getRelativePathname();
         $rules = Yaml::parse($yml);
         //var_dump($rules);
         if (preg_match('/\\/(\\w*)Bundle\\//', $relativePath, $matches)) {
             $bundle = $matches[1] . 'Bundle';
         } else {
             $bundle = "app*";
         }
         $this->output->writeln(PHP_EOL . $this->center($bundle));
         if (isset($rules['files'])) {
             foreach ($rules['files'] as $key => $fileRule) {
                 foreach ($managedLocales as $locale) {
                     $transFile = $relativePath . '/' . str_replace('%locale%', $locale, $fileRule);
                     if (file_exists($transFile)) {
                         $this->output->writeln(sprintf('<info>Processing file "%s"</info>', $transFile));
                         $result = $this->syncDoc($bundle, $key, $locale, $transFile);
                     } else {
                         $this->output->writeln(sprintf('<comment>File "%s" not found</comment>', $transFile));
                         $result = $this->getDoc($bundle, $key, $locale, $transFile);
                     }
                 }
             }
         }
     }
     die('ok');
     $catalogs = $this->translationsRepository->getCatalogs();
     foreach ($catalogs as $catalog) {
         // data para enviar al servidor
         $data = array();
         $this->output->writeln(PHP_EOL . sprintf('<info>Processing catalog %s ...</info>', $catalog));
         /** @var Translation[] $messages */
         $messages = $this->translationsRepository->findBy(array('domain' => $catalog));
         foreach ($messages as $message) {
             $key = $message->getKey();
             $locale = $message->getLocale();
             $data[$key][$locale] = array('message' => $message->getMessage(), 'updatedAt' => $message->getUpdatedAt()->format('c'));
         }
         //print_r($data); die;
         $this->output->writeln('uploadKeys("' . $catalog . '", $data)');
         $result = $this->clientApiService->uploadKeys($catalog, $data);
     }
     $result = $this->clientApiService->getCatalogIndex();
     if ($result['result']) {
         $catalogs = $result['catalogs'];
     } else {
         die('error getting catalogs');
     }
     foreach ($catalogs as $catalog) {
         $this->output->writeln(PHP_EOL . sprintf('<info>Processing catalog %s ...</info>', $catalog));
         $result = $this->clientApiService->downloadKeys($catalog);
         //var_dump($result); die;
         foreach ($result['data'] as $key => $data) {
             foreach ($data as $locale => $messageData) {
                 //$this->output->writeln(sprintf("\t|-- key %s:%s/%s ... ", $catalog, $key, $locale));
                 echo '.';
                 $trans = Translation::newFromArray($catalog, $key, $locale, $messageData);
                 $this->em->persist($trans);
             }
         }
         // meter las traducciones en local
     }
     $this->output->writeln(PHP_EOL . sprintf('<info>Flushing to DB ...</info>', $catalog));
     $this->em->flush();
     $this->output->writeln(PHP_EOL . '<info>Clearing SF cache ...</info>');
     /** @var Translator $translator */
     //$translator = $this->getContainer()->get('translator');
     //$translator->removeLocalesCacheFiles($managedLocales);
     exec("rm -rf " . $this->rootDir . "/app/cache/*");
     $this->output->writeln('');
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->input = $input;
     $this->output = $output;
     $ymlOptions = array('regenerate' => false, 'backup' => false, 'blank' => false);
     $yml = $this->input->getOption('yml');
     if ($yml) {
         $aux = explode(",", $yml);
         if (count($aux)) {
             foreach ($aux as $option) {
                 $ymlOptions[$option] = true;
             }
         }
     }
     if (count($ymlOptions) != 3) {
         var_dump($ymlOptions);
         die('Sorry, but you can use only regenerate,blank and backup with --yml option');
     }
     $this->init($input->getOption('address'), $input->getOption('port'));
     $config = $this->getContainer()->getParameter('translations_api');
     $managedLocales = $config['managed_locales'];
     $this->output->writeln(PHP_EOL . '<info>*** Syncing translations ***</info>');
     /**
      * uploading local catalog keys (from local table) to remote server
      */
     if ($input->getOption('upload-first') == 'yes') {
         $catalogs = $this->translationsRepository->getCatalogs();
         foreach ($catalogs as $catalog) {
             // data para enviar al servidor
             $data = array();
             $this->output->writeln(PHP_EOL . sprintf('<info>Processing catalog %s ...</info>', $catalog));
             /** @var Translation[] $messages */
             $messages = $this->translationsRepository->findBy(array('domain' => $catalog));
             foreach ($messages as $message) {
                 $key = $message->getKey();
                 $locale = $message->getLocale();
                 $bundle = $message->getBundle();
                 $fileName = $message->getFile();
                 $data[$key][$locale] = array('message' => $message->getMessage(), 'updatedAt' => $message->getUpdatedAt()->format('c'), 'fileName' => $message->getFile(), 'bundle' => $message->getBundle());
             }
             $this->output->writeln('uploadKeys("' . $catalog . '", $data)');
             $result = $this->clientApiService->uploadKeys($catalog, $data);
         }
     }
     /**
      * download the remote catalogs and integrate into local table (previously truncate local table)
      */
     // truncate local translations table
     $this->translationsRepository->truncateTranslations();
     $result = $this->clientApiService->getCatalogIndex();
     if ($result['result']) {
         $catalogs = $result['catalogs'];
     } else {
         die('error getting catalogs');
     }
     foreach ($catalogs as $catalog) {
         $this->output->writeln(PHP_EOL . sprintf('<info>Processing catalog %s ...</info>', $catalog));
         $result = $this->clientApiService->downloadKeys($catalog);
         file_put_contents(sys_get_temp_dir() . DIRECTORY_SEPARATOR . $catalog . '.json', json_encode($result));
         $bundles = $result['bundles'];
         foreach ($result['data'] as $key => $data) {
             foreach ($data as $locale => $messageData) {
                 echo '.';
                 $fileName = isset($messageData['fileName']) ? $messageData['fileName'] : '';
                 $trans = Translation::newFromArray($catalog, $key, $locale, $messageData, $bundles[$key], $fileName);
                 $this->em->persist($trans);
             }
         }
     }
     $this->output->writeln(PHP_EOL . '<info>Flushing to DB ...</info>');
     $this->em->flush();
     /**
      * regeneration of local .yml files if user wants
      */
     /** @var DialogHelper $dialog */
     $dialog = $this->getHelper('dialog');
     if ($ymlOptions['regenerate']) {
         $bundles = $this->translationsRepository->getBundles();
         foreach ($bundles as $bundle) {
             if (!$bundle) {
                 continue;
             }
             $keys = array();
             $filenames = array();
             $scheme = "";
             // in order to deduce filename from other keys
             $translations = $this->translationsRepository->getKeysByBundle($bundle);
             foreach ($translations as $translation) {
                 $locale = $translation->getLocale();
                 $file = $translation->getFile();
                 if ($file && $locale && !$scheme) {
                     $scheme = str_replace(".{$locale}.", ".%s.", $file);
                     break;
                 }
             }
             foreach ($translations as $translation) {
                 $locale = $translation->getLocale();
                 $file = $translation->getFile();
                 if ($locale && !$file && $scheme) {
                     $file = sprintf($scheme, $locale);
                 }
                 if ($file && $locale) {
                     if (!isset($filenames[$locale])) {
                         $filenames[$locale] = $file;
                     }
                     $keys[$locale][$translation->getKey()] = $translation->getMessage();
                 }
             }
             foreach ($filenames as $locale => $file) {
                 $this->output->writeln(sprintf('Generating <info>"%s"</info> ...', $file));
                 $subKeys = $keys[$locale];
                 $file = dirname($this->rootDir) . '/src/' . $file;
                 if ($ymlOptions['blank']) {
                     foreach ($subKeys as $key => $value) {
                         if (!$value) {
                             $subKeys[$key] = $key;
                         }
                     }
                 }
                 if ($ymlOptions['backup'] && file_exists($file)) {
                     copy($file, $file . '.' . date('U'));
                 }
                 @mkdir(dirname($file), 0777, true);
                 file_put_contents($file, ArrayTools::prettyYamlDump($subKeys));
             }
         }
     }
     /**
      * erasing cached translations files
      */
     $this->output->writeln(PHP_EOL . '<info>Clearing SF cache ...</info>');
     $finder = new Finder();
     $finder->files()->in($this->rootDir . "/cache")->name('*');
     foreach ($finder as $file) {
         $fileFull = $file->getRealpath();
         //$relativePath = $file->getRelativePath();
         $fileName = $file->getRelativePathname();
         if (preg_match('!/translations/.+$!i', $fileName)) {
             $this->output->writeln('removing ' . $fileName);
             unlink($file);
         }
     }
     $this->output->writeln('');
 }
 /**
  * FORMAT for the excel document
  * =============================
  *
  * one worksheet named as the language you want to import
  * one workseeht named "key" with the following format
  *   rowX colA ColB
  *     1   [1]  (1)   => (1) var substitution, [1] style substitution
  *
  * the reason for this "key system" is that normally translators haven't to translate the html labels and variables and this is a way to assure this
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $container = $this->getContainer();
     $file = $input->getArgument('excel');
     $language = $input->getArgument('language');
     $approved = (bool) $input->getOption('approved');
     //$this->init($input->getOption('address'), $input->getOption('port'));
     $phpExcel = $container->get('phpexcel');
     /** @var \PHPExcel $excel */
     $excel = $phpExcel->createPHPExcelObject();
     $excel->getProperties()->setCreator("Maarten Balliauw")->setLastModifiedBy("Maarten Balliauw")->setTitle("Office 2007 XLSX Test Document")->setSubject("Office 2007 XLSX Test Document")->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")->setKeywords("office 2007 openxml php")->setCategory("Test result file");
     $newSheet = clone $excel->getActiveSheet();
     $excel->setActiveSheetIndex(0)->setTitle($language)->setCellValue('A1', "key (don't translate)")->setCellValue('B1', $language . " (don't translate)")->setCellValue('C1', 'New language (here the translation)');
     $excel->addSheet($newSheet);
     $excel->setActiveSheetIndex(1)->setTitle('keys')->setCellValue('A4', 'Miscellaneous glyphs')->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
     $excel->getActiveSheet()->setCellValue('A8', "Hello\nWorld");
     $excel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
     $excel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
     $objWriter = new \PHPExcel_Writer_Excel5($excel);
     $objWriter->save($file);
     die('OK');
     $keySheet = $excel->getSheetByName('key');
     $key = array();
     //array_flip(json_decode($keySheet->getCell('A1'), true));
     foreach ($keySheet->getRowIterator() as $row) {
         var_dump($row->getRowIndex());
         $rowNum = $row->getRowIndex();
         $cellIterator = $row->getCellIterator();
         $cellIterator->setIterateOnlyExistingCells(false);
         // Loop all cells, even if it is not set
         foreach ($cellIterator as $cell) {
             /** @var \PHPExcel_Cell $cell */
             $cellValue = $cell->getCalculatedValue();
             switch ($cell->getColumn()) {
                 case "A":
                     $index = "[{$rowNum}]";
                     break;
                 case "B":
                     $index = "({$rowNum})";
                     break;
             }
             if (!is_null($cellValue)) {
                 $key[$index] = $cellValue;
             }
         }
     }
     // get the worksheet that match its title with language
     $worksheet = $excel->getSheetByName($language);
     $output->writeln("\n<comment>Worksheet - " . $worksheet->getTitle() . "</comment>");
     $localData = array();
     foreach ($worksheet->getRowIterator() as $row) {
         /** @var \PHPExcel_Worksheet_Row $row */
         $index = $row->getRowIndex();
         $rowNum = $row->getRowIndex();
         $keyName = $this->getCellValue($worksheet, "A{$rowNum}");
         $reference = $this->getCellValue($worksheet, "B{$rowNum}");
         $message = $this->getCellValue($worksheet, "C{$rowNum}");
         $substituted = $this->substitute($key, $message, $reference);
         //$output->writeln(sprintf("<comment>$index</comment>\t<info>%s</info> => %s => <comment>%s</comment>", $keyName, $reference, $substituted));
         $localData[$keyName] = $substituted;
     }
     // download translations from server
     $result = $this->clientApiService->getCatalogIndex();
     if ($result['result']) {
         $catalogs = $result['catalogs'];
     } else {
         die('error getting catalogs');
     }
     $tempData = array();
     foreach ($catalogs as $catalog) {
         $output->writeln(PHP_EOL . sprintf('<info>Processing "%s" catalog ...</info>', $catalog));
         $result = $this->clientApiService->downloadKeys($catalog);
         //var_dump($result); die;
         file_put_contents('/tmp/' . $catalog . '.json', json_encode($result));
         $bundles = $result['bundles'];
         //var_dump($result['data']['Bad credentials']); die;
         foreach ($result['data'] as $key => $data) {
             foreach ($data as $locale => $messageData) {
                 if ($locale == $language && isset($localData[$key])) {
                     $tempData[$key][$catalog] = array_merge($messageData, array('new' => $localData[$key]));
                     //$output->writeln(sprintf("\t|-- key %s:%s/%s ... ", $catalog, $key, $locale));
                     echo '.';
                     //$fileName = isset($messageData['fileName']) ? $messageData['fileName'] : '';
                 }
             }
         }
     }
     //print_r($tempData);
     $output->writeln("\nAnalysing the result of the match process...\n");
     $count = 0;
     // data to send to translations server
     $data = array();
     // this date guarantees that the data sent to server forces to update key
     $date = date('c');
     // get the key that are repeated
     foreach ($tempData as $key => $restData) {
         if (count($restData) > 1) {
             $output->writeln("\tthe key {$key} is in more that one catalog");
         }
         foreach ($restData as $catalog => $messageData) {
             if (!empty($messageData['new']) && $messageData['message'] != $messageData['new']) {
                 //var_dump($messageData); die;
                 $data[$key][$language] = array('approved' => $approved, 'message' => $messageData['new'], 'updatedAt' => $date, 'fileName' => isset($messageData['fileName']) ? $messageData['fileName'] : "", 'bundle' => isset($bundles[$key]) ? $bundles[$key] : "");
                 $output->writeln("the key {$key} needs to be updated");
                 $count++;
             }
         }
     }
     $total = count($localData);
     $output->writeln("\nfound {$count} keys that need to be updated from a total of {$total} keys that have the file to process\n");
     if ($count) {
         //ld($data);
         $output->writeln('uploadKeys("' . $catalog . '", $data)');
         $result = $this->clientApiService->uploadKeys($catalog, $data);
         //var_dump($result);
     }
     $output->writeln("\n done!");
 }
 /**
  * FORMAT for the excel document
  * =============================
  *
  * one worksheet named as the language you want to import
  * one workseeht named "key" with the following format
  *   rowX colA ColB
  *     1   [1]  (1)   => (1) var substitution, [1] style substitution
  *
  * the reason for this "key system" is that normally translators haven't to translate the html labels and variables and this is a way to assure this
  */
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $container = $this->getContainer();
     $file = $input->getArgument('excel');
     $language = $input->getArgument('language');
     $approved = (bool) $input->getOption('approved');
     $this->init($input->getOption('address'), $input->getOption('port'));
     $phpExcel = $container->get('phpexcel');
     /** @var \PHPExcel $excel */
     $excel = $phpExcel->createPHPExcelObject($file);
     $keySheet = $excel->getSheetByName('key');
     $key = array();
     //array_flip(json_decode($keySheet->getCell('A1'), true));
     foreach ($keySheet->getRowIterator() as $row) {
         $rowNum = $row->getRowIndex();
         $cellIterator = $row->getCellIterator();
         $cellIterator->setIterateOnlyExistingCells(false);
         // Loop all cells, even if it is not set
         foreach ($cellIterator as $cell) {
             /** @var \PHPExcel_Cell $cell */
             $cellValue = $cell->getCalculatedValue();
             switch ($cell->getColumn()) {
                 case "A":
                     $index = "[{$rowNum}]";
                     break;
                 case "B":
                     $index = "({$rowNum})";
                     break;
             }
             if (!is_null($cellValue)) {
                 $key[$index] = $cellValue;
             }
         }
     }
     // get the worksheet that match its title with language
     $worksheet = $excel->getSheetByName($language);
     $output->writeln("\n<comment>Worksheet - " . $worksheet->getTitle() . "</comment>");
     $localData = array();
     foreach ($worksheet->getRowIterator() as $row) {
         /** @var \PHPExcel_Worksheet_Row $row */
         $index = $row->getRowIndex();
         $rowNum = $row->getRowIndex();
         $keyName = $this->getCellValue($worksheet, "A{$rowNum}");
         $reference = $this->getCellValue($worksheet, "B{$rowNum}");
         $message = $this->getCellValue($worksheet, "C{$rowNum}");
         $substituted = $this->substitute($key, $message, $reference);
         //$output->writeln(sprintf("<comment>$index</comment>\t<info>%s</info> => %s => <comment>%s</comment>", $keyName, $reference, $substituted));
         $localData[$keyName] = $substituted;
     }
     // download translations from server
     $result = $this->clientApiService->getCatalogIndex();
     if ($result['result']) {
         $catalogs = $result['catalogs'];
     } else {
         die('error getting catalogs');
     }
     $tempData = array();
     foreach ($catalogs as $catalog) {
         $output->writeln(PHP_EOL . sprintf('<info>Processing "%s" catalog ...</info>', $catalog));
         $result = $this->clientApiService->downloadKeys($catalog);
         file_put_contents('/tmp/' . $catalog . '.json', json_encode($result));
         $bundles = $result['bundles'];
         foreach ($result['data'] as $key => $data) {
             foreach ($data as $locale => $messageData) {
                 if ($locale == $language && isset($localData[$key])) {
                     $tempData[$key][$catalog] = array_merge($messageData, array('new' => $localData[$key]));
                     //$output->writeln(sprintf("\t|-- key %s:%s/%s ... ", $catalog, $key, $locale));
                     echo '.';
                     //$fileName = isset($messageData['fileName']) ? $messageData['fileName'] : '';
                 }
             }
         }
     }
     $output->writeln("\nAnalysing the result of the match process...\n");
     $count = 0;
     // data to send to translations server
     $data = array();
     // this date guarantees that the data sent to server forces to update key
     $date = date('c');
     $output->writeln("found " . count($localData) . " keys in excel\n");
     // get the key that are repeated
     foreach ($tempData as $key => $restData) {
         if (count($restData) > 1) {
             $output->writeln(sprintf("\tthe key %s is in more that one catalog", $key));
         }
         foreach ($restData as $catalog => $messageData) {
             if (!empty($messageData['new']) && $messageData['message'] != $messageData['new']) {
                 //var_dump($messageData); die;
                 $data[$catalog][$key][$language] = array('approved' => $approved, 'message' => $messageData['new'], 'updatedAt' => $date, 'fileName' => isset($messageData['fileName']) ? $messageData['fileName'] : "", 'bundle' => isset($bundles[$key]) ? $bundles[$key] : "");
                 $output->writeln("the key {$key} needs to be updated");
                 $count++;
             }
         }
     }
     $total = count($localData);
     $output->writeln("\nfound {$count} keys that need to be updated from a total of {$total} keys that had the file to be processed\n");
     //var_dump($data); die;
     if ($count) {
         foreach ($data as $catalog => $restData) {
             //ld($data);
             //$output->writeln('uploadKeys("' . $catalog . '", $data)');
             $result = $this->clientApiService->uploadKeys($catalog, $restData);
             //var_dump($result);
         }
     }
     $output->writeln("\n done!");
 }