Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. https://github.com/raulferras/PHP-po-parser Class to parse .po file and extract its strings.
Example #1
0
 /**
  * Parses portable object (PO) format.
  *
  * @param string $resource translation catalog filename
  * @return Catalog translation catalog object
  */
 public function parse($resource)
 {
     $fileHandler = new FileHandler($resource);
     $poParser = new PoParser($fileHandler);
     $entries = $poParser->parse();
     $catalog = new Catalog();
     foreach ($entries as $entry) {
         $item = new CatalogItem();
         foreach ($entry as $key => $value) {
             if ($key == 'msgid') {
                 $item->ID = $value[0];
             } elseif ($key == 'msgid_plural') {
                 $item->ID_plural = $value[0];
             } elseif ($key == 'context') {
                 $item->context = $value[0];
             } elseif ($key == 'msgstr') {
                 $item->translations[0] = $value[0];
             } elseif (substr($key, 0, 7) === 'msgstr[') {
                 $size = strpos($key, ']') - 7;
                 $item->translations[(int) substr($key, 7, $size)] = $value[0];
             }
         }
         $catalog->add($item);
     }
     return $catalog;
 }
Example #2
0
 /**
  * function define language and parse PO file
  * 
  * @param String $lang language code
  */
 public static function defineLanguage($lang = "")
 {
     //get language from browser if not set
     if (!$lang) {
         $lang = Lang::getLanguage();
     }
     $poparser = new PoParser();
     // path to lang file
     $filePath["en"] = PATH . "lang/en.po";
     $filePath["de"] = PATH . "lang/de.po";
     // set default language if language is not available
     if (!isset($filePath[$lang])) {
         $lang = "en";
     }
     // returns array
     $po_output = $poparser->parse($filePath[$lang]);
     // convert array to $l_ array
     foreach ($po_output as $po_o) {
         if (isset($po_o["msgid"]) && isset($po_o["msgstr"])) {
             Lang::$lang_output[$po_o["msgid"][0]] = "";
             foreach ($po_o["msgstr"] as $msg_str) {
                 Lang::$lang_output[$po_o["msgid"][0]] .= $msg_str;
             }
         }
     }
 }
Example #3
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $inFile = new FileHandler($input->getArgument('from'));
     $outFileLocation = $input->getArgument('to');
     $poParser = new PoParser($inFile);
     $messages = $poParser->parse($inFile);
     foreach ($messages as $msgid => $message) {
         $message = $this->translateMessage($message);
         $poParser->setEntry($msgid, $message, false);
     }
     $poParser->writeFile($outFileLocation);
 }
Example #4
0
 protected function loadLang($config)
 {
     $scope = $config->get('environment.scope');
     $lang = $config->get('environment.lang') ?: $config->get('lang');
     $paths = $config->get('paths');
     $file = $paths['views'] . '/' . $scope . '/langs/' . $lang . '.po';
     if (file_exists($file)) {
         $fileHandler = new FileHandler($file);
         $poParser = new PoParser($fileHandler);
         $GLOBALS['traducciones'] = $poParser->parse();
     }
 }
Example #5
0
 public function load($lang = null)
 {
     $this->translations = array();
     $language = $lang == null ? $this->locale : $lang;
     if (array_key_exists($language, $this->poFiles)) {
         foreach ($this->poFiles[$language] as $file) {
             $fHandler = new FileHandler($file);
             $poParser = new PoParser($fHandler);
             $t = $poParser->parse();
             $this->translations = array_merge_recursive($this->translations, $t);
         }
     }
 }
Example #6
0
 public function parse()
 {
     $kwfTrlElements = array();
     if ($this->_kwfPoFilePath) {
         $this->_output->writeln('<info>Reading kwf-po file</info>');
         $kwfPoFile = \Sepia\PoParser::parseFile($this->_kwfPoFilePath);
         $trlElementsExtractor = new TrlElementsExtractor($kwfPoFile);
         $kwfTrlElements = $trlElementsExtractor->extractTrlElements();
     }
     $initDir = getcwd();
     $this->_output->writeln('<info>Changing into directory</info>');
     $repository = new Repository($this->_directory);
     $wc = $repository->getWorkingCopy();
     if ($wc->getDiffPending()->getRawDiff() != '' || $wc->getDiffStaged()->getRawDiff() != '') {
         $this->_output->writeln('<error>Uncommited changes</error>');
         exit;
     }
     chdir($initDir);
     $initBranch = trim($repository->run('rev-parse', array('--abbrev-ref', 'HEAD')));
     $trlElements = array();
     $errors = array();
     $repository = new Repository($this->_directory);
     $repository->run('fetch', array('origin'));
     if ($this->_kwfPoFilePath) {
         $this->_output->writeln('<info>Iterating over branches matching "^[1-9]+.[0-9]+$"</info>');
     } else {
         $this->_output->writeln('<info>Iterating over branches matching "^[3-9]+.[0-9]+$" and >=3.9</info>');
     }
     foreach ($repository->getReferences()->getBranches() as $branch) {
         $branchName = $branch->getName();
         if (strpos($branchName, 'origin/') === false) {
             continue;
         }
         $splited = explode('/', $branchName);
         $isVersionNumber = preg_match('/^[0-9]+.[0-9]+$/i', $splited[1]);
         if (sizeof($splited) >= 3) {
             continue;
         }
         if (!$isVersionNumber && $splited[1] != 'master' && $splited[1] != 'production') {
             continue;
         }
         if (!$this->_kwfPoFilePath && $isVersionNumber && version_compare($splited[1], '3.9', '<')) {
             continue;
         }
         $this->_output->writeln("<info>Checking out branch: {$branchName}</info>");
         $wc->checkout($branchName);
         // parse package
         $this->_output->writeln('Parsing source directory...');
         $parser = new ParseAll($this->_directory, $this->_output);
         $parser->setIgnoredFiles($this->_ignoredFiles);
         $trlElements = array_merge($parser->parseDirectoryForTrl(), $trlElements);
         $newErrors = $parser->getErrors();
         foreach ($newErrors as $key => $error) {
             $newErrors[$key]['branch'] = $branchName;
         }
         $errors = array_merge($newErrors, $errors);
     }
     $wc->checkout($initBranch);
     $sources = array();
     $filteredTrlElements = array();
     foreach ($trlElements as $trlElement) {
         $sources[$trlElement['source']] = true;
         if ($trlElement['source'] == $this->_source) {
             $filteredTrlElements[] = $trlElement;
         }
     }
     $trlElements = $filteredTrlElements;
     // generate po file
     $this->_output->writeln('Generate Po-File...');
     touch($this->_poFilePath);
     $this->_output->writeln($this->_poFilePath);
     $poFileGenerator = new PoFileGenerator($trlElements, $kwfTrlElements);
     $poFile = $poFileGenerator->generatePoFileObject($this->_poFilePath);
     $poFile->writeFile($this->_poFilePath);
     $this->_output->writeln('');
     $this->_output->writeln('Trl Errors:');
     foreach ($trlElements as $trlElement) {
         if (isset($trlElement['error_short']) && $trlElement['error_short']) {
             var_dump($trlElement);
         }
     }
     if (count($errors)) {
         $this->_output->writeln('');
         $this->_output->writeln('Php Parse-Errors:');
         foreach ($errors as $error) {
             $this->_output->writeln('  Branch: ' . $error['branch'] . ' | File: ' . $error['file']);
             $this->_output->writeln('    Error:' . $error['error']->getMessage());
             $this->_output->writeln('  -------------------------------------');
         }
     }
     $this->_output->writeln('');
     $this->_output->writeln('Every branch has been parsed an data is collected in ' . $this->_poFilePath);
     $this->_output->writeln('');
     $this->_output->writeln('1. Please check the mentioned Parse-Errors');
     $this->_output->writeln('2. Upload and translate file from ' . $this->_poFilePath . ' to lingohub or translate in another way');
     $this->_output->writeln('3. When using lingohub call "./vendor/bin/lingohub downloadTranslations" after translating');
     $this->_output->writeln('');
 }
Example #7
0
 private function _getPoParsers($source, $targetLanguage)
 {
     $files = array();
     if ($source == Kwf_Trl::SOURCE_WEB) {
         if (file_exists('trl/' . $targetLanguage . '.po')) {
             $files = array('trl/' . $targetLanguage . '.po');
         }
     } else {
         if ($source == Kwf_Trl::SOURCE_KWF) {
             // check all composer packages
             $this->_checkPackagesForTrlFilesAndTryDownloadFromKoalaWebsiteIfNotExisting($targetLanguage);
             $files = glob(VENDOR_PATH . '/*/*/trl/' . $targetLanguage . '.po');
         }
     }
     require_once VENDOR_PATH . '/autoload.php';
     $poParsers = array();
     foreach ($files as $file) {
         $poParser = \Sepia\PoParser::parseFile($file);
         array_push($poParsers, $poParser);
     }
     return $poParsers;
 }
Example #8
0
    // Failed to create dir
    if (!is_dir(dirname($output))) {
        die(Colors::colorize('%rDirectory "' . dirname($output) . '" not exists %n' . PHP_EOL));
    }
}
if (!is_dir($tmp = __DIR__ . '/../tmp')) {
    mkdir($tmp, 0777);
}
Translator::$cacheDir = $tmp;
try {
    // translator
    $translator = new Translator($arguments['apikey']);
    $translator->httpOptions[CURLOPT_FAILONERROR] = false;
    $translator->httpOptions[CURLOPT_HTTP200ALIASES] = [400];
    // parser
    $po = new PoParser();
    $entries = $po->read($input);
    $previousEntries = null;
    if (file_exists($output)) {
        $previousEntries = $po->read($output);
    }
    echo Colors::colorize('Translating : %b' . count($entries) . '%n entries from ' . $from . ' to ' . $to . PHP_EOL);
    $progress = new Bar('Translate status ', count($entries));
    foreach ($entries as $entry => $data) {
        $translate = "";
        $skipped = "";
        if (isset($previousEntries) && !empty($previousEntries[$entry]['msgstr'][0])) {
            $skipped = "(skipped)";
            $translate = $previousEntries[$entry]['msgstr'][0];
        } else {
            $translate = $translator->translate($entry, $from, $to);
Example #9
0
 private function _getAllPoParsersExceptKwf($source, $targetLanguage)
 {
     $files = array();
     if ($source == Kwf_Trl::SOURCE_WEB) {
         if (file_exists('trl/' . $targetLanguage . '.po')) {
             $files = array('trl/' . $targetLanguage . '.po');
         }
     } else {
         if ($source == Kwf_Trl::SOURCE_KWF) {
             // check all composer packages
             $files = $this->_getAllPackagesTrlFiles($targetLanguage);
         }
     }
     require_once VENDOR_PATH . '/autoload.php';
     $poParsers = array();
     foreach ($files as $file) {
         $poParsers[$file] = \Sepia\PoParser::parseFile($file);
     }
     return $poParsers;
 }