/**
  * Load the translations form the session
  *
  * @param string $key
  * @return Translations
  */
 public function load($key = self::DEFAULT_KEY)
 {
     $rawTranslations = $this->session->get($key);
     $translations = new Translations();
     $translations->setRawData($rawTranslations);
     return $translations;
 }
 /**
  * Test of the scanBundle protected method
  */
 public function testScanBundle()
 {
     // Configure the test
     $scanner = $this->getMockBuilder('Davamigo\\TranslatorBundle\\Model\\Translator\\Scanner')->setConstructorArgs(array($this->kernelMock))->setMethods(array('realPath', 'isDir', 'isFile', 'scanDir', 'scanFile'))->getMock();
     $scanner->expects($this->any())->method('realPath')->will($this->returnArgument(0));
     $scanner->expects($this->any())->method('isDir')->will($this->returnValue(true));
     $scanner->expects($this->any())->method('isFile')->will($this->returnValue(true));
     $scanner->expects($this->any())->method('scanDir')->will($this->returnValue(array('test.yml ')));
     $scanner->expects($this->any())->method('scanFile')->will($this->returnCallback(function ($bundleName, $resourcesFolder, $fileName) {
         $translations = new Translations();
         $translations->addFile($bundleName, $resourcesFolder, $fileName);
         $translations->addTranslation($bundleName, 'messages', 'en', 'app_name', 'The app name');
         $translations->addTranslation($bundleName, 'messages', 'es', 'app_name', 'La aplicación');
         return $translations;
     }));
     // Run the test
     /** @var Translations $translations */
     $translations = $this->runPrivateMethod($scanner, 'scanBundle', array('App', $this->testDir));
     // Expected result
     $expected = array(array('App', 'messages', 'app_name', 'The app name', 'La aplicación'));
     $locales = array('en', 'es');
     $domains = array('messages');
     // Assertions
     $this->assertEquals($expected, $translations->asArray(false));
     $this->assertEquals($locales, $translations->getLocales());
     $this->assertEquals($domains, $translations->getDomains());
 }
 /**
  * Export the translations
  *
  * @param Translations $translations The translations object
  * @param string $bundle The bundle
  * @param string $domain The domain
  * @param string $locale The locale
  * @param string $filename The filename to export
  * @return $this
  * @throws FileCreatorException
  */
 public function createFile(Translations $translations, $bundle, $domain, $locale, $filename)
 {
     $messages = $translations->getMessages($bundle, $domain, $locale);
     if (count($messages) > 0) {
         $data = $this->prepareYamlArray($messages);
         $buffer = '# ' . $bundle . '/' . $domain . '.' . $locale . '.yml' . PHP_EOL;
         $buffer .= $this->yamlDumper->dump($data, 100);
         $buffer .= PHP_EOL . PHP_EOL;
         $this->filePutContents($filename, $buffer);
     }
     return $this;
 }
 /**
  * Returns a translation object for many tests
  *
  * @return Translations
  */
 protected function getTranslationsTestObject()
 {
     $translations = new Translations();
     $translations->addTranslation('App', 'messages', 'en', 'app.name', 'The app name');
     $translations->addTranslation('App', 'messages', 'es', 'app.name', 'La aplicación');
     $translations->addTranslation('App', 'validators', 'en', 'error.not-found', 'Not found');
     $translations->addTranslation('App', 'validators', 'es', 'error.not-found', 'No encontrado');
     return $translations;
 }
 /**
  * Import the translations
  *
  * @param UploadedFile|string   $file The filename to read
  * @param Translations          $translations   The translations to export
  * @param array                 $bundles List of bundles (empty array: all)
  * @param array                 $domains List of domains (empty array: all)
  * @param array                 $locales List of locales (empty array: all)
  * @return Translations
  * @throws ImporterException
  */
 public function import($file, Translations $translations, array $bundles = array(), array $domains = array(), array $locales = array())
 {
     // Init
     $this->readResources = 0;
     $this->newTranslations = 0;
     // Get the file name
     $originalName = $this->getFileName($file);
     // Read the Excel file
     $worksheet = $this->readExcelFile($file);
     // Validate the headers
     try {
         $headers = $this->validateHeader($worksheet);
     } catch (\Exception $exc) {
         throw new ImporterException('Invalid Excel file ' . $originalName, 0, $exc);
     }
     $length = count($headers);
     $row = 1;
     do {
         ++$row;
         $bundle = $worksheet->getCellByColumnAndRow(0, $row)->getValue();
         $domain = $worksheet->getCellByColumnAndRow(1, $row)->getValue();
         $resource = $worksheet->getCellByColumnAndRow(2, $row)->getValue();
         if ($bundle && $domain && $resource) {
             ++$this->readResources;
             if ((empty($bundles) || in_array($bundle, $bundles)) && (empty($domains) || in_array($domain, $domains))) {
                 //
                 for ($col = count(static::$fixedHeader); $col < $length; ++$col) {
                     $locale = $headers[$col];
                     if (empty($locales) || in_array($locale, $locales)) {
                         $value = $worksheet->getCellByColumnAndRow($col, $row)->getValue();
                         $current = $translations->getTranslation($bundle, $domain, $locale, $resource);
                         if ($value && $value != $current) {
                             $translations->addTranslation($bundle, $domain, $locale, $resource, $value);
                             ++$this->newTranslations;
                         }
                     }
                 }
             }
         }
     } while ($bundle && $domain && $resource);
     return $translations;
 }
 /**
  * Test of the import() method
  */
 public function testImportWorksFine()
 {
     // Create mocks
     $excelImporterMock = $this->getMockBuilder('Davamigo\\TranslatorBundle\\Model\\Translator\\Excel\\ExcelImporter')->setMethods(array('getFileName', 'readExcelFile', 'validateHeader'))->disableOriginalConstructor()->getMock();
     $worksheetMock = $this->getMockBuilder('\\PHPExcel_Worksheet')->setMethods(array('getCellByColumnAndRow'))->getMock();
     $cellMock = $this->getMockBuilder('\\PHPExcel_Cell')->setMethods(array('getValue'))->disableOriginalConstructor()->getMock();
     // Configure the test
     $excelImporterMock->expects($this->once())->method('getFileName')->will($this->returnArgument(0));
     $excelImporterMock->expects($this->once())->method('readExcelFile')->will($this->returnValue($worksheetMock));
     $excelImporterMock->expects($this->once())->method('validateHeader')->will($this->returnValue(array('Bundle', 'Domain', 'Resource', 'en', 'es')));
     $worksheetMock->expects($this->atLeastOnce())->method('getCellByColumnAndRow')->will($this->returnValue($cellMock));
     $cellMock->expects($this->atLeastOnce())->method('getValue')->will($this->onConsecutiveCallsArray(array('App', 'messages', 'app.name', 'The app name', 'La aplicación', 'App', 'validators', 'error.not-found', 'Not found', 'No encontrado', null, null, null, null, null)));
     // Run the test
     /** @var ExcelImporter $excelImporterMock */
     $result = $excelImporterMock->import('some_file', new Translations());
     $readResources = $excelImporterMock->getReadResources();
     $newTranslations = $excelImporterMock->getNewTranslations();
     // Expected
     $expected = new Translations();
     $expected->addTranslation('App', 'messages', 'en', 'app.name', 'The app name');
     $expected->addTranslation('App', 'messages', 'es', 'app.name', 'La aplicación');
     $expected->addTranslation('App', 'validators', 'en', 'error.not-found', 'Not found');
     $expected->addTranslation('App', 'validators', 'es', 'error.not-found', 'No encontrado');
     // Assertions
     $this->assertEquals($expected, $result);
     $this->assertEquals(2, $readResources);
     $this->assertEquals(4, $newTranslations);
 }
 /**
  * Export the translations
  *
  * @param Translations $translations The translations to export
  * @param array        $bundles List of bundles (empty array: all)
  * @param array        $domains List of domains (empty array: all)
  * @param array        $locales List of locales (empty array: all)
  * @param string       $filename The filename to export
  * @return Response
  * @throws ExporterException
  */
 public function export(Translations $translations, array $bundles = array(), array $domains = array(), array $locales = array(), $filename = null)
 {
     // Current date and time
     $now = new \DateTime();
     // Validate the params
     if (!count($bundles)) {
         $bundles = $translations->getBundles();
     }
     if (!count($domains)) {
         $domains = $translations->getDomains();
     }
     if (!count($locales)) {
         $locales = $translations->getLocales();
     }
     if (null == $filename) {
         $filename = 'davamigo_translator_' . $now->format('Y-m-d_H-i-s') . '.yml';
     }
     // Create the Yaml file
     $buffer = '';
     foreach ($bundles as $bundle) {
         foreach ($domains as $domain) {
             foreach ($locales as $locale) {
                 $messages = $translations->getMessages($bundle, $domain, $locale);
                 if (count($messages) > 0) {
                     $buffer .= '# ' . str_repeat('-', 80) . PHP_EOL;
                     $buffer .= '# ' . $bundle . '/' . $domain . '.' . $locale . '.yml' . PHP_EOL;
                     try {
                         $data = $this->prepareYamlArray($messages);
                         $buffer .= $this->yamlDumper->dump($data, 100);
                     } catch (InvalidResourceException $exc) {
                         $buffer .= $exc->getMessage();
                     }
                     $buffer .= PHP_EOL . PHP_EOL;
                 }
             }
         }
     }
     // Create the response
     return $this->createResponse($buffer, $filename);
 }
 /**
  * Export the translations
  *
  * @param Translations $translations The translations to export
  * @param array        $bundles List of bundles (empty array: all)
  * @param array        $domains List of domains (empty array: all)
  * @param array        $locales List of locales (empty array: all)
  * @param string       $filename The filename to export
  * @return Response
  * @throws ExporterException
  */
 public function export(Translations $translations, array $bundles = array(), array $domains = array(), array $locales = array(), $filename = null)
 {
     // Current date and time
     $now = new \DateTime();
     // Validate the params
     if (!count($bundles)) {
         $bundles = $translations->getBundles();
     }
     if (!count($domains)) {
         $domains = $translations->getDomains();
     }
     if (!count($locales)) {
         $locales = $translations->getLocales();
     }
     if (null == $filename) {
         $filename = 'davamigo_translator_' . $now->format('Y-m-d_H-i-s') . '.xls';
     }
     // Create the Excel object
     $excelObj = $this->phpExcelFactory->createPHPExcelObject();
     if (null == $excelObj) {
         throw new ExporterException('Can\'t create the Excel object.');
     }
     // Se the Excel properties
     $excelObj->getProperties()->setTitle('Davamigo Symfony Translations')->setDescription('Davamigo Symfony Translations')->setCompany('Davamigo')->setCreator('Davamigo')->setLastModifiedBy('Davamigo')->setCreated($now->getTimestamp())->setModified($now->getTimestamp());
     // Create active sheet
     $excelObj->setActiveSheetIndex(0);
     $worksheet = $excelObj->getSheet(0);
     $worksheet->setTitle('Translations');
     // Create the Excel header (first row)
     $row = 1;
     $col = 0;
     $headers = array_merge(static::$fixedHeader, $locales);
     foreach ($headers as $string) {
         $cell = $worksheet->getCellByColumnAndRow($col, $row);
         $cell->setValue($string);
         $style = $worksheet->getStyle($cell->getCoordinate());
         $style->applyFromArray(static::$headerCellStyle);
         ++$col;
     }
     foreach ($bundles as $bundle) {
         foreach ($domains as $domain) {
             $resources = $translations->getResources($bundle, $domain);
             foreach ($resources as $resource) {
                 //
                 $content = array($bundle, $domain, $resource);
                 foreach ($locales as $locale) {
                     $content[] = $translations->getTranslation($bundle, $domain, $locale, $resource);
                 }
                 ++$row;
                 $col = 0;
                 foreach ($content as $string) {
                     $cell = $worksheet->getCellByColumnAndRow($col, $row);
                     $cell->setValue($string);
                     $style = $worksheet->getStyle($cell->getCoordinate());
                     $style->applyFromArray(static::$textCellStyle);
                     ++$col;
                 }
             }
         }
     }
     // Auto-size all columns
     for ($col = 0; $col < count($headers); ++$col) {
         $dimension = $worksheet->getColumnDimensionByColumn($col);
         $dimension->setAutoSize(true);
     }
     // Create the response
     return $this->createResponse($excelObj, $filename);
 }
 /**
  * Get configured translation test object
  *
  * @return Translations
  */
 protected function getConfiguredTranslationsTestObject()
 {
     $sourceTrans = $this->getTranslationsSourceTestData();
     $sourceFiles = $this->getFilesSourceTestData();
     $translations = new Translations();
     foreach ($sourceTrans as $item) {
         $translations->addTranslation($item[0], $item[1], $item[2], $item[3], $item[4]);
     }
     foreach ($sourceFiles as $item) {
         $translations->addFile($item[0], $item[1], $item[2]);
     }
     return $translations->sort();
 }
Example #10
0
 /**
  * Scan for all the translations in a file (yml, xlf or php)
  *
  * @param string $bundleName
  * @param string $resourcesFolder
  * @param string $fileName
  * @return Translations
  * @throws NotImplementedException
  */
 protected function scanFile($bundleName, $resourcesFolder, $fileName)
 {
     $translations = new Translations();
     list($domain, $locale, $loader) = explode('.', $fileName);
     if ($domain && $locale && $loader) {
         $loaderObj = $this->getFileLoader($loader);
         $resource = $resourcesFolder . '/' . $fileName;
         /** @var MessageCatalogueInterface $catalogue */
         $catalogue = $loaderObj->load($resource, $locale, $domain);
         $translations->addCatalogue($bundleName, $resourcesFolder, $catalogue);
     }
     return $translations;
 }