Refactoring

This commit is contained in:
gamonoid
2017-09-03 20:39:22 +02:00
parent af40881847
commit a7274d3cfd
5075 changed files with 238202 additions and 16291 deletions

View File

@@ -0,0 +1,17 @@
Contributing to Gettext
=======================
Looking to contribute something to this library? Here's how you can help.
## Bugs
A bug is a demonstrable problem that is caused by the code in the repository. Good bug reports are extremely helpful thank you!
Please try to be as detailed as possible in your report. Include specific information about the environment version of PHP, version of gettext, etc, and steps required to reproduce the issue.
## Pull Requests
Good pull requests patches, improvements, new features are a fantastic help. New extractors or generator are welcome. Before create a pull request, please follow these instructions:
* The code must be PSR-2 compliant
* Write some tests

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Oscar Otero Marzoa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,401 @@
Gettext
=======
[![Build Status](https://travis-ci.org/oscarotero/Gettext.png?branch=master)](https://travis-ci.org/oscarotero/Gettext)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/oscarotero/Gettext/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/oscarotero/Gettext/?branch=master)
[![Reference Status](https://www.versioneye.com/php/gettext:gettext/reference_badge.svg?style=flat)](https://www.versioneye.com/php/gettext:gettext/references)
[![Latest Stable Version](https://poser.pugx.org/gettext/gettext/v/stable.svg)](https://packagist.org/packages/gettext/gettext)
[![Total Downloads](https://poser.pugx.org/gettext/gettext/downloads.svg)](https://packagist.org/packages/gettext/gettext)
[![Monthly Downloads](https://poser.pugx.org/gettext/gettext/d/monthly.png)](https://packagist.org/packages/gettext/gettext)
[![License](https://poser.pugx.org/gettext/gettext/license.svg)](https://packagist.org/packages/gettext/gettext)
[![SensioLabsInsight](https://insight.sensiolabs.com/projects/496dc2a6-43be-4046-a283-f8370239dd47/big.png)](https://insight.sensiolabs.com/projects/496dc2a6-43be-4046-a283-f8370239dd47)
Created by Oscar Otero <http://oscarotero.com> <oom@oscarotero.com> (MIT License)
Gettext is a PHP (>=5.4) library to import/export/edit gettext from PO, MO, PHP, JS files, etc.
## Installation
With composer (recomended):
```
composer require gettext/gettext
```
If you don't use composer in your project, you have to download and place this package in a directory of your project. You need to install also [gettext/languages](https://github.com/mlocati/cldr-to-gettext-plural-rules). Then, include the autoloaders of both projects in any place of your php code:
```php
include_once "libs/gettext/src/autoloader.php";
include_once "libs/cldr-to-gettext-plural-rules/src/autoloader.php";
```
## Classes and functions
This package contains the following classes:
* `Gettext\Translation` - A translation definition
* `Gettext\Translations` - A collection of translations
* `Gettext\Extractors\*` - Import translations from various sources (po, mo, php, js, etc)
* `Gettext\Generators\*` - Export translations to various formats (po, mo, php, json, etc)
* `Gettext\Translator` - To use the translations in your php templates instead the [gettext extension](http://php.net/gettext)
* `Gettext\GettextTranslator` - To use the [gettext extension](http://php.net/gettext)
## Usage example
```php
use Gettext\Translations;
//import from a .po file:
$translations = Translations::fromPoFile('locales/gl.po');
//edit some translations:
$translation = $translations->find(null, 'apple');
if ($translation) {
$translation->setTranslation('Mazá');
}
//export to a php array:
$translations->toPhpArrayFile('locales/gl.php');
//and to a .mo file
$translations->toMoFile('Locale/gl/LC_MESSAGES/messages.mo');
```
If you want use this translations in your php templates without using the gettext extension:
```php
use Gettext\Translator;
//Create the translator instance
$t = new Translator();
//Load your translations (exported as PhpArray):
$t->loadTranslations('locales/gl.php');
//Use it:
echo $t->gettext('apple'); // "Mazá"
//If you want use global functions:
$t->register();
echo __('apple'); // "Mazá"
__e('apple'); // "Mazá"
```
To use this translations with the gettext extension:
```php
use Gettext\GettextTranslator;
//Create the translator instance
$t = new GettextTranslator();
//Set the language and load the domain
$t->setLanguage('gl');
$t->loadDomain('messages', 'Locale');
//Use it:
echo $t->gettext('apple'); // "Mazá"
//Or use the gettext functions
echo gettext('apple'); // "Mazá"
//If you want use the global functions
$t->register();
echo __('apple'); // "Mazá"
```
The benefits of using the functions provided by this library (`__()` instead `_()` or `gettext()`) are:
* You are using the same functions, no matter whether the translations are provided by gettext extension or any other method
* You can use variables easier because sprintf functionality is included. For example: `__('Hello %s', 'world')` instead `sprintf(_('Hello %s'), 'world')`.
## Translation
The `Gettext\Translation` class stores all information about a translation: the original text, the translated text, source references, comments, etc.
```php
// __construct($context, $original, $plural)
$translation = new Gettext\Translation('comments', 'One comment', '%s comments');
$translation->setTranslation('Un comentario');
$translation->setPluralTranslation('%s comentarios');
$translation->addReference('templates/comments/comment.php', 34);
$translation->addComment('To display the amount of comments in a post');
echo $translation->getContext(); // comments
echo $translation->getOriginal(); // One comment
echo $translation->getTranslation(); // Un comentario
// etc...
```
## Translations
The `Gettext\Translations` class stores a collection of translations:
```php
$translations = new Gettext\Translations();
//You can add new translations using the array syntax
$translations[] = new Gettext\Translation('comments', 'One comment', '%s comments');
//Or using the "insert" method
$insertedTranslation = $translations->insert('comments', 'One comments', '%s comments');
//Find a specific translation
$translation = $translations->find('comments', 'One comments');
//Edit headers, domain, etc
$translations->setHeader('Last-Translator', 'Oscar Otero');
$translations->setDomain('my-blog');
```
## Extractors
The extrators allows to fetch gettext values from any source. For example, to scan a .po file:
```php
$translations = new Gettext\Translations();
//From a file
Gettext\Extractors\Po::fromFile('locales/en.po', $translations);
//From a string
$string = file_get_contents('locales2/en.po');
Gettext\Extractors\Po::fromString($string, $translations);
```
The better way to use extractors is using the magic methods of `Gettext\Translations`:
```php
//Create a Translations instance using a po file
$translations = Gettext\Translations::fromPoFile('locales/en.po');
//Add more messages from other files
$translations->addFromPoFile('locales2/en.po');
```
The available extractors are the following:
Name | Description | Example
---- | ----------- | --------
**Blade** | Scans a Blade template (For laravel users). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/4/Input.Blade.php)
**Csv** | Gets the messages from csv. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Csv.csv)
**CsvDictionary** | Gets the messages from csv (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/CsvDictionary.csv)
**Jed** | Gets the messages from a json compatible with [Jed](http://slexaxton.github.com/Jed/). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Jed.json)
**JsCode** | Scans javascript code looking for all gettext functions (the same than PhpCode but for javascript). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/8/Input.JsCode.js)
**Json** | Gets the messages from json. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Json.json)
**JsonDictionary** | Gets the messages from a json (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/JsonDictionary.json)
**Mo** | Gets the messages from MO. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Mo.mo)
**PhpArray** | Gets the messages from a php file that returns an array. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/PhpArray.php)
**PhpCode** | Scans php code looking for all gettext functions (see `translator_functions.php`). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/2/Input.PhpCode.php)
**Po** | Gets the messages from PO. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Po.po)
**Twig** | To scan a Twig template. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/6/Input.Twig.php)
**Xliff** | Gets the messages from [xliff (2.0)](http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Xliff.xlf)
**Yaml** | Gets the messages from yaml. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Yaml.yml)
**YamlDictionary** | Gets the messages from a yaml (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/YamlDictionary.yml)
## Generators
The generators export a `Gettext\Translations` instance to any format (po, mo, array, etc).
```php
//Save to a file
Gettext\Generators\Po::toFile($translations, 'locales/en.po');
//Return as a string
$content = Gettext\Generators\Po::toString($translations);
file_put_contents('locales/en.po', $content);
```
Like extractors, the better way to use generators is using the magic methods of `Gettext\Translations`:
```php
//Extract messages from a php code file
$translations = Gettext\Translations::fromPhpCodeFile('templates/index.php');
//Export to a po file
$translations->toPoFile('locales/en.po');
//Export to a po string
$content = $translatons->toPoString();
file_put_contents('locales/en.po', $content);
```
The available generators are the following:
Name | Description | Example
---- | ----------- | --------
**Csv** | Exports to csv. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Csv.csv)
**CsvDictionary** | Exports to csv (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/CsvDictionary.csv)
**Json** | Exports to json. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Json.json)
**JsonDictionary** | Exports to json (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/JsonDictionary.json)
**Mo** | Exports to Mo. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Mo.mo)
**PhpArray** | Exports to php code that returns an array. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/PhpArray.php)
**Po** | Exports to Po. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Po.po)
**Jed** | Exports to json format compatible with [Jed](http://slexaxton.github.com/Jed/). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Jed.json)
**Xliff** | Exports to [xliff (2.0)](http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Xliff.xlf)
**Yaml** | Exports to yaml. | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/Yaml.yml)
**YamlDictionary** | Exports to yaml (without plurals and context). | [example](https://github.com/oscarotero/Gettext/blob/master/tests/assets/1/YamlDictionary.yml)
## Translator
The class `Gettext\Translator` implements the gettext functions in php. Useful if you don't have the native gettext extension for php or want to avoid problems with it. You can load the translations from a php array file or using a `Gettext\Translations` instance:
```php
use Gettext\Translator;
//Create a new instance of the translator
$t = new Translator();
//Load the translations using any of the following ways:
// 1. from php files (generated by Gettext\Extractors\PhpArray)
$t->loadTranslations('locales/gl.php');
// 2. using the array directly
$array = include 'locales/gl.php';
$t->loadTranslations($array);
// 3. using a Gettext\Translations instance (slower)
$translations = Gettext\Translations::fromPoFile('locales/gl.po');
$t->loadTranslations($translations);
//Now you can use it in your templates
echo $t->gettext('apple');
```
## GettextTranslator
The class `Gettext\GettextTranslator` uses the gettext extension. It's useful because combines the performance of using real gettext functions but with the same API than `Translator` class, so you can switch to one or other translator deppending of the environment without change code of your app.
```php
use Gettext\GettextTranslator;
//Create a new instance
$t = new GettextTranslator();
//It detects the environment variables to set the locale, but you can change it:
$t->setLanguage('gl');
//Load the domains:
$t->loadDomain('messages', 'project/Locale');
//this means you have the file "project/Locale/gl/LC_MESSAGES/messages.po"
//Now you can use it in your templates
echo $t->gettext('apple');
```
## Global functions
To ease the use of translations in your php templates, you can use the provided functions:
```php
//Register the translator to use the global functions
$t->register();
echo __('apple'); // it's the same than $t->gettext('apple');
__e('apple'); // it's the same than echo $t->gettext('apple');
```
You can scan the php files containing these functions and extract the values with the PhpCode extractor:
```html
<!-- index.php -->
<html>
<body>
<?php echo __('Hello world'); ?>
</body>
</html>
```
## Merge translations
To work with different translations you may want merge them in an unique file. There are two ways to do this:
The simplest way is adding new translations:
```php
use Gettext\Translations;
$translations = Translations::fromPoFile('my-file1.po');
$translations->addFromPoFile('my-file2.po');
```
A more advanced way is merge two `Translations` instances:
```php
use Gettext\Translations;
//Create a new Translations instances with our translations.
$translations1 = Translations::fromPoFile('my-file1.po');
$translations2 = Translations::fromPoFile('my-file2.po');
//Merge one inside other:
$translations1->mergeWith($translations2);
//Now translations1 has all values
```
The second argument of `mergeWith` defines how the merge will be done. Use the `Gettext\Merge` constants to configure the merging:
Constant | Description
--------- | -----------
`Merge::ADD` | Adds the translations from `$translations2` that are missing
`Merge::REMOVE` | Removes the translations missing in `$translations2`
`Merge::HEADERS_ADD` | Adds the headers from `$translations2` that are missing
`Merge::HEADERS_REMOVE` | Removes the headers missing in `$translations2`
`Merge::HEADERS_OVERRIDE` | Overrides the headers with the values of `$translations2`
`Merge::LANGUAGE_OVERRIDE` | Set the language defined in `$translations2`
`Merge::DOMAIN_OVERRIDE` | Set the domain defined in `$translations2`
`Merge::TRANSLATION_OVERRIDE` | Override the translation and plural translations with the value of `$translation2`
`Merge::COMMENTS_OURS` | Use only the comments of `$translation1`
`Merge::COMMENTS_THEIRS` | Use only the comments of `$translation2`
`Merge::EXTRACTED_COMMENTS_OURS` | Use only the extracted comments of `$translation1`
`Merge::EXTRACTED_COMMENTS_THEIRS` | Use only the extracted comments of `$translation2`
`Merge::FLAGS_OURS` | Use only the flags of `$translation1`
`Merge::FLAGS_THEIRS` | Use only the flags of `$translation2`
`Merge::REFERENCES_OURS` | Use only the references of `$translation1`
`Merge::REFERENCES_THEIRS` | Use only the references of `$translation2`
Example:
```php
use Gettext\Translations;
use Gettext\Merge;
//Scan the php code to find the latest gettext translations
$phpTranslations = Translations::fromPhpCodeFile('my-templates.php');
//Get the translations of the code that are stored in a po file
$poTranslations = Translations::fromPoFile('locale.po');
//Merge the translations from the po file using the references from `$phpTranslations`:
$translations->mergeWith($poTranslations, Merge::REFERENCES_OURS);
//Now save a po file with the result
$translations->toPoFile('locale.po');
```
Note, if the second argument is not defined, the default value is `Merge::DEFAULTS` that's equivalent to `Merge::ADD | Merge::HEADERS_ADD`.
## Use from CLI
There's a Robo task to use this library from the command line interface: https://github.com/oscarotero/GettextRobo
## Use in the browser
If you want to use your translations in the browser, there's a javascript translator: https://github.com/oscarotero/gettext-translator
## Contributors
Thanks to all [contributors](https://github.com/oscarotero/Gettext/graphs/contributors) specially to [@mlocati](https://github.com/mlocati).

View File

@@ -0,0 +1,46 @@
{
"name": "gettext/gettext",
"type": "library",
"description": "PHP gettext manager",
"keywords": ["js", "gettext", "i18n", "translation", "po", "mo"],
"homepage": "https://github.com/oscarotero/Gettext",
"license": "MIT",
"authors": [
{
"name": "Oscar Otero",
"email": "oom@oscarotero.com",
"homepage": "http://oscarotero.com",
"role": "Developer"
}
],
"support": {
"email": "oom@oscarotero.com",
"issues": "https://github.com/oscarotero/Gettext/issues"
},
"require": {
"php": ">=5.4.0",
"gettext/languages": "2.*"
},
"require-dev": {
"illuminate/view": "*",
"twig/twig": "*",
"twig/extensions": "*",
"symfony/yaml": "~2"
},
"suggest": {
"illuminate/view": "Is necessary if you want to use the Blade extractor",
"twig/twig": "Is necessary if you want to use the Twig extractor",
"twig/extensions": "Is necessary if you want to use the Twig extractor",
"symfony/yaml": "Is necessary if you want to use the Yaml extractor/generator"
},
"autoload": {
"psr-4": {
"Gettext\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Gettext\\Tests\\": "tests"
}
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Gettext;
abstract class BaseTranslator implements TranslatorInterface
{
/** @var TranslatorInterface */
public static $current;
/**
* @see TranslatorInterface
*/
public function register()
{
$previous = self::$current;
self::$current = $this;
include_once __DIR__.'/translator_functions.php';
return $previous;
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Illuminate\Filesystem\Filesystem;
use Illuminate\View\Compilers\BladeCompiler;
/**
* Class to get gettext strings from blade.php files returning arrays.
*/
class Blade extends Extractor implements ExtractorInterface
{
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$bladeCompiler = new BladeCompiler(new Filesystem(), null);
$string = $bladeCompiler->compileString($string);
PhpCode::fromString($string, $translations, $options);
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\HeadersExtractorTrait;
/**
* Class to get gettext strings from csv.
*/
class Csv extends Extractor implements ExtractorInterface
{
use HeadersExtractorTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$handle = fopen('php://memory', 'w');
fputs($handle, $string);
rewind($handle);
while ($row = fgetcsv($handle)) {
$context = array_shift($row);
$original = array_shift($row);
if ($context === '' && $original === '') {
self::extractHeaders(array_shift($row), $translations);
continue;
}
$translation = $translations->insert($context, $original);
if (!empty($row)) {
$translation->setTranslation(array_shift($row));
$translation->setPluralTranslations($row);
}
}
fclose($handle);
}
}

View File

@@ -0,0 +1,38 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\HeadersExtractorTrait;
/**
* Class to get gettext strings from csv.
*/
class CsvDictionary extends Extractor implements ExtractorInterface
{
use HeadersExtractorTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$handle = fopen('php://memory', 'w');
fputs($handle, $string);
rewind($handle);
while ($message = fgetcsv($handle)) {
list($original, $translation) = $message + ['', ''];
if ($original === '') {
self::extractHeaders($translation, $translations);
continue;
}
$translations->insert(null, $original)->setTranslation($translation);
}
fclose($handle);
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Gettext\Extractors;
use Exception;
use InvalidArgumentException;
use Gettext\Translations;
abstract class Extractor implements ExtractorInterface
{
/**
* {@inheritdoc}
*/
public static function fromFile($file, Translations $translations, array $options = [])
{
foreach (self::getFiles($file) as $file) {
$options['file'] = $file;
static::fromString(self::readFile($file), $translations, $options);
}
}
/**
* Checks and returns all files.
*
* @param string|array $file The file/s
*
* @return array The file paths
*/
protected static function getFiles($file)
{
if (empty($file)) {
throw new InvalidArgumentException('There is not any file defined');
}
if (is_string($file)) {
if (!is_file($file)) {
throw new InvalidArgumentException("'$file' is not a valid file");
}
if (!is_readable($file)) {
throw new InvalidArgumentException("'$file' is not a readable file");
}
return [$file];
}
if (is_array($file)) {
$files = [];
foreach ($file as $f) {
$files = array_merge($files, self::getFiles($f));
}
return $files;
}
throw new InvalidArgumentException('The first argumet must be string or array');
}
/**
* Reads and returns the content of a file.
*
* @param string $file
*
* @return string
*/
protected static function readFile($file)
{
$length = filesize($file);
if (!($fd = fopen($file, 'rb'))) {
throw new Exception("Cannot read the file '$file', probably permissions");
}
$content = $length ? fread($fd, $length) : '';
fclose($fd);
return $content;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
interface ExtractorInterface
{
/**
* Extract the translations from a file.
*
* @param array|string $file A path of a file or files
* @param Translations $translations The translations instance to append the new translations.
* @param array $options
*/
public static function fromFile($file, Translations $translations, array $options = []);
/**
* Parses a string and append the translations found in the Translations instance.
*
* @param string $string
* @param Translations $translations
* @param array $options
*/
public static function fromString($string, Translations $translations, array $options = []);
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
/**
* Class to get gettext strings from json files.
*/
class Jed extends Extractor implements ExtractorInterface
{
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
self::extract(json_decode($string, true), $translations);
}
/**
* 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);
}
}
}

View File

@@ -0,0 +1,42 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\JsFunctionsScanner;
/**
* Class to get gettext strings from javascript files.
*/
class JsCode extends Extractor implements ExtractorInterface
{
public static $options = [
'functions' => [
'gettext' => 'gettext',
'__' => 'gettext',
'ngettext' => 'ngettext',
'n__' => 'ngettext',
'pgettext' => 'pgettext',
'p__' => 'pgettext',
'dgettext' => 'dgettext',
'd__' => 'dgettext',
'dpgettext' => 'dpgettext',
'dp__' => 'dpgettext',
'npgettext' => 'npgettext',
'np__' => 'npgettext',
'dnpgettext' => 'dnpgettext',
'dnp__' => 'dnpgettext',
],
];
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$options += static::$options;
$functions = new JsFunctionsScanner($string);
$functions->saveGettextFunctions($translations, $options);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
/**
* Class to get gettext strings from json.
*/
class Json extends Extractor implements ExtractorInterface
{
use MultidimensionalArrayTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$messages = json_decode($string, true);
if (is_array($messages)) {
self::fromArray($messages, $translations);
}
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\DictionaryTrait;
/**
* Class to get gettext strings from plain json.
*/
class JsonDictionary extends Extractor implements ExtractorInterface
{
use DictionaryTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$messages = json_decode($string, true);
if (is_array($messages)) {
self::fromArray($messages, $translations);
}
}
}

View File

@@ -0,0 +1,128 @@
<?php
namespace Gettext\Extractors;
use Exception;
use Gettext\Translations;
use Gettext\Utils\StringReader;
/**
* Class to get gettext strings from .mo files.
*/
class Mo extends Extractor implements ExtractorInterface
{
const MAGIC1 = -1794895138;
const MAGIC2 = -569244523;
const MAGIC3 = 2500072158;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$stream = new StringReader($string);
$magic = self::readInt($stream, 'V');
if (($magic === self::MAGIC1) || ($magic === self::MAGIC3)) { //to make sure it works for 64-bit platforms
$byteOrder = 'V'; //low endian
} elseif ($magic === (self::MAGIC2 & 0xFFFFFFFF)) {
$byteOrder = 'N'; //big endian
} else {
throw new Exception('Not MO file');
}
self::readInt($stream, $byteOrder);
$total = self::readInt($stream, $byteOrder); //total string count
$originals = self::readInt($stream, $byteOrder); //offset of original table
$tran = self::readInt($stream, $byteOrder); //offset of translation table
$stream->seekto($originals);
$table_originals = self::readIntArray($stream, $byteOrder, $total * 2);
$stream->seekto($tran);
$table_translations = self::readIntArray($stream, $byteOrder, $total * 2);
for ($i = 0; $i < $total; ++$i) {
$next = $i * 2;
$stream->seekto($table_originals[$next + 2]);
$original = $stream->read($table_originals[$next + 1]);
$stream->seekto($table_translations[$next + 2]);
$translated = $stream->read($table_translations[$next + 1]);
if ($original === '') {
// Headers
foreach (explode("\n", $translated) as $headerLine) {
if ($headerLine === '') {
continue;
}
$headerChunks = preg_split('/:\s*/', $headerLine, 2);
$translations->setHeader($headerChunks[0], isset($headerChunks[1]) ? $headerChunks[1] : '');
}
continue;
}
$chunks = explode("\x04", $original, 2);
if (isset($chunks[1])) {
$context = $chunks[0];
$original = $chunks[1];
} else {
$context = '';
}
$chunks = explode("\x00", $original, 2);
if (isset($chunks[1])) {
$original = $chunks[0];
$plural = $chunks[1];
} else {
$plural = '';
}
$translation = $translations->insert($context, $original, $plural);
if ($translated === '') {
continue;
}
if ($plural === '') {
$translation->setTranslation($translated);
continue;
}
$v = explode("\x00", $translated);
$translation->setTranslation(array_shift($v));
$translation->setPluralTranslations($v);
}
}
/**
* @param StringReader $stream
* @param string $byteOrder
*/
private static function readInt(StringReader $stream, $byteOrder)
{
if (($read = $stream->read(4)) === false) {
return false;
}
$read = unpack($byteOrder, $read);
return array_shift($read);
}
/**
* @param StringReader $stream
* @param string $byteOrder
* @param int $count
*/
private static function readIntArray(StringReader $stream, $byteOrder, $count)
{
return unpack($byteOrder.$count, $stream->read(4 * $count));
}
}

View File

@@ -0,0 +1,33 @@
<?php
namespace Gettext\Extractors;
use BadMethodCallException;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
/**
* Class to get gettext strings from php files returning arrays.
*/
class PhpArray extends Extractor implements ExtractorInterface
{
use MultidimensionalArrayTrait;
/**
* {@inheritdoc}
*/
public static function fromFile($file, Translations $translations, array $options = [])
{
foreach (static::getFiles($file) as $file) {
self::fromArray(include($file), $translations);
}
}
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
throw new BadMethodCallException('PhpArray::fromString() cannot be called. Use PhpArray::fromFile()');
}
}

View File

@@ -0,0 +1,127 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\PhpFunctionsScanner;
/**
* Class to get gettext strings from php files returning arrays.
*/
class PhpCode extends Extractor implements ExtractorInterface
{
public static $options = [
// - false: to not extract comments
// - empty string: to extract all comments
// - non-empty string: to extract comments that start with that string
'extractComments' => false,
'functions' => [
'gettext' => 'gettext',
'__' => 'gettext',
'ngettext' => 'ngettext',
'n__' => 'ngettext',
'pgettext' => 'pgettext',
'p__' => 'pgettext',
'dgettext' => 'dgettext',
'd__' => 'dgettext',
'dpgettext' => 'dpgettext',
'dp__' => 'dpgettext',
'npgettext' => 'npgettext',
'np__' => 'npgettext',
'dnpgettext' => 'dnpgettext',
'dnp__' => 'dnpgettext',
],
];
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$options += static::$options;
$functions = new PhpFunctionsScanner($string);
if ($options['extractComments'] !== false) {
$functions->enableCommentsExtraction($options['extractComments']);
}
$functions->saveGettextFunctions($translations, $options);
}
/**
* Decodes a T_CONSTANT_ENCAPSED_STRING string.
*
* @param string $value
*
* @return string
*/
public static function convertString($value)
{
if (strpos($value, '\\') === false) {
return substr($value, 1, -1);
}
if ($value[0] === "'") {
return strtr(substr($value, 1, -1), ['\\\\' => '\\', '\\\'' => '\'']);
}
$value = substr($value, 1, -1);
return preg_replace_callback('/\\\(n|r|t|v|e|f|\$|"|\\\|x[0-9A-Fa-f]{1,2}|u{[0-9a-f]{1,6}}|[0-7]{1,3})/', function ($match) {
switch ($match[1][0]) {
case 'n':
return "\n";
case 'r':
return "\r";
case 't':
return "\t";
case 'v':
return "\v";
case 'e':
return "\e";
case 'f':
return "\f";
case '$':
return '$';
case '"':
return '"';
case '\\':
return '\\';
case 'x':
return chr(hexdec(substr($match[0], 1)));
case 'u':
return self::unicodeChar(hexdec(substr($match[0], 1)));
default:
return chr(octdec($match[0]));
}
}, $value);
}
//http://php.net/manual/en/function.chr.php#118804
private static function unicodeChar($dec)
{
if ($dec < 0x80) {
return chr($dec);
}
if ($dec < 0x0800) {
return chr(0xC0 + ($dec >> 6))
.chr(0x80 + ($dec & 0x3f));
}
if ($dec < 0x010000) {
return chr(0xE0 + ($dec >> 12))
.chr(0x80 + (($dec >> 6) & 0x3f))
.chr(0x80 + ($dec & 0x3f));
}
if ($dec < 0x200000) {
return chr(0xF0 + ($dec >> 18))
.chr(0x80 + (($dec >> 12) & 0x3f))
.chr(0x80 + (($dec >> 6) & 0x3f))
.chr(0x80 + ($dec & 0x3f));
}
}
}

View File

@@ -0,0 +1,199 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Translation;
use Gettext\Utils\HeadersExtractorTrait;
/**
* Class to get gettext strings from php files returning arrays.
*/
class Po extends Extractor implements ExtractorInterface
{
use HeadersExtractorTrait;
/**
* Parses a .po file and append the translations found in the Translations instance.
*
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$lines = explode("\n", $string);
$i = 0;
$translation = new Translation('', '');
for ($n = count($lines); $i < $n; ++$i) {
$line = trim($lines[$i]);
$line = self::fixMultiLines($line, $lines, $i);
if ($line === '') {
if ($translation->is('', '')) {
self::extractHeaders($translation->getTranslation(), $translations);
} elseif ($translation->hasOriginal()) {
$translations[] = $translation;
}
$translation = new Translation('', '');
continue;
}
$splitLine = preg_split('/\s+/', $line, 2);
$key = $splitLine[0];
$data = isset($splitLine[1]) ? $splitLine[1] : '';
switch ($key) {
case '#':
$translation->addComment($data);
$append = null;
break;
case '#.':
$translation->addExtractedComment($data);
$append = null;
break;
case '#,':
foreach (array_map('trim', explode(',', trim($data))) as $value) {
$translation->addFlag($value);
}
$append = null;
break;
case '#:':
foreach (preg_split('/\s+/', trim($data)) as $value) {
if (preg_match('/^(.+)(:(\d*))?$/U', $value, $matches)) {
$translation->addReference($matches[1], isset($matches[3]) ? $matches[3] : null);
}
}
$append = null;
break;
case 'msgctxt':
$translation = $translation->getClone(self::convertString($data));
$append = 'Context';
break;
case 'msgid':
$translation = $translation->getClone(null, self::convertString($data));
$append = 'Original';
break;
case 'msgid_plural':
$translation->setPlural(self::convertString($data));
$append = 'Plural';
break;
case 'msgstr':
case 'msgstr[0]':
$translation->setTranslation(self::convertString($data));
$append = 'Translation';
break;
case 'msgstr[1]':
$translation->setPluralTranslations([self::convertString($data)]);
$append = 'PluralTranslation';
break;
default:
if (strpos($key, 'msgstr[') === 0) {
$p = $translation->getPluralTranslations();
$p[] = self::convertString($data);
$translation->setPluralTranslations($p);
$append = 'PluralTranslation';
break;
}
if (isset($append)) {
if ($append === 'Context') {
$translation = $translation->getClone($translation->getContext()."\n".self::convertString($data));
break;
}
if ($append === 'Original') {
$translation = $translation->getClone(null, $translation->getOriginal()."\n".self::convertString($data));
break;
}
if ($append === 'PluralTranslation') {
$p = $translation->getPluralTranslations();
$p[] = array_pop($p)."\n".self::convertString($data);
$translation->setPluralTranslations($p);
break;
}
$getMethod = 'get'.$append;
$setMethod = 'set'.$append;
$translation->$setMethod($translation->$getMethod()."\n".self::convertString($data));
}
break;
}
}
if ($translation->hasOriginal() && !in_array($translation, iterator_to_array($translations))) {
$translations[] = $translation;
}
}
/**
* Gets one string from multiline strings.
*
* @param string $line
* @param array $lines
* @param int &$i
*
* @return string
*/
private static function fixMultiLines($line, array $lines, &$i)
{
for ($j = $i, $t = count($lines); $j < $t; ++$j) {
if (substr($line, -1, 1) == '"'
&& isset($lines[$j + 1])
&& substr(trim($lines[$j + 1]), 0, 1) == '"'
) {
$line = substr($line, 0, -1).substr(trim($lines[$j + 1]), 1);
} else {
$i = $j;
break;
}
}
return $line;
}
/**
* Convert a string from its PO representation.
*
* @param string $value
*
* @return string
*/
public static function convertString($value)
{
if (!$value) {
return '';
}
if ($value[0] === '"') {
$value = substr($value, 1, -1);
}
return strtr(
$value,
[
'\\\\' => '\\',
'\\a' => "\x07",
'\\b' => "\x08",
'\\t' => "\t",
'\\n' => "\n",
'\\v' => "\x0b",
'\\f' => "\x0c",
'\\r' => "\r",
'\\"' => '"',
]
);
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Twig_Loader_String;
use Twig_Environment;
use Twig_Extensions_Extension_I18n;
/**
* Class to get gettext strings from twig files returning arrays.
*/
class Twig extends Extractor implements ExtractorInterface
{
public static $options = [
'twig' => null
];
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$options += static::$options;
$twig = $options['twig'] ?: self::createTwig();
PhpCode::fromString($twig->compileSource($string), $translations, $options);
}
/**
* Returns a Twig instance.
*
* @return Twig_Environment
*/
private static function createTwig()
{
$twig = new Twig_Environment(new Twig_Loader_String());
$twig->addExtension(new Twig_Extensions_Extension_I18n());
return static::$options['twig'] = $twig;
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Translation;
use SimpleXMLElement;
/**
* Class to get gettext strings from xliff format.
*/
class Xliff extends Extractor implements ExtractorInterface
{
/**
* {@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;
}
}
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
use Symfony\Component\Yaml\Yaml as YamlParser;
/**
* Class to get gettext strings from yaml.
*/
class Yaml extends Extractor implements ExtractorInterface
{
use MultidimensionalArrayTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$messages = YamlParser::parse($string);
if (is_array($messages)) {
self::fromArray($messages, $translations);
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace Gettext\Extractors;
use Gettext\Translations;
use Gettext\Utils\DictionaryTrait;
use Symfony\Component\Yaml\Yaml as YamlParser;
/**
* Class to get gettext strings from yaml.
*/
class YamlDictionary extends Extractor implements ExtractorInterface
{
use DictionaryTrait;
/**
* {@inheritdoc}
*/
public static function fromString($string, Translations $translations, array $options = [])
{
$messages = YamlParser::parse($string);
if (is_array($messages)) {
self::fromArray($messages, $translations);
}
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\HeadersGeneratorTrait;
/**
* Class to export translations to csv.
*/
class Csv extends Generator implements GeneratorInterface
{
use HeadersGeneratorTrait;
public static $options = [
'includeHeaders' => false,
];
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
$handle = fopen('php://memory', 'w');
if ($options['includeHeaders']) {
fputcsv($handle, ['', '', self::generateHeaders($translations)]);
}
foreach ($translations as $translation) {
$line = [$translation->getContext(), $translation->getOriginal(), $translation->getTranslation()];
if ($translation->hasPluralTranslations(true)) {
$line = array_merge($line, $translation->getPluralTranslations());
}
fputcsv($handle, $line);
}
rewind($handle);
$csv = stream_get_contents($handle);
fclose($handle);
return $csv;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\DictionaryTrait;
class CsvDictionary extends Generator implements GeneratorInterface
{
use DictionaryTrait;
public static $options = [
'includeHeaders' => false,
];
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
$handle = fopen('php://memory', 'w');
foreach (self::toArray($translations, $options['includeHeaders']) as $original => $translation) {
fputcsv($handle, [$original, $translation]);
}
rewind($handle);
$csv = stream_get_contents($handle);
fclose($handle);
return $csv;
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
abstract class Generator implements GeneratorInterface
{
/**
* {@inheritdoc}
*/
public static function toFile(Translations $translations, $file, array $options = [])
{
$content = static::toString($translations);
if (file_put_contents($file, $content) === false) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
interface GeneratorInterface
{
/**
* Saves the translations in a file.
*
* @param Translations $translations
* @param string $file
* @param array $options
*
* @return bool
*/
public static function toFile(Translations $translations, $file, array $options = []);
/**
* Generates a string with the translations ready to save in a file.
*
* @param Translations $translations
* @param array $options
*
* @return string
*/
public static function toString(Translations $translations, array $options = []);
}

View File

@@ -0,0 +1,61 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
class Jed extends Generator implements GeneratorInterface
{
public static $options = [
'json' => 0,
];
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$domain = $translations->getDomain() ?: 'messages';
$options += static::$options;
return json_encode([
$domain => [
'' => [
'domain' => $domain,
'lang' => $translations->getLanguage() ?: 'en',
'plural-forms' => $translations->getHeader('Plural-Forms') ?: 'nplurals=2; plural=(n != 1);',
],
] + self::buildMessages($translations),
], $options['json']);
}
/**
* Generates an array with all translations.
*
* @param Translations $translations
*
* @return array
*/
private static function buildMessages(Translations $translations)
{
$pluralForm = $translations->getPluralForms();
$pluralLimit = 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($pluralLimit);
array_unshift($message, $translation->getTranslation());
} else {
$message = [$translation->getTranslation()];
}
$messages[$key] = $message;
}
return $messages;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
class Json extends Generator implements GeneratorInterface
{
use MultidimensionalArrayTrait;
public static $options = [
'json' => 0,
'includeHeaders' => false,
];
/**
* {@inheritdoc}
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
return json_encode(self::toArray($translations, $options['includeHeaders'], true), $options['json']);
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\DictionaryTrait;
class JsonDictionary extends Generator implements GeneratorInterface
{
use DictionaryTrait;
public static $options = [
'json' => 0,
'includeHeaders' => false,
];
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
return json_encode(self::toArray($translations, $options['includeHeaders']), $options['json']);
}
}

View File

@@ -0,0 +1,134 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\HeadersGeneratorTrait;
class Mo extends Generator implements GeneratorInterface
{
use HeadersGeneratorTrait;
public static $options = [
'includeHeaders' => true,
];
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
$messages = [];
if ($options['includeHeaders']) {
$messages[''] = self::generateHeaders($translations);
}
foreach ($translations as $translation) {
if (!$translation->hasTranslation()) {
continue;
}
if ($translation->hasContext()) {
$originalString = $translation->getContext()."\x04".$translation->getOriginal();
} else {
$originalString = $translation->getOriginal();
}
$messages[$originalString] = $translation;
}
ksort($messages);
$numEntries = count($messages);
$originalsTable = '';
$translationsTable = '';
$originalsIndex = [];
$translationsIndex = [];
$pluralForm = $translations->getPluralForms();
$pluralLimit = is_array($pluralForm) ? ($pluralForm[0] - 1) : null;
foreach ($messages as $originalString => $translation) {
if (is_string($translation)) {
// Headers
$translationString = $translation;
} else {
/* @var $translation \Gettext\Translation */
if ($translation->hasPlural() && $translation->hasPluralTranslations(true)) {
$originalString .= "\x00".$translation->getPlural();
$translationString = $translation->getTranslation();
$translationString .= "\x00".implode("\x00", $translation->getPluralTranslations($pluralLimit));
} else {
$translationString = $translation->getTranslation();
}
}
$originalsIndex[] = ['relativeOffset' => strlen($originalsTable), 'length' => strlen($originalString)];
$originalsTable .= $originalString."\x00";
$translationsIndex[] = ['relativeOffset' => strlen($translationsTable), 'length' => strlen($translationString)];
$translationsTable .= $translationString."\x00";
}
// Offset of table with the original strings index: right after the header (which is 7 words)
$originalsIndexOffset = 7 * 4;
// Size of table with the original strings index
$originalsIndexSize = $numEntries * (4 + 4);
// Offset of table with the translation strings index: right after the original strings index table
$translationsIndexOffset = $originalsIndexOffset + $originalsIndexSize;
// Size of table with the translation strings index
$translationsIndexSize = $numEntries * (4 + 4);
// Hashing table starts after the header and after the index table
$originalsStringsOffset = $translationsIndexOffset + $translationsIndexSize;
// Translations start after the keys
$translationsStringsOffset = $originalsStringsOffset + strlen($originalsTable);
// Let's generate the .mo file binary data
$mo = '';
// Magic number
$mo .= pack('L', 0x950412de);
// File format revision
$mo .= pack('L', 0);
// Number of strings
$mo .= pack('L', $numEntries);
// Offset of table with original strings
$mo .= pack('L', $originalsIndexOffset);
// Offset of table with translation strings
$mo .= pack('L', $translationsIndexOffset);
// Size of hashing table: we don't use it.
$mo .= pack('L', 0);
// Offset of hashing table: it would start right after the translations index table
$mo .= pack('L', $translationsIndexOffset + $translationsIndexSize);
// Write the lengths & offsets of the original strings
foreach ($originalsIndex as $info) {
$mo .= pack('L', $info['length']);
$mo .= pack('L', $originalsStringsOffset + $info['relativeOffset']);
}
// Write the lengths & offsets of the translated strings
foreach ($translationsIndex as $info) {
$mo .= pack('L', $info['length']);
$mo .= pack('L', $translationsStringsOffset + $info['relativeOffset']);
}
// Write original strings
$mo .= $originalsTable;
// Write translation strings
$mo .= $translationsTable;
return $mo;
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
class PhpArray extends Generator implements GeneratorInterface
{
use MultidimensionalArrayTrait;
public static $options = [
'includeHeaders' => true,
];
/**
* {@inheritdoc}
*/
public static function toString(Translations $translations, array $options = [])
{
$array = self::generate($translations, $options);
return '<?php return '.var_export($array, true).';';
}
/**
* Generates an array with the translations.
*
* @param Translations $translations
* @param array $options
*
* @return array
*/
public static function generate(Translations $translations, array $options = [])
{
$options += static::$options;
return self::toArray($translations, $options['includeHeaders'], true);
}
}

View File

@@ -0,0 +1,134 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
class Po extends Generator implements GeneratorInterface
{
/**
* {@parentDoc}.
*/
public static function toString(Translations $translations, array $options = [])
{
$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() as $k => $v) {
self::addLines($lines, 'msgstr['.($k + 1).']', $v);
}
} else {
self::addLines($lines, 'msgstr', $translation->getTranslation());
}
$lines[] = '';
}
return implode("\n", $lines);
}
/**
* Escapes and adds double quotes to a string.
*
* @param string $string
*
* @return string
*/
private static function multilineQuote($string)
{
$lines = explode("\n", $string);
$last = count($lines) - 1;
foreach ($lines as $k => $line) {
if ($k === $last) {
$lines[$k] = self::convertString($line);
} else {
$lines[$k] = self::convertString($line."\n");
}
}
return $lines;
}
/**
* Add one or more lines depending whether the string is multiline or not.
*
* @param array &$lines
* @param string $name
* @param string $value
*/
private static function addLines(array &$lines, $name, $value)
{
$newLines = self::multilineQuote($value);
if (count($newLines) === 1) {
$lines[] = $name.' '.$newLines[0];
} else {
$lines[] = $name.' ""';
foreach ($newLines as $line) {
$lines[] = $line;
}
}
}
/**
* Convert a string to its PO representation.
*
* @param string $value
*
* @return string
*/
public static function convertString($value)
{
return '"'.strtr(
$value,
[
"\x00" => '',
'\\' => '\\\\',
"\t" => '\t',
"\n" => '\n',
'"' => '\\"',
]
).'"';
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use DOMDocument;
class Xliff extends Generator implements GeneratorInterface
{
/**
* {@inheritdoc}
*/
public static function toString(Translations $translations, array $options = [])
{
$dom = new DOMDocument('1.0', 'utf-8');
$dom->formatOutput = true;
$xliff = $dom->appendChild($dom->createElement('xliff'));
$xliff->setAttribute('xmlns', 'urn:oasis:names:tc:xliff:document:2.0');
$xliff->setAttribute('version', '2.0');
$xliff->setAttribute('srcLang', $translations->getLanguage());
$xliff->setAttribute('trgLang', $translations->getLanguage());
$file = $xliff->appendChild($dom->createElement('file'));
$file->setAttribute('id', $translations->getDomain().'.'.$translations->getLanguage());
//Save headers as notes
$notes = $dom->createElement('notes');
foreach ($translations->getHeaders() as $name => $value) {
$notes->appendChild(self::createTextNode($dom, 'note', $value))->setAttribute('id', $name);
}
if ($notes->hasChildNodes()) {
$file->appendChild($notes);
}
foreach ($translations as $translation) {
$unit = $dom->createElement('unit');
$unit->setAttribute('id', md5($translation->getContext().$translation->getOriginal()));
//Save comments as notes
$notes = $dom->createElement('notes');
$notes->appendChild(self::createTextNode($dom, 'note', $translation->getContext()))->setAttribute('category', 'context');
foreach ($translation->getComments() as $comment) {
$notes->appendChild(self::createTextNode($dom, 'note', $comment))->setAttribute('category', 'comment');
}
foreach ($translation->getExtractedComments() as $comment) {
$notes->appendChild(self::createTextNode($dom, 'note', $comment))->setAttribute('category', 'extracted-comment');
}
foreach ($translation->getFlags() as $flag) {
$notes->appendChild(self::createTextNode($dom, 'note', $flag))->setAttribute('category', 'flag');
}
foreach ($translation->getReferences() as $reference) {
$notes->appendChild(self::createTextNode($dom, 'note', $reference[0].':'.$reference[1]))->setAttribute('category', 'reference');
}
$unit->appendChild($notes);
$segment = $unit->appendChild($dom->createElement('segment'));
$segment->appendChild(self::createTextNode($dom, 'source', $translation->getOriginal()));
$segment->appendChild(self::createTextNode($dom, 'target', $translation->getTranslation()));
foreach ($translation->getPluralTranslations() as $plural) {
if ($plural !== '') {
$segment->appendChild(self::createTextNode($dom, 'target', $plural));
}
}
$file->appendChild($unit);
}
return $dom->saveXML();
}
private static function createTextNode(DOMDocument $dom, $name, $string)
{
$node = $dom->createElement($name);
$text = (preg_match('/[&<>]/', $string) === 1) ? $dom->createCDATASection($string) : $dom->createTextNode($string);
$node->appendChild($text);
return $node;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\MultidimensionalArrayTrait;
use Symfony\Component\Yaml\Yaml as YamlDumper;
class Yaml extends Generator implements GeneratorInterface
{
use MultidimensionalArrayTrait;
public static $options = [
'includeHeaders' => false,
'indent' => 2,
'inline' => 4,
];
/**
* {@inheritdoc}
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
return YamlDumper::dump(self::toArray($translations, $options['includeHeaders']), $options['inline'], $options['indent']);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Gettext\Generators;
use Gettext\Translations;
use Gettext\Utils\DictionaryTrait;
use Symfony\Component\Yaml\Yaml as YamlDumper;
class YamlDictionary extends Generator implements GeneratorInterface
{
use DictionaryTrait;
public static $options = [
'includeHeaders' => false,
'indent' => 2,
'inline' => 3,
];
/**
* {@inheritdoc}
*/
public static function toString(Translations $translations, array $options = [])
{
$options += static::$options;
return YamlDumper::dump(self::toArray($translations, $options['includeHeaders']), $options['inline'], $options['indent']);
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace Gettext;
class GettextTranslator extends BaseTranslator implements TranslatorInterface
{
/**
* Constructor. Detects the current language using the environment variables.
*
* @param string $language
*/
public function __construct($language = null)
{
if (!function_exists('gettext')) {
throw new \RuntimeException('This class require the gettext extension for PHP');
}
//detects the language environment respecting the priority order
//http://php.net/manual/en/function.gettext.php#114062
if (empty($language)) {
$language = getenv('LANGUAGE') ?: getenv('LC_ALL') ?: getenv('LC_MESSAGES') ?: getenv('LANG');
}
if (!empty($language)) {
$this->setLanguage($language);
}
}
/**
* Define the current locale.
*
* @param string $language
* @param int|null $category
*
* @return self
*/
public function setLanguage($language, $category = null)
{
if ($category === null) {
$category = defined('LC_MESSAGES') ? LC_MESSAGES : LC_ALL;
}
setlocale($category, $language);
putenv('LANGUAGE='.$language);
return $this;
}
/**
* Loads a gettext domain.
*
* @param string $domain
* @param string $path
* @param bool $default
*
* @return self
*/
public function loadDomain($domain, $path = null, $default = true)
{
bindtextdomain($domain, $path);
bind_textdomain_codeset($domain, 'UTF-8');
if ($default) {
textdomain($domain);
}
return $this;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function gettext($original)
{
return gettext($original);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function ngettext($original, $plural, $value)
{
return ngettext($original, $plural, $value);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dngettext($domain, $original, $plural, $value)
{
return dngettext($domain, $original, $plural, $value);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function npgettext($context, $original, $plural, $value)
{
$message = $context."\x04".$original;
$translation = ngettext($message, $plural, $value);
return ($translation === $message) ? $original : $translation;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function pgettext($context, $original)
{
$message = $context."\x04".$original;
$translation = gettext($message);
return ($translation === $message) ? $original : $translation;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dgettext($domain, $original)
{
return dgettext($domain, $original);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dpgettext($domain, $context, $original)
{
$message = $context."\x04".$original;
$translation = dgettext($domain, $message);
return ($translation === $message) ? $original : $translation;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dnpgettext($domain, $context, $original, $plural, $value)
{
$message = $context."\x04".$original;
$translation = dngettext($domain, $message, $plural, $value);
return ($translation === $message) ? $original : $translation;
}
}

View File

@@ -0,0 +1,221 @@
<?php
namespace Gettext;
/**
* Static class with merge contants.
*/
class Merge
{
const ADD = 1;
const REMOVE = 2;
const HEADERS_ADD = 4;
const HEADERS_REMOVE = 8;
const HEADERS_OVERRIDE = 16;
const LANGUAGE_OVERRIDE = 32;
const DOMAIN_OVERRIDE = 64;
const TRANSLATION_OVERRIDE = 128;
const COMMENTS_OURS = 256;
const COMMENTS_THEIRS = 512;
const EXTRACTED_COMMENTS_OURS = 1024;
const EXTRACTED_COMMENTS_THEIRS = 2048;
const FLAGS_OURS = 4096;
const FLAGS_THEIRS = 8192;
const REFERENCES_OURS = 16384;
const REFERENCES_THEIRS = 32768;
const DEFAULTS = 5; //1 + 4
/**
* Merge the flags of two translations.
*
* @param Translation $from
* @param Translation $to
* @param int $options
*/
public static function mergeFlags(Translation $from, Translation $to, $options = self::DEFAULTS)
{
if ($options & self::FLAGS_THEIRS) {
$to->deleteFlags();
}
if (!($options & self::FLAGS_OURS)) {
foreach ($from->getFlags() as $flag) {
$to->addFlag($flag);
}
}
}
/**
* Merge the extracted comments of two translations.
*
* @param Translation $from
* @param Translation $to
* @param int $options
*/
public static function mergeExtractedComments(Translation $from, Translation $to, $options = self::DEFAULTS)
{
if ($options & self::EXTRACTED_COMMENTS_THEIRS) {
$to->deleteExtractedComments();
}
if (!($options & self::EXTRACTED_COMMENTS_OURS)) {
foreach ($from->getExtractedComments() as $comment) {
$to->addExtractedComment($comment);
}
}
}
/**
* Merge the comments of two translations.
*
* @param Translation $from
* @param Translation $to
* @param int $options
*/
public static function mergeComments(Translation $from, Translation $to, $options = self::DEFAULTS)
{
if ($options & self::COMMENTS_THEIRS) {
$to->deleteComments();
}
if (!($options & self::COMMENTS_OURS)) {
foreach ($from->getComments() as $comment) {
$to->addComment($comment);
}
}
}
/**
* Merge the references of two translations.
*
* @param Translation $from
* @param Translation $to
* @param int $options
*/
public static function mergeReferences(Translation $from, Translation $to, $options = self::DEFAULTS)
{
if ($options & self::REFERENCES_THEIRS) {
$to->deleteReferences();
}
if (!($options & self::REFERENCES_OURS)) {
foreach ($from->getReferences() as $reference) {
$to->addReference($reference[0], $reference[1]);
}
}
}
/**
* Merge the translations of two translations.
*
* @param Translation $from
* @param Translation $to
* @param int $options
*/
public static function mergeTranslation(Translation $from, Translation $to, $options = self::DEFAULTS)
{
$override = (boolean) ($options & self::TRANSLATION_OVERRIDE);
if (!$to->hasTranslation() || ($from->hasTranslation() && $override)) {
$to->setTranslation($from->getTranslation());
}
if (!$to->hasPlural() || ($from->hasPlural() && $override)) {
$to->setPlural($from->getPlural());
}
if (!$to->hasPluralTranslations() || ($from->hasPluralTranslations() && $override)) {
$to->setPluralTranslations($from->getPluralTranslations());
}
}
/**
* Merge the translations of two translations.
*
* @param Translations $from
* @param Translations $to
* @param int $options
*/
public static function mergeTranslations(Translations $from, Translations $to, $options = self::DEFAULTS)
{
if ($options & self::REMOVE) {
$filtered = [];
foreach ($to as $entry) {
if ($from->find($entry)) {
$filtered[$entry->getId()] = $entry;
}
}
$to->exchangeArray($filtered);
}
foreach ($from as $entry) {
if (($existing = $to->find($entry))) {
$existing->mergeWith($entry);
} elseif ($options & self::ADD) {
$to[] = $entry;
}
}
}
/**
* Merge the headers of two translations.
*
* @param Translations $from
* @param Translations $to
* @param int $options
*/
public static function mergeHeaders(Translations $from, Translations $to, $options = self::DEFAULTS)
{
if ($options & self::HEADERS_REMOVE) {
foreach (array_keys($to->getHeaders()) as $name) {
if ($from->getHeader($name) === null) {
$to->deleteHeader($name);
}
}
}
foreach ($from->getHeaders() as $name => $value) {
$current = $to->getHeader($name);
if (empty($current)) {
if ($options & self::HEADERS_ADD) {
$to->setHeader($name, $value);
}
continue;
}
if (empty($value)) {
continue;
}
switch ($name) {
case Translations::HEADER_LANGUAGE:
case Translations::HEADER_PLURAL:
if ($options & self::LANGUAGE_OVERRIDE) {
$to->setHeader($name, $value);
}
break;
case Translations::HEADER_DOMAIN:
if ($options & self::DOMAIN_OVERRIDE) {
$to->setHeader($name, $value);
}
break;
default:
if ($options & self::HEADERS_OVERRIDE) {
$to->setHeader($name, $value);
}
}
}
}
}

View File

@@ -0,0 +1,480 @@
<?php
namespace Gettext;
/**
* Class to manage a translation string.
*/
class Translation
{
protected $context;
protected $original;
protected $translation = '';
protected $plural;
protected $pluralTranslation = [];
protected $references = [];
protected $comments = [];
protected $extractedComments = [];
protected $flags = [];
/**
* Generates the id of a translation (context + glue + original).
*
* @param string $context
* @param string $original
*
* @return string
*/
public static function generateId($context, $original)
{
return "{$context}\004{$original}";
}
/**
* Construct.
*
* @param string $context The context of the translation
* @param string $original The original string
* @param string $plural The original plural string
*/
public function __construct($context, $original, $plural = '')
{
$this->context = (string) $context;
$this->original = (string) $original;
$this->setPlural($plural);
}
/**
* Clones this translation.
*
* @param null|string $context Optional new context
* @param null|string $original Optional new original
*
* @return Translation
*/
public function getClone($context = null, $original = null)
{
$new = clone $this;
if ($context !== null) {
$new->context = (string) $context;
}
if ($original !== null) {
$new->original = (string) $original;
}
return $new;
}
/**
* Returns the id of this translation.
*
* @return string
*/
public function getId()
{
return static::generateId($this->context, $this->original);
}
/**
* Checks whether the translation matches with the arguments.
*
* @param string $context
* @param string $original
*
* @return bool
*/
public function is($context, $original = '')
{
return (($this->context === $context) && ($this->original === $original)) ? true : false;
}
/**
* Gets the original string.
*
* @return string
*/
public function getOriginal()
{
return $this->original;
}
/**
* Checks if the original string is empty or not.
*
* @return bool
*/
public function hasOriginal()
{
return ($this->original !== '') ? true : false;
}
/**
* Sets the translation string.
*
* @param string $translation
*
* @return self
*/
public function setTranslation($translation)
{
$this->translation = (string) $translation;
return $this;
}
/**
* Gets the translation string.
*
* @return string
*/
public function getTranslation()
{
return $this->translation;
}
/**
* Checks if the translation string is empty or not.
*
* @return bool
*/
public function hasTranslation()
{
return ($this->translation !== '') ? true : false;
}
/**
* Sets the plural translation string.
*
* @param string $plural
*
* @return self
*/
public function setPlural($plural)
{
$this->plural = (string) $plural;
return $this;
}
/**
* Gets the plural translation string.
*
* @return string
*/
public function getPlural()
{
return $this->plural;
}
/**
* Checks if the plural translation string is empty or not.
*
* @return bool
*/
public function hasPlural()
{
return ($this->plural !== '') ? true : false;
}
/**
* Set a new plural translation.
*
* @param array $plural
*
* @return self
*/
public function setPluralTranslations(array $plural)
{
$this->pluralTranslation = $plural;
return $this;
}
/**
* Gets all plural translations.
*
* @param int $limit
*
* @return array
*/
public function getPluralTranslations($limit = null)
{
if ($limit === null) {
return $this->pluralTranslation;
}
$current = count($this->pluralTranslation);
if ($limit > $current) {
return $this->pluralTranslation + array_fill(0, $limit, '');
}
if ($limit < $current) {
return array_slice($this->pluralTranslation, 0, $limit);
}
return $this->pluralTranslation;
}
/**
* Checks if there are any plural translation.
*
* @param bool $checkContent
*
* @return bool
*/
public function hasPluralTranslations($checkContent = false)
{
if ($checkContent) {
return implode('', $this->pluralTranslation) !== '';
}
return !empty($this->pluralTranslation);
}
/**
* Removes all plural translations.
*
* @return self
*/
public function deletePluralTranslation()
{
$this->pluralTranslation = [];
return $this;
}
/**
* Gets the context of this translation.
*
* @return string
*/
public function getContext()
{
return $this->context;
}
/**
* Checks if the context is empty or not.
*
* @return bool
*/
public function hasContext()
{
return (isset($this->context) && ($this->context !== '')) ? true : false;
}
/**
* Adds a new reference for this translation.
*
* @param string $filename The file path where the translation has been found
* @param null|int $line The line number where the translation has been found
*
* @return self
*/
public function addReference($filename, $line = null)
{
$key = "{$filename}:{$line}";
$this->references[$key] = [$filename, $line];
return $this;
}
/**
* Checks if the translation has any reference.
*
* @return bool
*/
public function hasReferences()
{
return !empty($this->references);
}
/**
* Return all references for this translation.
*
* @return array
*/
public function getReferences()
{
return array_values($this->references);
}
/**
* Removes all references.
*
* @return self
*/
public function deleteReferences()
{
$this->references = [];
return $this;
}
/**
* Adds a new comment for this translation.
*
* @param string $comment
*
* @return self
*/
public function addComment($comment)
{
if (!in_array($comment, $this->comments, true)) {
$this->comments[] = $comment;
}
return $this;
}
/**
* Checks if the translation has any comment.
*
* @return bool
*/
public function hasComments()
{
return isset($this->comments[0]);
}
/**
* Returns all comments for this translation.
*
* @return array
*/
public function getComments()
{
return $this->comments;
}
/**
* Removes all comments.
*
* @return self
*/
public function deleteComments()
{
$this->comments = [];
return $this;
}
/**
* Adds a new extracted comment for this translation.
*
* @param string $comment
*
* @return self
*/
public function addExtractedComment($comment)
{
if (!in_array($comment, $this->extractedComments, true)) {
$this->extractedComments[] = $comment;
}
return $this;
}
/**
* Checks if the translation has any extracted comment.
*
* @return bool
*/
public function hasExtractedComments()
{
return isset($this->extractedComments[0]);
}
/**
* Returns all extracted comments for this translation.
*
* @return array
*/
public function getExtractedComments()
{
return $this->extractedComments;
}
/**
* Removes all extracted comments.
*
* @return self
*/
public function deleteExtractedComments()
{
$this->extractedComments = [];
return $this;
}
/**
* Adds a new flag for this translation.
*
* @param string $flag
*
* @return self
*/
public function addFlag($flag)
{
if (!in_array($flag, $this->flags, true)) {
$this->flags[] = $flag;
}
return $this;
}
/**
* Checks if the translation has any flag.
*
* @return bool
*/
public function hasFlags()
{
return isset($this->flags[0]);
}
/**
* Returns all extracted flags for this translation.
*
* @return array
*/
public function getFlags()
{
return $this->flags;
}
/**
* Removes all flags.
*
* @return self
*/
public function deleteFlags()
{
$this->flags = [];
return $this;
}
/**
* Merges this translation with other translation.
*
* @param Translation $translation The translation to merge with
* @param int $options
*
* @return self
*/
public function mergeWith(Translation $translation, $options = Merge::DEFAULTS)
{
Merge::mergeTranslation($translation, $this, $options);
Merge::mergeReferences($translation, $this, $options);
Merge::mergeComments($translation, $this, $options);
Merge::mergeExtractedComments($translation, $this, $options);
Merge::mergeFlags($translation, $this, $options);
return $this;
}
}

View File

@@ -0,0 +1,409 @@
<?php
namespace Gettext;
use Gettext\Languages\Language;
use BadMethodCallException;
use InvalidArgumentException;
/**
* Class to manage a collection of translations.
*
* @method addFromCsvFile(string $filename, array $options = [])
* @method addFromCsvString(array $options = [])
* @method toCsvFile(string $filename, array $options = [])
* @method toCsvString(array $options = [])
* @method addFromCsvDictionaryFile(string $filename, array $options = [])
* @method addFromCsvDictionaryString(array $options = [])
* @method toCsvDictionaryFile(string $filename, array $options = [])
* @method toCsvDictionaryString(array $options = [])
* @method addFromJedFile(string $filename, array $options = [])
* @method addFromJedString(array $options = [])
* @method toJedFile(string $filename, array $options = [])
* @method toJedString(array $options = [])
* @method addFromJsonFile(string $filename, array $options = [])
* @method addFromJsonString(array $options = [])
* @method toJsonFile(string $filename, array $options = [])
* @method toJsonString(array $options = [])
* @method addFromJsonDictionaryFile(string $filename, array $options = [])
* @method addFromJsonDictionaryString(array $options = [])
* @method toJsonDictionaryFile(string $filename, array $options = [])
* @method toJsonDictionaryString(array $options = [])
* @method addFromMoFile(string $filename, array $options = [])
* @method addFromMoString(array $options = [])
* @method toMoFile(string $filename, array $options = [])
* @method toMoString(array $options = [])
* @method addFromPhpArrayFile(string $filename, array $options = [])
* @method addFromPhpArrayString(array $options = [])
* @method toPhpArrayFile(string $filename, array $options = [])
* @method toPhpArrayString(array $options = [])
* @method addFromPoFile(string $filename, array $options = [])
* @method addFromPoString(array $options = [])
* @method toPoFile(string $filename, array $options = [])
* @method toPoString(array $options = [])
* @method addFromXliffFile(string $filename, array $options = [])
* @method addFromXliffString(array $options = [])
* @method toXliffFile(string $filename, array $options = [])
* @method toXliffString(array $options = [])
* @method addFromYamlFile(string $filename, array $options = [])
* @method addFromYamlString(array $options = [])
* @method toYamlFile(string $filename, array $options = [])
* @method toYamlString(array $options = [])
* @method addFromYamlDictionaryFile(string $filename, array $options = [])
* @method addFromYamlDictionaryString(array $options = [])
* @method toYamlDictionaryFile(string $filename, array $options = [])
* @method toYamlDictionaryString(array $options = [])
*/
class Translations extends \ArrayObject
{
const HEADER_LANGUAGE = 'Language';
const HEADER_PLURAL = 'Plural-Forms';
const HEADER_DOMAIN = 'X-Domain';
public static $options = [
'defaultHeaders' => [
'Project-Id-Version' => '',
'Report-Msgid-Bugs-To' => '',
'Last-Translator' => '',
'Language-Team' => '',
'MIME-Version' => '1.0',
'Content-Type' => 'text/plain; charset=UTF-8',
'Content-Transfer-Encoding' => '8bit',
],
'headersSorting' => false,
'defaultDateHeaders' => [
'POT-Creation-Date',
'PO-Revision-Date',
],
];
private $headers;
/**
* @see \ArrayObject::__construct()
*/
public function __construct($input = [], $flags = 0, $iterator_class = 'ArrayIterator')
{
$this->headers = static::$options['defaultHeaders'];
foreach (static::$options['defaultDateHeaders'] as $header) {
$this->headers[$header] = date('c');
}
$this->headers[self::HEADER_LANGUAGE] = '';
parent::__construct($input, $flags, $iterator_class);
}
/**
* Magic method to create new instances using extractors
* For example: Translations::fromMoFile($filename, $options);.
*
* @return Translations
*/
public static function __callStatic($name, $arguments)
{
if (!preg_match('/^from(\w+)(File|String)$/i', $name, $matches)) {
throw new BadMethodCallException("The method $name does not exists");
}
return call_user_func_array([new static(), 'add'.ucfirst($name)], $arguments);
}
/**
* Magic method to import/export the translations to a specific format
* For example: $translations->toMoFile($filename, $options);
* For example: $translations->addFromMoFile($filename, $options);.
*
* @return self|bool
*/
public function __call($name, $arguments)
{
if (!preg_match('/^(addFrom|to)(\w+)(File|String)$/i', $name, $matches)) {
throw new BadMethodCallException("The method $name does not exists");
}
if ($matches[1] === 'addFrom') {
$extractor = 'Gettext\\Extractors\\'.$matches[2].'::from'.$matches[3];
$source = array_shift($arguments);
$options = array_shift($arguments) ?: [];
call_user_func($extractor, $source, $this, $options);
return $this;
}
$generator = 'Gettext\\Generators\\'.$matches[2].'::to'.$matches[3];
array_unshift($arguments, $this);
return call_user_func_array($generator, $arguments);
}
/**
* Magic method to clone each translation on clone the translations object.
*/
public function __clone()
{
$array = [];
foreach ($this as $key => $translation) {
$array[$key] = clone $translation;
}
$this->exchangeArray($array);
}
/**
* Control the new translations added.
*
* @param mixed $index
* @param Translation $value
*
* @throws InvalidArgumentException If the value is not an instance of Gettext\Translation
*
* @return Translation
*/
public function offsetSet($index, $value)
{
if (!($value instanceof Translation)) {
throw new InvalidArgumentException('Only instances of Gettext\\Translation must be added to a Gettext\\Translations');
}
$id = $value->getId();
if ($this->offsetExists($id)) {
$this[$id]->mergeWith($value);
return $this[$id];
}
parent::offsetSet($id, $value);
return $value;
}
/**
* Set the plural definition.
*
* @param int $count
* @param string $rule
*
* @return self
*/
public function setPluralForms($count, $rule)
{
$this->setHeader(self::HEADER_PLURAL, "nplurals={$count}; plural={$rule};");
return $this;
}
/**
* Returns the parsed plural definition.
*
* @param null|array [count, rule]
*/
public function getPluralForms()
{
$header = $this->getHeader(self::HEADER_PLURAL);
if (!empty($header) && preg_match('/^nplurals\s*=\s*(\d+)\s*;\s*plural\s*=\s*([^;]+)\s*;$/', $header, $matches)) {
return [intval($matches[1]), $matches[2]];
}
}
/**
* Set a new header.
*
* @param string $name
* @param string $value
*
* @return self
*/
public function setHeader($name, $value)
{
$name = trim($name);
$this->headers[$name] = trim($value);
return $this;
}
/**
* Returns a header value.
*
* @param string $name
*
* @return null|string
*/
public function getHeader($name)
{
return isset($this->headers[$name]) ? $this->headers[$name] : null;
}
/**
* Returns all header for this translations (in alphabetic order).
*
* @return array
*/
public function getHeaders()
{
if (static::$options['headersSorting']) {
ksort($this->headers);
}
return $this->headers;
}
/**
* Removes all headers.
*
* @return self
*/
public function deleteHeaders()
{
$this->headers = [];
return $this;
}
/**
* Removes one header.
*
* @param string $name
*
* @return self
*/
public function deleteHeader($name)
{
unset($this->headers[$name]);
return $this;
}
/**
* Returns the language value.
*
* @return string $language
*/
public function getLanguage()
{
return $this->getHeader(self::HEADER_LANGUAGE);
}
/**
* Sets the language and the plural forms.
*
* @param string $language
*
* @throws InvalidArgumentException if the language hasn't been recognized
*
* @return self
*/
public function setLanguage($language)
{
$this->setHeader(self::HEADER_LANGUAGE, trim($language));
if (($info = Language::getById($language))) {
return $this->setPluralForms(count($info->categories), $info->formula);
}
throw new InvalidArgumentException(sprintf('The language "%s" is not valid', $language));
}
/**
* Checks whether the language is empty or not.
*
* @return bool
*/
public function hasLanguage()
{
$language = $this->getLanguage();
return (is_string($language) && ($language !== '')) ? true : false;
}
/**
* Set a new domain for this translations.
*
* @param string $domain
*
* @return self
*/
public function setDomain($domain)
{
$this->setHeader(self::HEADER_DOMAIN, trim($domain));
return $this;
}
/**
* Returns the domain.
*
* @return string
*/
public function getDomain()
{
return $this->getHeader(self::HEADER_DOMAIN);
}
/**
* Checks whether the domain is empty or not.
*
* @return bool
*/
public function hasDomain()
{
$domain = $this->getDomain();
return (is_string($domain) && ($domain !== '')) ? true : false;
}
/**
* Search for a specific translation.
*
* @param string|Translation $context The context of the translation or a translation instance
* @param string $original The original string
*
* @return Translation|false
*/
public function find($context, $original = '')
{
if ($context instanceof Translation) {
$id = $context->getId();
} else {
$id = Translation::generateId($context, $original);
}
return $this->offsetExists($id) ? $this[$id] : false;
}
/**
* Creates and insert/merges a new translation.
*
* @param string $context The translation context
* @param string $original The translation original string
* @param string $plural The translation original plural string
*
* @return Translation The translation created
*/
public function insert($context, $original, $plural = '')
{
return $this->offsetSet(null, new Translation($context, $original, $plural));
}
/**
* Merges this translations with other translations.
*
* @param Translations $translations The translations instance to merge with
* @param int $options
*
* @return self
*/
public function mergeWith(Translations $translations, $options = Merge::DEFAULTS)
{
Merge::mergeHeaders($translations, $this, $options);
Merge::mergeTranslations($translations, $this, $options);
return $this;
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace Gettext;
use Gettext\Generators\PhpArray;
class Translator extends BaseTranslator implements TranslatorInterface
{
private $domain;
private $dictionary = [];
private $plurals = [];
/**
* Loads translation from a Translations instance, a file on an array.
*
* @param Translations|string|array $translations
*
* @return self
*/
public function loadTranslations($translations)
{
if (is_object($translations) && $translations instanceof Translations) {
$translations = PhpArray::generate($translations);
} elseif (is_string($translations) && is_file($translations)) {
$translations = include $translations;
} elseif (!is_array($translations)) {
throw new \InvalidArgumentException('Invalid Translator: only arrays, files or instance of Translations are allowed');
}
$this->addTranslations($translations);
return $this;
}
/**
* Set the default domain.
*
* @param string $domain
*
* @return self
*/
public function defaultDomain($domain)
{
$this->domain = $domain;
return $this;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function gettext($original)
{
return $this->dpgettext($this->domain, null, $original);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function ngettext($original, $plural, $value)
{
return $this->dnpgettext($this->domain, null, $original, $plural, $value);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dngettext($domain, $original, $plural, $value)
{
return $this->dnpgettext($domain, null, $original, $plural, $value);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function npgettext($context, $original, $plural, $value)
{
return $this->dnpgettext($this->domain, $context, $original, $plural, $value);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function pgettext($context, $original)
{
return $this->dpgettext($this->domain, $context, $original);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dgettext($domain, $original)
{
return $this->dpgettext($domain, null, $original);
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dpgettext($domain, $context, $original)
{
$translation = $this->getTranslation($domain, $context, $original);
if (isset($translation[0]) && $translation[0] !== '') {
return $translation[0];
}
return $original;
}
/**
* @see TranslatorInterface
*
* {@inheritdoc}
*/
public function dnpgettext($domain, $context, $original, $plural, $value)
{
$key = $this->getPluralIndex($domain, $value);
$translation = $this->getTranslation($domain, $context, $original);
if (isset($translation[$key]) && $translation[$key] !== '') {
return $translation[$key];
}
return ($key === 0) ? $original : $plural;
}
/**
* Set new translations to the dictionary.
*
* @param array $translations
*/
protected function addTranslations(array $translations)
{
$domain = isset($translations['domain']) ? $translations['domain'] : '';
//Set the first domain loaded as default domain
if ($this->domain === null) {
$this->domain = $domain;
}
if (isset($this->dictionary[$domain])) {
$this->dictionary[$domain] = array_replace_recursive($this->dictionary[$domain], $translations['messages']);
return;
}
if (!empty($translations['plural-forms'])) {
list($count, $code) = array_map('trim', explode(';', $translations['plural-forms'], 2));
// extract just the expression turn 'n' into a php variable '$n'.
// Slap on a return keyword and semicolon at the end.
$this->plurals[$domain] = [
'count' => (int) str_replace('nplurals=', '', $count),
'code' => str_replace('plural=', 'return ', str_replace('n', '$n', $code)).';',
];
}
$this->dictionary[$domain] = $translations['messages'];
}
/**
* Search and returns a translation.
*
* @param string $domain
* @param string $context
* @param string $original
*
* @return string|false
*/
protected function getTranslation($domain, $context, $original)
{
return isset($this->dictionary[$domain][$context][$original]) ? $this->dictionary[$domain][$context][$original] : false;
}
/**
* Executes the plural decision code given the number to decide which
* plural version to take.
*
* @param string $domain
* @param string $n
*
* @return int
*/
protected function getPluralIndex($domain, $n)
{
//Not loaded domain, use a fallback
if (!isset($this->plurals[$domain])) {
return $n == 1 ? 0 : 1;
}
if (!isset($this->plurals[$domain]['function'])) {
$this->plurals[$domain]['function'] = create_function('$n', self::fixTerseIfs($this->plurals[$domain]['code']));
}
if ($this->plurals[$domain]['count'] <= 2) {
return call_user_func($this->plurals[$domain]['function'], $n) ? 1 : 0;
}
return call_user_func($this->plurals[$domain]['function'], $n);
}
/**
* This function will recursively wrap failure states in brackets if they contain a nested terse if.
*
* This because PHP can not handle nested terse if's unless they are wrapped in brackets.
*
* This code probably only works for the gettext plural decision codes.
*
* return ($n==1 ? 0 : $n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2);
* becomes
* return ($n==1 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2));
*
* @param string $code the terse if string
* @param bool $inner If inner is true we wrap it in brackets
*
* @return string A formatted terse If that PHP can work with.
*/
private static function fixTerseIfs($code, $inner = false)
{
/*
* (?P<expression>[^?]+) Capture everything up to ? as 'expression'
* \? ?
* (?P<success>[^:]+) Capture everything up to : as 'success'
* : :
* (?P<failure>[^;]+) Capture everything up to ; as 'failure'
*/
preg_match('/(?P<expression>[^?]+)\?(?P<success>[^:]+):(?P<failure>[^;]+)/', $code, $matches);
// If no match was found then no terse if was present
if (!isset($matches[0])) {
return $code;
}
$expression = $matches['expression'];
$success = $matches['success'];
$failure = $matches['failure'];
// Go look for another terse if in the failure state.
$failure = self::fixTerseIfs($failure, true);
$code = $expression.' ? '.$success.' : '.$failure;
if ($inner) {
return "($code)";
}
// note the semicolon. We need that for executing the code.
return "$code;";
}
}

View File

@@ -0,0 +1,103 @@
<?php
namespace Gettext;
/**
* Interface used by all translators.
*/
interface TranslatorInterface
{
/**
* Register this translator as global, to use with the gettext functions __(), p__(), etc.
* Returns the previous translator if exists.
*
* @return TranslatorInterface|null
*/
public function register();
/**
* Gets a translation using the original string.
*
* @param string $original
*
* @return string
*/
public function gettext($original);
/**
* Gets a translation checking the plural form.
*
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
public function ngettext($original, $plural, $value);
/**
* Gets a translation checking the domain and the plural form.
*
* @param string $domain
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
public function dngettext($domain, $original, $plural, $value);
/**
* Gets a translation checking the context and the plural form.
*
* @param string $context
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
public function npgettext($context, $original, $plural, $value);
/**
* Gets a translation checking the context.
*
* @param string $context
* @param string $original
*
* @return string
*/
public function pgettext($context, $original);
/**
* Gets a translation checking the domain.
*
* @param string $domain
* @param string $original
*
* @return string
*/
public function dgettext($domain, $original);
/**
* Gets a translation checking the domain and context.
*
* @param string $domain
* @param string $context
* @param string $original
*
* @return string
*/
public function dpgettext($domain, $context, $original);
/**
* Gets a translation checking the domain, the context and the plural form.
*
* @param string $domain
* @param string $context
* @param string $original
* @param string $plural
* @param string $value
*/
public function dnpgettext($domain, $context, $original, $plural, $value);
}

View File

@@ -0,0 +1,55 @@
<?php
namespace Gettext\Utils;
use Gettext\Translations;
/**
* Trait used by all generators that exports the translations to plain dictionary (original => singular-translation).
*/
trait DictionaryTrait
{
use HeadersGeneratorTrait;
use HeadersExtractorTrait;
/**
* Returns a plain dictionary with the format [original => translation].
*
* @param Translations $translations
* @param bool $includeHeaders
*
* @return array
*/
private static function toArray(Translations $translations, $includeHeaders)
{
$messages = [];
if ($includeHeaders) {
$messages[''] = self::generateHeaders($translations);
}
foreach ($translations as $translation) {
$messages[$translation->getOriginal()] = $translation->getTranslation();
}
return $messages;
}
/**
* Extract the entries from a dictionary.
*
* @param array $messages
* @param Translations $translations
*/
private static function fromArray(array $messages, Translations $translations)
{
foreach ($messages as $original => $translation) {
if ($original === '') {
self::extractHeaders($translation, $translations);
continue;
}
$translations->insert(null, $original)->setTranslation($translation);
}
}
}

View File

@@ -0,0 +1,110 @@
<?php
namespace Gettext\Utils;
use Exception;
use Gettext\Translations;
abstract class FunctionsScanner
{
/**
* Scan and returns the functions and the arguments.
*
* @return array
*/
abstract public function getFunctions();
/**
* Search for specific functions and create translations.
*
* @param Translations $translations The translations instance where save the values
* @param array $options The extractor options
*/
public function saveGettextFunctions(Translations $translations, array $options)
{
$functions = $options['functions'];
$file = $options['file'];
foreach ($this->getFunctions() as $function) {
list($name, $line, $args) = $function;
if (!isset($functions[$name])) {
continue;
}
$domain = $context = $original = $plural = null;
switch ($functions[$name]) {
case 'gettext':
if (!isset($args[0])) {
continue 2;
}
$original = $args[0];
break;
case 'ngettext':
if (!isset($args[1])) {
continue 2;
}
list($original, $plural) = $args;
break;
case 'pgettext':
if (!isset($args[1])) {
continue 2;
}
list($context, $original) = $args;
break;
case 'dgettext':
if (!isset($args[1])) {
continue 2;
}
list($domain, $original) = $args;
break;
case 'dpgettext':
if (!isset($args[2])) {
continue 2;
}
list($domain, $context, $original) = $args;
break;
case 'npgettext':
if (!isset($args[2])) {
continue 2;
}
list($context, $original, $plural) = $args;
break;
case 'dnpgettext':
if (!isset($args[4])) {
continue 2;
}
list($domain, $context, $original, $plural) = $args;
break;
default:
throw new Exception(sprintf('Not valid function %s', $functions[$name]));
}
if ((string) $original !== '' && ($domain === null || $domain === $translations->getDomain())) {
$translation = $translations->insert($context, $original, $plural);
$translation->addReference($file, $line);
if (isset($function[3])) {
foreach ($function[3] as $extractedComment) {
$translation->addExtractedComment($extractedComment);
}
}
}
}
}
}

View File

@@ -0,0 +1,67 @@
<?php
namespace Gettext\Utils;
use Gettext\Translations;
/**
* Trait to provide the functionality of extracting headers.
*/
trait HeadersExtractorTrait
{
/**
* 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);
}
}
}
/**
* Checks if it is a header definition line. Useful for distguishing between header definitions
* and possible continuations of a header entry.
*
* @param string $line Line to parse
*
* @return bool
*/
private static function isHeaderDefinition($line)
{
return (bool) preg_match('/^[\w-]+:/', $line);
}
/**
* Normalize a string.
*
* @param string $value
*
* @return string
*/
public static function convertString($value)
{
return $value;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Gettext\Utils;
use Gettext\Translations;
/**
* Trait to provide the functionality of extracting headers.
*/
trait HeadersGeneratorTrait
{
/**
* 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;
}
}

View File

@@ -0,0 +1,220 @@
<?php
namespace Gettext\Utils;
class JsFunctionsScanner extends FunctionsScanner
{
protected $code;
protected $status = [];
/**
* Constructor.
*
* @param string $code The php code to scan
*/
public function __construct($code)
{
$this->code = $code;
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
$length = strlen($this->code);
$line = 1;
$buffer = '';
$functions = [];
$bufferFunctions = [];
$char = null;
for ($pos = 0; $pos < $length; ++$pos) {
$prev = $char;
$char = $this->code[$pos];
$next = isset($this->code[$pos]) ? $this->code[$pos] : null;
switch ($char) {
case "\n":
++$line;
if ($this->status('line-comment')) {
$this->upStatus();
}
break;
case '/':
switch ($this->status()) {
case 'simple-quote':
case 'double-quote':
case 'line-comment':
break;
case 'block-comment':
if ($prev === '*') {
$this->upStatus();
}
break;
default:
if ($next === '/') {
$this->downStatus('line-comment');
} elseif ($next === '*') {
$this->downStatus('block-comment');
}
break;
}
break;
case "'":
switch ($this->status()) {
case 'simple-quote':
$this->upStatus();
break;
case 'line-comment':
case 'block-comment':
case 'double-quote':
break;
default:
$this->downStatus('simple-quote');
break;
}
break;
case '"':
switch ($this->status()) {
case 'double-quote':
$this->upStatus();
break;
case 'line-comment':
case 'block-comment':
case 'simple-quote':
break;
default:
$this->downStatus('double-quote');
break;
}
break;
case '(':
switch ($this->status()) {
case 'double-quote':
case 'line-comment':
case 'block-comment':
case 'line-comment':
break;
default:
if ($buffer && preg_match('/(\w+)$/', $buffer, $matches)) {
$this->downStatus('function');
array_unshift($bufferFunctions, [$matches[1], $line, []]);
$buffer = '';
continue 3;
}
break;
}
break;
case ')':
switch ($this->status()) {
case 'function':
if (($argument = self::prepareArgument($buffer))) {
$bufferFunctions[0][2][] = $argument;
}
if (!empty($bufferFunctions)) {
$functions[] = array_shift($bufferFunctions);
}
$buffer = '';
continue 3;
}
case ',':
switch ($this->status()) {
case 'function':
if (($argument = self::prepareArgument($buffer))) {
$bufferFunctions[0][2][] = $argument;
}
$buffer = '';
continue 3;
}
}
switch ($this->status()) {
case 'line-comment':
case 'block-comment':
break;
default:
$buffer .= $char;
break;
}
}
return $functions;
}
/**
* Get the current context of the scan.
*
* @param null|string $match To check whether the current status is this value
*
* @return string|bool
*/
protected function status($match = null)
{
$status = isset($this->status[0]) ? $this->status[0] : null;
if ($match !== null) {
return $status === $match;
}
return $status;
}
/**
* Add a new status to the stack.
*
* @param string $status
*/
protected function downStatus($status)
{
array_unshift($this->status, $status);
}
/**
* Removes and return the current status.
*
* @return string|null
*/
protected function upStatus()
{
return array_shift($this->status);
}
/**
* Prepares the arguments found in functions.
*
* @param string $argument
*
* @return string
*/
protected static function prepareArgument($argument)
{
if ($argument && ($argument[0] === '"' || $argument[0] === "'")) {
if ($argument[0] === '"') {
$argument = str_replace('\\"', '"', $argument);
} else {
$argument = str_replace("\\'", "'", $argument);
}
return substr($argument, 1, -1);
}
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace Gettext\Utils;
use Gettext\Translations;
/**
* Trait used by all generators that exports the translations to multidimensional arrays (context => [original => [translation, plural1, pluraln...]]).
*/
trait MultidimensionalArrayTrait
{
use HeadersGeneratorTrait;
use HeadersExtractorTrait;
/**
* Returns a multidimensional array.
*
* @param Translations $translations
* @param bool $includeHeaders
* @param bool $forceArray
*
* @return array
*/
private static function toArray(Translations $translations, $includeHeaders, $forceArray = false)
{
$pluralForm = $translations->getPluralForms();
$pluralLimit = is_array($pluralForm) ? ($pluralForm[0] - 1) : null;
$messages = [];
if ($includeHeaders) {
$messages[''] = [
'' => [self::generateHeaders($translations)],
];
}
foreach ($translations as $translation) {
$context = $translation->getContext();
$original = $translation->getOriginal();
if (!isset($messages[$context])) {
$messages[$context] = [];
}
if ($translation->hasPluralTranslations(true)) {
$messages[$context][$original] = $translation->getPluralTranslations($pluralLimit);
array_unshift($messages[$context][$original], $translation->getTranslation());
} elseif ($forceArray) {
$messages[$context][$original] = [$translation->getTranslation()];
} else {
$messages[$context][$original] = $translation->getTranslation();
}
}
return [
'domain' => $translations->getDomain(),
'plural-forms' => $translations->getHeader('Plural-Forms'),
'messages' => $messages,
];
}
/**
* Extract the entries from a multidimensional array.
*
* @param array $messages
* @param Translations $translations
*/
private static function fromArray(array $messages, Translations $translations)
{
if (!empty($messages['domain'])) {
$translations->setDomain($messages['domain']);
}
if (!empty($messages['plural-forms'])) {
$translations->setHeader(Translations::HEADER_PLURAL, $messages['plural-forms']);
}
foreach ($messages['messages'] as $context => $contextTranslations) {
foreach ($contextTranslations as $original => $value) {
if ($context === '' && $original === '') {
self::extractHeaders(is_array($value) ? array_shift($value) : $value, $translations);
continue;
}
$translation = $translations->insert($context, $original);
if (is_array($value)) {
$translation->setTranslation(array_shift($value));
$translation->setPluralTranslations($value);
} else {
$translation->setTranslation($value);
}
}
}
}
}

View File

@@ -0,0 +1,148 @@
<?php
namespace Gettext\Utils;
/**
* Function parsed by PhpFunctionsScanner.
*/
class ParsedFunction
{
/**
* The function name.
*
* @var string
*/
protected $name;
/**
* The line where the function starts.
*
* @var int
*/
protected $line;
/**
* The strings extracted from the function arguments.
*
* @var string[]
*/
protected $arguments;
/**
* The current index of the function (-1 if no arguments).
*
* @var int|null
*/
protected $argumentIndex;
/**
* Shall we stop adding string chunks to the current argument?
*
* @var bool
*/
protected $argumentStopped;
/**
* Extracted comments.
*
* @var string[]|null
*/
protected $comments;
/**
* Initializes the instance.
*
* @param string $name The function name.
* @param int $line The line where the function starts.
*/
public function __construct($name, $line)
{
$this->name = $name;
$this->line = $line;
$this->arguments = [];
$this->argumentIndex = -1;
$this->argumentStopped = false;
$this->comments = null;
}
/**
* Stop extracting strings from the current argument (because we found something that's not a string).
*/
public function stopArgument()
{
if ($this->argumentIndex === -1) {
$this->argumentIndex = 0;
}
$this->argumentStopped = true;
}
/**
* Go to the next argument because we a comma was found.
*/
public function nextArgument()
{
if ($this->argumentIndex === -1) {
// This should neve occur, but let's stay safe - During test/development an Exception should be thrown.
$this->argumentIndex = 1;
} else {
++$this->argumentIndex;
}
$this->argumentStopped = false;
}
/**
* Add a string to the current argument.
*
* @param string $chunk
*/
public function addArgumentChunk($chunk)
{
if ($this->argumentStopped === false) {
if ($this->argumentIndex === -1) {
$this->argumentIndex = 0;
}
if (isset($this->arguments[$this->argumentIndex])) {
$this->arguments[$this->argumentIndex] .= $chunk;
} else {
$this->arguments[$this->argumentIndex] = $chunk;
}
}
}
/**
* Add a comment associated to this function.
*
* @param string $comment
*/
public function addComment($comment)
{
if ($this->comments === null) {
$this->comments = [];
}
$this->comments[] = $comment;
}
/**
* A closing parenthesis was found: return the final data.
* The array returned has the following values:
* 0 => string The function name.
* 1 => int The line where the function starts.
* 2 => string[] the strings extracted from the function arguments.
* 3 => string[] the comments associated to the function.
*
* @return array
*/
public function close()
{
$arguments = [];
for ($i = 0; $i <= $this->argumentIndex; ++$i) {
$arguments[$i] = isset($this->arguments[$i]) ? $this->arguments[$i] : '';
}
return [
$this->name,
$this->line,
$arguments,
$this->comments,
];
}
}

View File

@@ -0,0 +1,160 @@
<?php
namespace Gettext\Utils;
use Gettext\Extractors\PhpCode;
class PhpFunctionsScanner extends FunctionsScanner
{
/**
* PHP tokens of the code to be parsed.
*
* @var array
*/
protected $tokens;
/**
* If not false, comments will be extracted.
*
* @var string|false
*/
protected $extractComments = false;
/**
* Enable extracting comments that start with a tag (if $tag is empty all the comments will be extracted).
*
* @param string $tag
*/
public function enableCommentsExtraction($tag = '')
{
$this->extractComments = (string) $tag;
}
/**
* Disable comments extraction.
*/
public function disableCommentsExtraction()
{
$this->extractComments = false;
}
/**
* Constructor.
*
* @param string $code The php code to scan
*/
public function __construct($code)
{
$this->tokens = array_values(
array_filter(
token_get_all($code),
function ($token) {
return !is_array($token) || $token[0] !== T_WHITESPACE;
}
)
);
}
/**
* {@inheritdoc}
*/
public function getFunctions()
{
$count = count($this->tokens);
$bufferFunctions = [];
/* @var ParsedFunction[] $bufferFunctions */
$functions = [];
/* @var ParsedFunction[] $functions */
for ($k = 0; $k < $count; ++$k) {
$value = $this->tokens[$k];
if (is_string($value)) {
if (isset($bufferFunctions[0])) {
switch ($value) {
case ',':
$bufferFunctions[0]->nextArgument();
break;
case ')':
$functions[] = array_shift($bufferFunctions)->close();
break;
case '.':
break;
default:
$bufferFunctions[0]->stopArgument();
break;
}
}
continue;
}
switch ($value[0]) {
case T_CONSTANT_ENCAPSED_STRING:
//add an argument to the current function
if (isset($bufferFunctions[0])) {
$bufferFunctions[0]->addArgumentChunk(PhpCode::convertString($value[1]));
}
break;
case T_STRING:
if (isset($bufferFunctions[0])) {
$bufferFunctions[0]->stopArgument();
}
//new function found
for ($j = $k + 1; $j < $count; ++$j) {
$nextToken = $this->tokens[$j];
if (is_array($nextToken) && $nextToken[0] === T_COMMENT) {
continue;
}
if ($nextToken === '(') {
$newFunction = new ParsedFunction($value[1], $value[2]);
if ($k > 0 && is_array($this->tokens[$k - 1]) && $this->tokens[$k - 1][0] === T_COMMENT) {
$comment = $this->parsePhpComment($this->tokens[$k - 1][1]);
if ($comment !== null) {
$newFunction->addComment($comment);
}
}
array_unshift($bufferFunctions, $newFunction);
$k = $j;
}
break;
}
break;
case T_COMMENT:
if (isset($bufferFunctions[0])) {
$comment = $this->parsePhpComment($value[1]);
if ($comment !== null) {
$bufferFunctions[0]->addComment($comment);
}
}
break;
default:
if (isset($bufferFunctions[0])) {
$bufferFunctions[0]->stopArgument();
}
break;
}
}
return $functions;
}
protected function parsePhpComment($value)
{
$result = null;
if ($this->extractComments !== false) {
if ($value[0] === '#') {
$value = substr($value, 1);
} elseif ($value[1] === '/') {
$value = substr($value, 2);
} else {
$value = substr($value, 2, -2);
}
$value = trim($value);
if ($value !== '' && ($this->extractComments === '' || strpos($value, $this->extractComments) === 0)) {
$result = $value;
}
}
return $result;
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Gettext\Utils;
class StringReader
{
public $pos;
public $str;
public $strlen;
/**
* Constructor.
*
* @param string $str The string to read
*/
public function __construct($str)
{
$this->str = $str;
$this->strlen = strlen($this->str);
}
/**
* Read and returns a part of the string.
*
* @param int $bytes The number of bytes to read
*
* @return string
*/
public function read($bytes)
{
$data = substr($this->str, $this->pos, $bytes);
$this->seekto($this->pos + $bytes);
return $data;
}
/**
* Move the cursor to a specific position.
*
* @param int $pos The amount of bytes to move
*
* @return int The new position
*/
public function seekto($pos)
{
$this->pos = ($this->strlen < $pos) ? $this->strlen : $pos;
return $this->pos;
}
}

View File

@@ -0,0 +1,13 @@
<?php
spl_autoload_register(function ($class) {
if (strpos($class, 'Gettext\\') !== 0) {
return;
}
$file = __DIR__.str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen('Gettext'))).'.php';
if (is_file($file)) {
require_once $file;
}
});

View File

@@ -0,0 +1,156 @@
<?php
use Gettext\BaseTranslator;
/**
* Returns the translation of a string.
*
* @param string $original
*
* @return string
*/
function __($original)
{
$text = BaseTranslator::$current->gettext($original);
if (func_num_args() === 1) {
return $text;
}
$args = array_slice(func_get_args(), 1);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the singular/plural translation of a string.
*
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
function n__($original, $plural, $value)
{
$text = BaseTranslator::$current->ngettext($original, $plural, $value);
if (func_num_args() === 3) {
return $text;
}
$args = array_slice(func_get_args(), 3);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the translation of a string in a specific context.
*
* @param string $context
* @param string $original
*
* @return string
*/
function p__($context, $original)
{
$text = BaseTranslator::$current->pgettext($context, $original);
if (func_num_args() === 2) {
return $text;
}
$args = array_slice(func_get_args(), 2);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the translation of a string in a specific domain.
*
* @param string $domain
* @param string $original
*
* @return string
*/
function d__($domain, $original)
{
$text = BaseTranslator::$current->dgettext($domain, $original);
if (func_num_args() === 2) {
return $text;
}
$args = array_slice(func_get_args(), 2);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the translation of a string in a specific domain and context.
*
* @param string $domain
* @param string $context
* @param string $original
*
* @return string
*/
function dp__($domain, $context, $original)
{
$text = BaseTranslator::$current->dpgettext($domain, $context, $original);
if (func_num_args() === 3) {
return $text;
}
$args = array_slice(func_get_args(), 3);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the singular/plural translation of a string in a specific context.
*
* @param string $context
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
function np__($context, $original, $plural, $value)
{
$text = BaseTranslator::$current->npgettext($context, $original, $plural, $value);
if (func_num_args() === 4) {
return $text;
}
$args = array_slice(func_get_args(), 4);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}
/**
* Returns the singular/plural translation of a string in a specific domain and context.
*
* @param string $domain
* @param string $context
* @param string $original
* @param string $plural
* @param string $value
*
* @return string
*/
function dnp__($domain, $context, $original, $plural, $value)
{
$text = BaseTranslator::$current->dnpgettext($domain, $context, $original, $plural, $value);
if (func_num_args() === 5) {
return $text;
}
$args = array_slice(func_get_args(), 5);
return vsprintf($text, is_array($args[0]) ? $args[0] : $args);
}