Пример #1
3
 public function register(Fol $app)
 {
     $app['middleware'] = function ($app) {
         $middleware = [];
         if ($app->has('users')) {
             $middleware[] = new Middlewares\DigestAuthentication($app['users']);
         }
         $middleware[] = new Middlewares\Expires();
         $middleware[] = (new Middlewares\ErrorHandler())->catchExceptions()->statusCode(function ($code) {
             return $code > 400 && $code < 600;
         })->arguments($app);
         $middleware[] = new Middlewares\BasePath($app->getUrlPath());
         $middleware[] = new Middlewares\TrailingSlash();
         $middleware[] = new Middlewares\ContentType();
         $middleware[] = new Middlewares\ContentLanguage(['en', 'gl', 'es']);
         $middleware[] = function ($request, $next) use($app) {
             $language = $request->getHeaderLine('Accept-Language');
             $translator = new Translator();
             $translator->loadTranslations(Translations::fromPoFile(dirname(dirname(__DIR__)) . '/locales/' . $language . '.po'));
             $prev = $translator->register();
             $app['templates']->addData(['language' => $language]);
             $response = $next($request);
             if ($prev) {
                 $prev->register();
             }
             return $response;
         };
         $middleware[] = (new Middlewares\MethodOverride())->parsedBodyParameter('method-override');
         $middleware[] = (new Middlewares\Reader(dirname(dirname(__DIR__)) . '/assets'))->continueOnError();
         $middleware[] = (new Middlewares\AuraRouter($app['router']))->arguments($app);
         return new Dispatcher($middleware);
     };
 }
Пример #2
1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->writeSection($output, 'Po to Csv converter');
     $this->cwd = getcwd() . DIRECTORY_SEPARATOR;
     $output->writeln('<info>Using CWD</info> ' . $this->cwd);
     $poFiles = $this->getInputPoFiles($input, $output);
     $outputFolder = $this->getOutputFolder($input, $output);
     $useDefaults = $input->getOption('use-defaults');
     if ($useDefaults) {
         $output->writeln('<info>Po files</info>:');
         $this->writeList($output, $poFiles);
         $output->writeln(['', '<info>Output folder</info>: ' . $outputFolder]);
     }
     $poHandles = [];
     foreach ($poFiles as $poFile) {
         $key = basename($poFile, '.po');
         $output->writeln('<info>loading ' . $key . '</info>...');
         $poHandles[$key] = Translations::fromPoFile($poFile);
     }
     $output->writeln('<info>merging po files</info>...');
     $csvArray = [];
     foreach ($poHandles as $language => $poHandle) {
         foreach ($poHandle as $translation) {
             $original = trim($translation->original);
             $translation = trim($translation->translation);
             if (!isset($csvArray[$original])) {
                 $csvArray[$original] = [$language => $translation];
             } elseif (!isset($csvArray[$original][$language])) {
                 $csvArray[$original][$language] = $translation;
             } elseif ($csvArray[$original][$language] != $translation) {
                 $csvArray[$original][$language] = $this->handleConflict($input, $output, $original, $csvArray[$original][$language], $translation);
             }
         }
     }
     $output->writeln('<info>writing csv</info>...');
     $writer = Writer::createFromFileObject(new SplTempFileObject());
     $writer->setDelimiter(';');
     $header = ['original'];
     $header = array_merge($header, array_keys($poHandles));
     $writer->insertOne($header);
     foreach ($csvArray as $original => $item) {
         $row = [];
         foreach ($header as $column) {
             if ($column === 'original') {
                 $row[] = $original;
             } else {
                 $row[] = isset($item[$column]) ? $item[$column] : null;
             }
         }
         $writer->insertOne($row);
     }
     $outputFile = $outputFolder . DIRECTORY_SEPARATOR . 'translations.csv';
     file_put_contents($outputFile, $writer->__toString());
     $output->writeln('<info>done. output file is</info> ' . $outputFile);
 }
Пример #3
0
 public static function process(\Twig_Node $node, Translations $translations, $file)
 {
     $fileReference = str_replace(realpath(self::$rootDir . '/../') . '/', "", $file);
     if ($node instanceof TransNode) {
         //Process nodes that {% trans %} blocks
         $body = new \Twig_Node_Expression_Constant($node->getNode('body')->getAttribute('data'), $node->getLine());
         $compiledTranslation = eval('return ' . self::$twig->compile($body) . ';');
         $translations->insert('', $compiledTranslation)->addReference($fileReference, $node->getLine());
     }
     if ($node instanceof \Twig_Node_Expression_Function) {
         //Process nodes that are function expressions
         if ($node->getAttribute('name') == '__') {
             //Check the function name for __()
             foreach ($node->getNode('arguments') as $argument) {
                 //Grab the argument
                 $key = eval('return ' . self::$twig->compile($argument) . ';');
                 $translations->insert('', $key)->addReference($fileReference, $node->getLine());
                 break;
                 //I only needed the first argument in my implementation
             }
         }
     }
     //Recursively loop through the AST
     foreach ($node as $child) {
         if ($child instanceof \Twig_Node) {
             self::process($child, $translations, $file);
         }
     }
 }
 /**
  * All known translation functions are covered.
  */
 public function testAllKnownTranslationFunctionsAreCovered()
 {
     $extractor = new WordPressExtractor();
     $translations = new Translations();
     $translations->setDomain('test');
     $translations = $extractor->fromDirectory($this->getResourcesPath() . 'commonSources', $translations);
     // file_put_contents($this->getResourcesPath() . 'commonSources.php', var_export($arrayCopy, true));
     $poContent = $translations->toPoString();
     // strip base path for better comparison
     $poContent = str_replace($this->getResourcesPath(), '', $poContent);
     $this->assertContains('"translate"', $poContent);
     $this->assertContains('"translate_with_gettext_context"', $poContent);
     $this->assertContains('"__"', $poContent);
     $this->assertContains('"_x"', $poContent);
     $this->assertContains('"_e"', $poContent);
     $this->assertContains('"_ex"', $poContent);
     $this->assertContains('"esc_attr__"', $poContent);
     $this->assertContains('"esc_attr_e"', $poContent);
     $this->assertContains('"esc_attr_x"', $poContent);
     $this->assertContains('"esc_html__"', $poContent);
     $this->assertContains('"esc_html_e"', $poContent);
     $this->assertContains('"esc_html_x"', $poContent);
     $this->assertContains('"_n-single"', $poContent);
     $this->assertContains('"_n-plural"', $poContent);
     $this->assertContains('"_nx-context"', $poContent);
     $this->assertContains('"_nx-single"', $poContent);
     $this->assertContains('"_nx-plural"', $poContent);
     $this->assertContains('"_n_noop-singular"', $poContent);
     $this->assertContains('"_n_noop-plural"', $poContent);
     $this->assertContains('"_nx_noop-context"', $poContent);
     $this->assertContains('"_nx_noop-singular"', $poContent);
     $this->assertContains('"_nx_noop-plural"', $poContent);
 }
Пример #5
0
 /**
  * main
  *
  */
 public function main()
 {
     $schemaPo = APP . 'Locale' . DS . 'schema.pot';
     $conn = ConnectionManager::get('default');
     $collection = $conn->schemaCollection();
     $translations = new Translations();
     $tables = $collection->listTables();
     foreach ($tables as $table) {
         $translations->insert($table, Inflector::humanize(Inflector::underscore($table)));
         $translations->insert($table, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))));
         $columns = $collection->describe($table)->columns();
         foreach ($columns as $column) {
             $c = $collection->describe($table)->column($column);
             $comment = $c['comment'];
             $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore($column)));
             $translations[] = $t;
             $t->setTranslation($comment);
             $t = new Translation($table . '.' . $column, Inflector::humanize(Inflector::underscore(Inflector::singularize($table))) . ' ' . Inflector::humanize(Inflector::underscore($column)));
             $translations[] = $t;
             $t->setTranslation($comment);
         }
     }
     $poString = $translations->toPoString();
     $caked = preg_replace('/msgctxt "([^"]+)"/i', '#: \\1', $poString);
     $this->createFile($schemaPo, $caked);
 }
Пример #6
0
 /**
  * @deprecated
  */
 public function exportTranslations()
 {
     $translations = new Translations();
     foreach ($this->getList() as $type) {
         $translations->insert('AttributeTypeName', $type->getAttributeTypeName());
     }
     return $translations;
 }
Пример #7
0
 public function mergeTranslationsWithSectionFile(Section $section, Translations $translations)
 {
     $file = DIR_LANGUAGES_SITE_INTERFACE . '/' . $section->getLocale() . '.po';
     if (is_file($file)) {
         $sectionTranslations = PoExtractor::fromFile($file);
         $translations->mergeWith($sectionTranslations);
     }
 }
Пример #8
0
 /**
  * Returns the headers as a string.
  * 
  * @param Translations $translations
  *
  * @return string
  */
 private static function generateHeaders(Translations $translations)
 {
     $headers = '';
     foreach ($translations->getHeaders() as $name => $value) {
         $headers .= sprintf("%s: %s\n", $name, $value);
     }
     return $headers;
 }
Пример #9
0
 /**
  * @deprecated
  */
 public function exportTranslations()
 {
     $translations = new Translations();
     $sets = $this->entityManager->getRepository('\\Concrete\\Core\\Entity\\Attribute\\Set')->findAll();
     foreach ($sets as $set) {
         $translations->insert('AttributeSet', $set->getAttributeSetName());
     }
     return $translations;
 }
Пример #10
0
 /**
  * @deprecated
  */
 public function exportTranslations()
 {
     $translations = new Translations();
     $keys = $this->entityManager->getRepository('\\Concrete\\Core\\Entity\\Attribute\\Key\\Key')->findAll();
     foreach ($keys as $key) {
         $translations->insert('AttributeKeyName', $key->getAttributeKeyName());
     }
     return $translations;
 }
Пример #11
0
 /**
  * @deprecated
  */
 public function exportTranslations()
 {
     $translations = new Translations();
     $list = $this->getList();
     $akcNameMap = array('collection' => 'Page attributes', 'user' => 'User attributes', 'file' => 'File attributes');
     foreach ($list as $category) {
         $akcHandle = $category->getAttributeKeyCategoryHandle();
         $translations->insert('AttributeKeyCategory', isset($akcNameMap[$akcHandle]) ? $akcNameMap[$akcHandle] : ucwords(str_replace(array('_', '-', '/'), ' ', $akcHandle)));
     }
     return $translations;
 }
Пример #12
0
 /**
  * {@inheritdoc}
  *
  * @see \C5TL\Parser::parseDirectoryDo()
  */
 protected function parseDirectoryDo(\Gettext\Translations $translations, $rootDirectory, $relativePath, $subParsersFilter, $exclude3rdParty)
 {
     $themesPresets = array();
     $prefix = $relativePath === '' ? '' : "{$relativePath}/";
     $matches = null;
     foreach (array_merge(array(''), $this->getDirectoryStructure($rootDirectory, $exclude3rdParty)) as $child) {
         $presetsAbsDirectory = $child === '' ? $rootDirectory : "{$rootDirectory}/{$child}";
         if (preg_match('%(?:^|/)themes/\\w+/css/presets$%', $presetsAbsDirectory, $matches)) {
             $dirList = @scandir($presetsAbsDirectory);
             if ($dirList === false) {
                 throw new \Exception("Unable to parse directory {$presetsAbsDirectory}");
             }
             $shownChild = $child === '' ? rtrim($prefix, '/') : $prefix . $child;
             foreach ($dirList as $file) {
                 if ($file[0] !== '.' && preg_match('/[^.].*\\.less$/i', $file)) {
                     $fileAbs = "{$presetsAbsDirectory}/{$file}";
                     if (is_file($fileAbs)) {
                         $content = @file_get_contents($fileAbs);
                         if ($content === false) {
                             throw new \Exception("Error reading file '{$fileAbs}'");
                         }
                         $content = str_replace("\r", "\n", str_replace("\r\n", "\n", $content));
                         // Strip multiline comments
                         $content = preg_replace_callback('|/\\*.*?\\*/|s', function ($matches) {
                             return str_repeat("\n", substr_count($matches[0], "\n"));
                         }, $content);
                         foreach (array("'", '"') as $quote) {
                             if (preg_match('%(?:^|\\n|;)[ \\t]*@preset-name:\\s*' . $quote . '([^' . $quote . ']*)' . $quote . '\\s*(?:;|$)%s', $content, $matches)) {
                                 $presetName = $matches[1];
                                 $presetLine = null;
                                 $p = strpos($content, $matches[0]);
                                 if ($p !== false) {
                                     $presetLine = substr_count(substr($content, 0, $p), "\n") + 1;
                                 }
                                 if (!isset($themesPresets[$presetName])) {
                                     $themesPresets[$presetName] = array();
                                 }
                                 $themesPresets[$presetName][] = array($shownChild . "/{$file}", $presetLine);
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     foreach ($themesPresets as $themesPreset => $references) {
         $translation = $translations->insert('PresetName', ucwords(str_replace(array('_', '-', '/'), ' ', $themesPreset)));
         foreach ($references as $reference) {
             $translation->addReference($reference[0], $reference[1]);
         }
     }
 }
Пример #13
0
 /**
  * {@inheritDoc}
  */
 public static function fromString($string, Translations $translations = null, $file = '')
 {
     if ($translations === null) {
         $translations = new Translations();
     }
     if ($entries = json_decode($string, true)) {
         foreach ($entries as $original => $translation) {
             $translations->insert(null, $original)->setTranslation($translation);
         }
     }
     return $translations;
 }
Пример #14
0
 /**
  * Extract and insert a new translation.
  * 
  * @param Translations $translations
  * @param string       $key
  * @param string       $message
  */
 protected static function insertTranslation(Translations $translations, $key, $message)
 {
     $context_glue = '\\u0004';
     $key = explode($context_glue, $key);
     $context = isset($key[1]) ? array_shift($key) : '';
     $original = array_shift($key);
     $translation = array_shift($message);
     $plural_translation = array_shift($message);
     $entry = $translations->insert($context, $original);
     $entry->setTranslation($translation);
     $entry->setPluralTranslation($plural_translation);
 }
Пример #15
0
 public static function exportTranslations()
 {
     $translations = new Translations();
     $em = \Database::connection()->getEntityManager();
     $options = $em->getRepository(SelectValueOption::class)->findAll();
     /**
      * @var $option SelectValueOption
      */
     foreach ($options as $option) {
         $translations->insert('SelectAttributeValue', $option->getSelectAttributeOptionValue());
     }
     return $translations;
 }
Пример #16
0
 /**
  * Search for specific functions and create translations.
  *
  * @param array        $functions    The gettext functions to search
  * @param Translations $translations The translations instance where save the values
  * @param string       $file         The filename used to the reference
  */
 public function saveGettextFunctions(array $functions, Translations $translations, $file = '')
 {
     foreach ($this->getFunctions() as $function) {
         list($name, $line, $args) = $function;
         if (!isset($functions[$name])) {
             continue;
         }
         $translation = null;
         switch ($functions[$name]) {
             case '__':
                 if (!isset($args[0])) {
                     continue 2;
                 }
                 $original = $args[0];
                 if ($original !== '') {
                     $translation = $translations->insert('', $original);
                 }
                 break;
             case 'n__':
                 if (!isset($args[1])) {
                     continue 2;
                 }
                 $original = $args[0];
                 $plural = $args[1];
                 if ($original !== '') {
                     $translation = $translations->insert('', $original, $plural);
                 }
                 break;
             case 'p__':
                 if (!isset($args[1])) {
                     continue 2;
                 }
                 $context = $args[0];
                 $original = $args[1];
                 if ($original !== '') {
                     $translation = $translations->insert($context, $original);
                 }
                 break;
             default:
                 throw new Exception('Not valid functions');
         }
         if (isset($translation)) {
             $translation->addReference($file, $line);
             if (isset($function[3])) {
                 foreach ($function[3] as $extractedComment) {
                     $translation->addExtractedComment($extractedComment);
                 }
             }
         }
     }
 }
Пример #17
0
 /**
  * main
  *
  */
 public function main()
 {
     $default = APP . 'Locale' . DS . 'default.pot';
     $response = $this->in("What is the full path you would like to merge file (created pot file)?\nExample:" . $default . "\n[Q]uit", null, $default);
     if (strtoupper($response) === 'Q') {
         $this->out('Merge Aborted');
         $this->_stop();
     }
     $created = new File($response, false, 0755);
     if (!$created->exists()) {
         $this->err('The file path you supplied was not found. Please try again.');
         $this->_stop();
     }
     $default = APP . 'Locale' . DS . 'ja' . DS . 'default.po';
     $response = $this->in("What is the full path you would like to merge file (current po file)?\nExample: " . $default . "\n[Q]uit", null, $default);
     if (strtoupper($response) === 'Q') {
         $this->out('Merge Aborted');
         $this->_stop();
     }
     $current = new File($response, false, 0755);
     if (!$current->exists()) {
         $this->err('The file path you supplied was not found. Please try again.');
         $this->_stop();
     }
     $createdTranslations = Translations::fromPoFile($created->path);
     $createdTranslations->addFromPoFile($current->path);
     $merged = $createdTranslations->toPoString();
     $this->createFile($current->path, $merged);
 }
Пример #18
0
 /**
  * {@parentDoc}.
  */
 public static function toString(Translations $translations)
 {
     $lines = array('msgid ""', 'msgstr ""');
     $headers = $translations->getHeaders();
     $headers['PO-Revision-Date'] = date('c');
     foreach ($headers as $name => $value) {
         $lines[] = '"' . $name . ': ' . $value . '\\n"';
     }
     $lines[] = '';
     //Translations
     foreach ($translations as $translation) {
         if ($translation->hasComments()) {
             foreach ($translation->getComments() as $comment) {
                 $lines[] = '# ' . $comment;
             }
         }
         if ($translation->hasExtractedComments()) {
             foreach ($translation->getExtractedComments() as $comment) {
                 $lines[] = '#. ' . $comment;
             }
         }
         if ($translation->hasReferences()) {
             foreach ($translation->getReferences() as $reference) {
                 $lines[] = '#: ' . $reference[0] . (!is_null($reference[1]) ? ':' . $reference[1] : null);
             }
         }
         if ($translation->hasFlags()) {
             $lines[] = '#, ' . implode(',', $translation->getFlags());
         }
         if ($translation->hasContext()) {
             $lines[] = 'msgctxt ' . self::convertString($translation->getContext());
         }
         self::addLines($lines, 'msgid', $translation->getOriginal());
         if ($translation->hasPlural()) {
             self::addLines($lines, 'msgid_plural', $translation->getPlural());
             self::addLines($lines, 'msgstr[0]', $translation->getTranslation());
             foreach ($translation->getPluralTranslation() as $k => $v) {
                 self::addLines($lines, 'msgstr[' . ($k + 1) . ']', $v);
             }
         } else {
             self::addLines($lines, 'msgstr', $translation->getTranslation());
         }
         $lines[] = '';
     }
     return implode("\n", $lines);
 }
Пример #19
0
 /**
  * {@parentDoc}.
  */
 public static function toString(Translations $translations, array $options = [])
 {
     $pluralForm = $translations->getPluralForms();
     $pluralSize = is_array($pluralForm) ? $pluralForm[0] - 1 : null;
     $lines = ['msgid ""', 'msgstr ""'];
     foreach ($translations->getHeaders() as $name => $value) {
         $lines[] = sprintf('"%s: %s\\n"', $name, $value);
     }
     $lines[] = '';
     //Translations
     foreach ($translations as $translation) {
         if ($translation->hasComments()) {
             foreach ($translation->getComments() as $comment) {
                 $lines[] = '# ' . $comment;
             }
         }
         if ($translation->hasExtractedComments()) {
             foreach ($translation->getExtractedComments() as $comment) {
                 $lines[] = '#. ' . $comment;
             }
         }
         if ($translation->hasReferences()) {
             foreach ($translation->getReferences() as $reference) {
                 $lines[] = '#: ' . $reference[0] . (!is_null($reference[1]) ? ':' . $reference[1] : null);
             }
         }
         if ($translation->hasFlags()) {
             $lines[] = '#, ' . implode(',', $translation->getFlags());
         }
         if ($translation->hasContext()) {
             $lines[] = 'msgctxt ' . self::convertString($translation->getContext());
         }
         self::addLines($lines, 'msgid', $translation->getOriginal());
         if ($translation->hasPlural()) {
             self::addLines($lines, 'msgid_plural', $translation->getPlural());
             self::addLines($lines, 'msgstr[0]', $translation->getTranslation());
             foreach ($translation->getPluralTranslations($pluralSize) as $k => $v) {
                 self::addLines($lines, 'msgstr[' . ($k + 1) . ']', $v);
             }
         } else {
             self::addLines($lines, 'msgstr', $translation->getTranslation());
         }
         $lines[] = '';
     }
     return implode("\n", $lines);
 }
Пример #20
0
 /**
  * {@inheritdoc}
  */
 public static function fromString($string, Translations $translations, array $options = [])
 {
     $xml = new SimpleXMLElement($string, null, false);
     foreach ($xml->file as $file) {
         if (isset($file->notes)) {
             foreach ($file->notes->note as $note) {
                 $translations->setHeader($note['id'], (string) $note);
             }
         }
         foreach ($file->unit as $unit) {
             foreach ($unit->segment as $segment) {
                 $targets = [];
                 foreach ($segment->target as $target) {
                     $targets[] = (string) $target;
                 }
                 $translation = new Translation(null, (string) $segment->source);
                 $translation->setTranslation(array_shift($targets));
                 $translation->setPluralTranslations($targets);
                 if (isset($unit->notes)) {
                     foreach ($unit->notes->note as $note) {
                         switch ($note['category']) {
                             case 'context':
                                 $translation = $translation->getClone((string) $note);
                                 break;
                             case 'extracted-comment':
                                 $translation->addExtractedComment((string) $note);
                                 break;
                             case 'flag':
                                 $translation->addFlag((string) $note);
                                 break;
                             case 'reference':
                                 $ref = explode(':', (string) $note, 2);
                                 $translation->addReference($ref[0], isset($ref[1]) ? $ref[1] : null);
                                 break;
                             default:
                                 $translation->addComment((string) $note);
                                 break;
                         }
                     }
                 }
                 $translations[] = $translation;
             }
         }
     }
 }
Пример #21
0
 /**
  * Generates an array with all translations.
  * 
  * @param Translations $translations
  *
  * @return array
  */
 private static function buildMessages(Translations $translations)
 {
     $pluralForm = $translations->getPluralForms();
     $pluralSize = is_array($pluralForm) ? $pluralForm[0] - 1 : null;
     $messages = [];
     $context_glue = '\\u0004';
     foreach ($translations as $translation) {
         $key = ($translation->hasContext() ? $translation->getContext() . $context_glue : '') . $translation->getOriginal();
         if ($translation->hasPluralTranslations(true)) {
             $message = $translation->getPluralTranslations($pluralSize);
             array_unshift($message, $translation->getTranslation());
         } else {
             $message = [$translation->getTranslation()];
         }
         $messages[$key] = $message;
     }
     return $messages;
 }
Пример #22
0
 /**
  * Add the headers found to the translations instance.
  * 
  * @param string       $headers
  * @param Translations $translations
  *
  * @return array
  */
 private static function extractHeaders($headers, Translations $translations)
 {
     $headers = explode("\n", $headers);
     $currentHeader = null;
     foreach ($headers as $line) {
         $line = self::convertString($line);
         if ($line === '') {
             continue;
         }
         if (self::isHeaderDefinition($line)) {
             $header = array_map('trim', explode(':', $line, 2));
             $currentHeader = $header[0];
             $translations->setHeader($currentHeader, $header[1]);
         } else {
             $entry = $translations->getHeader($currentHeader);
             $translations->setHeader($currentHeader, $entry . $line);
         }
     }
 }
Пример #23
0
 protected function loadTranslations()
 {
     if (!file_exists($this->arguments['src-po'])) {
         $this->error('src-po file not found');
         exit;
     }
     $this->translations = Translations::fromPoFile($this->arguments['src-po']);
     list($code) = explode('_', $this->translations->getLanguage());
     $this->translateDirection = ($this->arguments['src-lang'] ?: 'en') . '-' . $code;
 }
Пример #24
0
 /**
  * Load the i12n translation file.
  */
 public function load_translation()
 {
     $translator = new \Gettext\Translator();
     $i18n_path = realpath(__DIR__ . '/../../i18n/' . Config::$locale . '.po');
     if (file_exists($i18n_path)) {
         $translations = \Gettext\Translations::fromPoFile($i18n_path);
         $translator->loadTranslations($translations);
     }
     Translator::initGettextFunctions($translator);
 }
Пример #25
0
 /**
  * Parse the file type names.
  *
  * @param \Gettext\Translations $translations
  * @param string                $rootDirectory
  * @param string                $prefix
  * @param string[]              $directoryAlternatives
  */
 private function parseFileTypes(\Gettext\Translations $translations, $rootDirectory, $prefix, $directoryAlternatives)
 {
     foreach ($directoryAlternatives as $subDir) {
         $rel = $subDir === '' ? 'app.php' : "{$subDir}/app.php";
         $fileAbs = $rootDirectory . '/' . $rel;
         if (!is_file($fileAbs)) {
             continue;
         }
         $fileRel = $prefix . $rel;
         $configFile = new \C5TL\Util\ConfigFile($fileAbs);
         $config = $configFile->getArray();
         if (isset($config['file_types']) && is_array($config['file_types'])) {
             $fileTypes = $config['file_types'];
             foreach (array_keys($fileTypes) as $fileType) {
                 $translation = $translations->insert('', $fileType);
                 $translation->addReference($fileRel);
             }
         }
     }
 }
Пример #26
0
 /**
  * Handle an array of translations and append to the Translations instance
  *
  * @param array        $content
  * @param Translations $translations
  */
 public static function handleArray(array $content, Translations $translations)
 {
     $content = $content['messages'];
     $translations_info = isset($content['']) ? $content[''] : null;
     unset($content['']);
     if (isset($translations_info['domain'])) {
         $translations->setDomain($translations_info['domain']);
     }
     $context_glue = '\\u0004';
     foreach ($content as $key => $message) {
         $key = explode($context_glue, $key);
         $context = isset($key[1]) ? array_shift($key) : '';
         $original = array_shift($key);
         $plural = array_shift($message);
         $translation = array_shift($message);
         $plural_translation = array_shift($message);
         $entry = $translations->insert($context, $original, $plural);
         $entry->setTranslation($translation);
         $entry->setPluralTranslation($plural_translation);
     }
 }
Пример #27
0
 /**
  * Generates an array with the translations.
  *
  * @param Translations $translations
  *
  * @return array
  */
 public static function toArray(Translations $translations)
 {
     $array = array();
     $context_glue = "";
     foreach ($translations as $translation) {
         $key = ($translation->hasContext() ? $translation->getContext() . $context_glue : '') . $translation->getOriginal();
         $entry = array($translation->getPlural(), $translation->getTranslation());
         if ($translation->hasPluralTranslation()) {
             $entry = array_merge($entry, $translation->getPluralTranslation());
         }
         $array[$key] = $entry;
     }
     $domain = $translations->getDomain() ?: 'messages';
     $lang = $translations->getLanguage() ?: 'en';
     $fullArray = array($domain => array('' => array('domain' => $domain, 'lang' => $lang, 'plural-forms' => 'nplurals=2; plural=(n != 1);')));
     if ($translations->getHeader('Plural-Forms') !== null) {
         $fullArray[$domain]['']['plural-forms'] = $translations->getHeader('Plural-Forms');
     }
     $fullArray[$domain] = array_merge($fullArray[$domain], $array);
     return $fullArray;
 }
Пример #28
0
 /**
  * Handle an array of translations and append to the Translations instance.
  *
  * @param array        $content
  * @param Translations $translations
  */
 public static function extract(array $content, Translations $translations)
 {
     $messages = current($content);
     $headers = isset($messages['']) ? $messages[''] : null;
     unset($messages['']);
     if (!empty($headers['domain'])) {
         $translations->setDomain($headers['domain']);
     }
     if (!empty($headers['lang'])) {
         $translations->setLanguage($headers['lang']);
     }
     if (!empty($headers['plural-forms'])) {
         $translations->setHeader(Translations::HEADER_PLURAL, $headers['plural-forms']);
     }
     $context_glue = '\\u0004';
     foreach ($messages as $key => $translation) {
         $key = explode($context_glue, $key);
         $context = isset($key[1]) ? array_shift($key) : '';
         $translations->insert($context, array_shift($key))->setTranslation(array_shift($translation))->setPluralTranslations($translation);
     }
 }
Пример #29
0
 /**
  * Updates the catalog file from the given po file
  *
  * @return void
  */
 public function updateFromCatalog()
 {
     $domain = $this->params['domain'];
     #$localePaths = App::path('Locale');
     $localePath = ROOT . '/src/Locale/';
     $catalogFile = $localePath . $domain . '.pot';
     if (!file_exists($catalogFile)) {
         return $this->abort(sprintf('Catalog File %s not found.', $catalogFile));
     }
     $poFiles = [];
     $folder = new Folder($localePath);
     $tree = $folder->tree();
     foreach ($tree[1] as $file) {
         $basename = basename($file);
         if ($domain . '.po' === $basename) {
             $poFiles[] = $file;
         }
     }
     if (empty($poFiles)) {
         return $this->abort('I could not find any matching po files in the given locale path (%s) for the domain (%s)', $localePath, $domain);
     }
     if (!$this->params['overwrite']) {
         $this->out('I will update the following .po files and their corresponding .mo file with the keys from catalog: ' . $catalogFile);
         foreach ($poFiles as $poFile) {
             $this->out('    - ' . $poFile);
         }
         $response = $this->in('Would you like to continue?', ['y', 'n'], 'n');
         if ($response !== 'y') {
             return $this->abort('Aborted');
         }
     }
     foreach ($poFiles as $poFile) {
         $catalogEntries = Translations::fromPoFile($catalogFile);
         $moFile = str_replace('.po', '.mo', $poFile);
         $translationEntries = Translations::fromPoFile($poFile);
         $newTranslationEntries = $catalogEntries->mergeWith($translationEntries, Merge::REFERENCES_THEIRS);
         $newTranslationEntries->deleteHeaders();
         foreach ($translationEntries->getHeaders() as $key => $value) {
             $newTranslationEntries->setHeader($key, $value);
         }
         if ($this->params['strip-references']) {
             foreach ($newTranslationEntries as $translation) {
                 $translation->deleteReferences();
             }
         }
         $newTranslationEntries->toPoFile($poFile);
         $newTranslationEntries->toMoFile($moFile);
         $this->out('Updated ' . $poFile);
         $this->out('Updated ' . $moFile);
     }
 }
Пример #30
-1
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->writeSection($output, 'Csv to Po converter');
     $this->cwd = getcwd() . DIRECTORY_SEPARATOR;
     $output->writeln('<info>Using CWD</info> ' . $this->cwd);
     $csvFile = $this->getInputCsvFile($input, $output);
     $poFiles = $this->getInputPoFiles($input, $output);
     $outputFolder = $this->getOutputFolder($input, $output);
     $useDefaults = $input->getOption('use-defaults');
     if ($useDefaults) {
         $output->writeln('<info>Csv file</info>:' . "\n" . $csvFile . "\n");
         $output->writeln('<info>Po files</info>:');
         $this->writeList($output, $poFiles);
         $output->writeln("\n" . '<info>Output folder</info>: ' . "\n" . $outputFolder . "\n");
     }
     $writeHandles = [];
     foreach ($poFiles as $poFile) {
         $key = basename($poFile, '.po');
         $output->writeln('<info>loading ' . $key . '</info>...');
         $writeHandles[$key] = Translations::fromPoFile($poFile);
     }
     $header = null;
     $output->writeln('<info>reading from csv</info>...');
     $reader = Reader::createFromPath($csvFile);
     foreach ($reader as $i => $row) {
         if ($header == null) {
             $header = $row;
             continue;
         }
         $original = null;
         foreach ($row as $j => $string) {
             if ($original == null) {
                 $original = $string;
                 continue;
             }
             if (empty($string)) {
                 continue;
             }
             $writeHandle = $writeHandles[$header[$j]];
             $translation = $writeHandle->find(null, $original);
             if ($translation != false && $translation->translation != $string) {
                 if (!empty($translation->translation)) {
                     $this->handleConflict($input, $output, $original, $translation->translation, $string);
                 } else {
                     $translation->setTranslation($string);
                 }
             } else {
                 $translation = new Translation(null, $original);
                 $translation->setTranslation($string);
                 $writeHandle[] = $translation;
             }
         }
     }
     foreach ($writeHandles as $key => $writeHandle) {
         $output->writeln('<info>writing ' . $key . '</info>...');
         $content = Po::toString($writeHandle);
         file_put_contents($this->outputDir . DIRECTORY_SEPARATOR . $key . '.po', $content);
     }
     $output->writeln('<info>done</info>');
 }