Skip to content

[WIP]: Allow Drupal to use Translate component #4249

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 71 additions & 6 deletions src/Symfony/Component/Translation/Dumper/PoFileDumper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Translation\Dumper;

use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Component\Translation\Gettext;

/**
* PoFileDumper generates a gettext formatted string representation of a message catalogue.
Expand All @@ -23,18 +24,43 @@ class PoFileDumper extends FileDumper
/**
* {@inheritDoc}
*/
public function format(MessageCatalogue $messages, $domain = 'messages')
public function format(MessageCatalogue $catalogue, $domain = 'messages')
{
$output = '';
$messages = $catalogue->all();
$header = Gettext::getHeader($messages['messages']);
$newLine = false;
foreach ($messages->all($domain) as $source => $target) {
if (!empty($header)) {
$output .= Gettext::headerToString($header);
$newLine = true;
}
Gettext::deleteHeader($messages['messages']);
$messages = $messages[$domain];
// Make plural form translations arrays
$this->extractSingulars($messages);
foreach ($messages as $source => $target) {
if ($newLine) {
$output .= "\n";
$output .= "\n\n";
} else {
$newLine = true;
}
// Gettext PO files only understand non indexed rules or 'standard'
if (!is_array($target)) {
$output .= sprintf("msgid \"%s\"\n", $this->escape($source));
$output .= sprintf("msgstr \"%s\"", $this->escape($target));
} else {
$newLine = true;
// ExtractSingular return 3 items so extract these.
list( $singularKey, $plural_key, $targets) = $target;
$output .= sprintf("msgid \"%s\"\n", $this->escape($source));
$output .= sprintf("msgid_plural \"%s\"\n", $this->escape($plural_key));
$targets = explode("|", $targets);
foreach ($targets as $index => $target) {
if ($index>0) {
$output .= "\n";
}
$output .= sprintf('msgstr[%d] "%s"', $index, $this->escape($target));
}
}
$output .= sprintf('msgid "%s"'."\n", $this->escape($source));
$output .= sprintf('msgstr "%s"', $this->escape($target));
}

return $output;
Expand All @@ -52,4 +78,43 @@ private function escape($str)
{
return addcslashes($str, "\0..\37\42\134");
}

/**
* Merges the singular and plurals back into 1 item.
*
* Gettext allows for a combination of messages being a singular and
* a plural form for the source.
*
* msgid "One sheep"
* msgid_plural "@count sheep"
* msgstr[0] "un mouton"
* msgstr[1] "@count moutons"
*
* By scanning $messages for "One sheep|@count sheep" we can recombine
* these string for Dumping.
*
* @param array $messages All plural forms are merged into the first occurence of a singular.
*/
private function extractSingulars(array &$messages)
{
$messageBundles = array();
foreach ($messages as $key => $message) {
if (strpos($key, '|') !== FALSE) {
$messageBundles[] = $key;
}
}
foreach ($messageBundles as $bundle) {
list($singularKey, $pluralKey) = explode('|', $bundle, 2);
if (isset($messages[$singularKey])&&isset($messages[$pluralKey])) {
$messages[$singularKey] = array(
$singularKey,
$pluralKey,
$messages[$pluralKey],
);
unset($messages[$pluralKey]);
unset($messages[$bundle]);
}
}
}

}
205 changes: 205 additions & 0 deletions src/Symfony/Component/Translation/Gettext.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Translation;

/**
* Provide for specific Gettext related helper functionality.
*
* @see http://www.gnu.org/software/gettext/manual/gettext.html#PO-Files
* @author Clemens Tolboom
* @copyright Clemens Tolboom clemens@build2be.com
*/
class Gettext
{
/**
* Defines a key for managing a PO Header in our messages.
*
* Gettext files (.po .mo) can contain a header which needs to be managed.
* A Gettext file can have multiple domains into one file. This is called
* a message context or msgctxt.
*
* To provide for both header and context this class provides for
* some static functions to (help) process their values.
*
* @see GettextTest
* @see PoFileLoader
* @see PoFileLoaderTest
* @see PoFileDumper
* @see PoFileDumperTest
*/
const HEADER_KEY = "__HEADER__";
const CONTEXT_KEY = "__CONTEXT__";

/**
* Merge key/value pair into Gettext compatible item.
*
* Each combination is into substring: "key: value \n".
*
* If any key found the values are preceded by empty msgid and msgstr
*
* @param array $header
* @return array|NULL A Gettext compatible string.
*/
static public function headerToString(array $header)
{
$zipped = Gettext::zipHeader($header);
if (!empty($zipped)) {
$result = array(
'msgid ""',
'msgstr ""',
$zipped,
);

return implode("\n", $result);
}
}

/**
* Ordered list of Gettext header keys
*
* TODO: this list is probably incomplete
*
* @return array Ordered list of Gettext keys
*/
static public function headerKeys() {
return array(
'Project-Id-Version',
'POT-Creation-Date',
'PO-Revision-Date',
'Last-Translator',
'Language-Team',
'MIME-Version',
'Content-Type',
'Content-Transfer-Encoding',
'Plural-Forms'
);
}

static public function emptyHeader() {
return array_fill_keys(Gettext::headerKeys(), "");
}

/**
* Retrieve PO Header from messages.
*
* @param array $messages
* @return array containing key/value pair|empty array.
*/
static public function getHeader(array &$messages)
{
if (isset($messages[Gettext::HEADER_KEY])) {
return Gettext::unzipHeader($messages[Gettext::HEADER_KEY]);
}

return array();
}

/**
* Adds or overwrite a header to the messages.
*
* @param array $messages
* @param array $header
*/
static public function addHeader(array &$messages, array $header)
{
$messages[Gettext::HEADER_KEY] = Gettext::zipHeader($header);
}

/**
* Deletes a header from the messages if exists.
*
* @param array $messages
*/
static public function deleteHeader(array &$messages) {
if (isset($messages[Gettext::HEADER_KEY])) {
unset($messages[Gettext::HEADER_KEY]);
}
}

/**
* Add context to the messages.
*
* Gettext supports for multiple context (domains) in one PO|MO file.
* By injecting these into the translated messages we can post process.
*
* @param array $messages
* @param type $context
*/
static public function addContext(array &$messages, $context) {
if (!isset($messages[Gettext::CONTEXT_KEY])) {
$messages[Gettext::CONTEXT_KEY] = '';
}
$contexts = array_flip(explode('|', $messages[Gettext::CONTEXT_KEY]));
$contexts[$context] = $context;
unset($contexts['']);
$messages[Gettext::CONTEXT_KEY] = implode('|', array_keys($contexts));
}

static public function deleteContext(array &$messages) {
unset($messages[Gettext::CONTEXT_KEY]);
}

static public function getContext(array &$messages) {
if (isset($messages[Gettext::CONTEXT_KEY])) {
return explode('|', $messages[Gettext::CONTEXT_KEY]);
}

return array();
}

/**
* Parses a Gettext header string into a key/value pairs.
*
* @param $header
* The Gettext header.
* @return array
* Array with the key/value pair
*/
static private function unzipHeader($header)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Private functions should be after public and protected ones.

{
$result = array();
$lines = explode("\n", $header);
foreach ($lines as $line) {
$cleaned = trim($line);
$cleaned = preg_replace(array('/^\"/','/\\\n\"$/'), '', $cleaned);
if (strpos($cleaned, ':') > 0) {
list($key, $value) = explode(':', $cleaned, 2);
$result[trim($key)] = trim($value);
}
}

return $result;
}

/**
* Zips header into a Gettext formatted string.
*
* The returned value is what msgstr would contain when used by the header
* in a Gettext file.
*
* @param array $header
* @return string
*
* @see unzipHeader().
* @see fixtures/full.po
*/
static private function zipHeader(array $header)
{
$lines = array();
foreach ($header as $key => $value) {
$lines[] = '"' . $key . ": " . $value . '\n"';
}

return implode("\n", $lines);
}

}
Loading