You know the drill, Updates

This commit is contained in:
2023-05-01 19:51:20 -07:00
parent af6f76fbcb
commit 006e3d3314
105 changed files with 1725 additions and 1430 deletions

View File

@ -1,14 +1,15 @@
POMO
====
# POMO
> Gettext library to translate with i18n
[![Latest Release](https://img.shields.io/packagist/v/pomo/pomo.svg)](https://packagist.org/packages/pomo/pomo)
[![Build Status](https://travis-ci.org/LeoColomb/pomo.svg?branch=master)](https://travis-ci.org/LeoColomb/pomo)
[![Code Climate](https://img.shields.io/codeclimate/github/LeoColomb/pomo.svg)](https://codeclimate.com/github/LeoColomb/pomo)
**Gettext library to translate with I18n**.
[Why use it](http://codex.wordpress.org/I18n_for_WordPress_Developers).
## About
[Why use it](https://codex.wordpress.org/I18n_for_WordPress_Developers).
## Usage
Usage
-----
```php
<?php
use POMO\MO;
@ -23,30 +24,28 @@ $translations->import_from_file($the_mo_filepath);
$translations->translate($text);
```
Installation
------------
The easiest way to install POMO is via [composer](http://getcomposer.org/).
Create the following `composer.json` file and run the `php composer.phar install` command to install it.
## Installation
```json
{
"require": {
"pomo/pomo": "*"
}
}
The easiest way to install POMO is via [composer](http://getcomposer.org/).
```console
composer require pomo/pomo
```
```php
<?php
require 'vendor/autoload.php';
use POMO\MO;
...
[...]
```
Requirements
------------
## Requirements
POMO works with PHP 5.3 or above.
License
-------
## License
POMO is licensed under the [GPLv2 License](LICENSE).

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*
@ -18,6 +19,11 @@ use POMO\Translations\GettextTranslations;
*/
class MO extends GettextTranslations
{
/**
* Number of plural forms.
*
* @var int
*/
public $_nplurals = 2;
/**
@ -38,16 +44,16 @@ class MO extends GettextTranslations
}
/**
* Fills up with the entries from MO file $filename.
* Fills up with the entries from MO file $filename
*
* @param string $filename MO file to load
*
* @return bool Success
* @return bool True if the import from file was successful, otherwise false.
*/
public function import_from_file($filename)
{
$reader = new FileReader($filename);
if (!$reader->is_resource()) {
if (! $reader->is_resource()) {
return false;
}
@ -58,18 +64,16 @@ class MO extends GettextTranslations
/**
* @param string $filename
*
* @return bool
*/
public function export_to_file($filename)
{
$fh = fopen($filename, 'wb');
if (!$fh) {
if (! $fh) {
return false;
}
$res = $this->export_to_file_handle($fh);
fclose($fh);
return $res;
}
@ -79,12 +83,11 @@ class MO extends GettextTranslations
public function export()
{
$tmp_fh = fopen('php://temp', 'r+');
if (!$tmp_fh) {
if (! $tmp_fh) {
return false;
}
$this->export_to_file_handle($tmp_fh);
rewind($tmp_fh);
return stream_get_contents($tmp_fh);
}
@ -99,7 +102,7 @@ class MO extends GettextTranslations
return false;
}
if (!array_filter($entry->translations)) {
if (! array_filter($entry->translations)) {
return false;
}
@ -108,69 +111,63 @@ class MO extends GettextTranslations
/**
* @param resource $fh
*
* @return true
*/
public function export_to_file_handle($fh)
{
$entries = array_filter(
$this->entries,
array($this, 'is_entry_good_for_export')
);
$entries = array_filter($this->entries, array($this, 'is_entry_good_for_export'));
ksort($entries);
$magic = 0x950412de;
$revision = 0;
$total = count($entries) + 1; // all the headers are one entry
$originals_lenghts_addr = 28;
$translations_lenghts_addr = $originals_lenghts_addr + 8 * $total;
$size_of_hash = 0;
$hash_addr = $translations_lenghts_addr + 8 * $total;
$current_addr = $hash_addr;
fwrite($fh, pack(
'V*',
$magic,
$revision,
$total,
$originals_lenghts_addr,
$translations_lenghts_addr,
$size_of_hash,
$hash_addr
));
fseek($fh, $originals_lenghts_addr);
$magic = 0x950412de;
$revision = 0;
$total = count($entries) + 1; // All the headers are one entry.
$originals_lengths_addr = 28;
$translations_lengths_addr = $originals_lengths_addr + 8 * $total;
$size_of_hash = 0;
$hash_addr = $translations_lengths_addr + 8 * $total;
$current_addr = $hash_addr;
fwrite(
$fh,
pack(
'V*',
$magic,
$revision,
$total,
$originals_lengths_addr,
$translations_lengths_addr,
$size_of_hash,
$hash_addr
)
);
fseek($fh, $originals_lengths_addr);
// headers' msgid is an empty string
// Headers' msgid is an empty string.
fwrite($fh, pack('VV', 0, $current_addr));
$current_addr++;
$originals_table = chr(0);
$originals_table = "\0";
$reader = new NOOPReader();
foreach ($entries as $entry) {
$originals_table .= $this->export_original($entry).chr(0);
$length = $reader->strlen($this->export_original($entry));
$originals_table .= $this->export_original($entry) . "\0";
$length = $reader->strlen($this->export_original($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1; // account for the NULL byte after
$current_addr += $length + 1; // Account for the NULL byte after.
}
$exported_headers = $this->export_headers();
fwrite($fh, pack(
'VV',
$reader->strlen($exported_headers),
$current_addr
));
$current_addr += strlen($exported_headers) + 1;
$translations_table = $exported_headers.chr(0);
fwrite($fh, pack('VV', $reader->strlen($exported_headers), $current_addr));
$current_addr += strlen($exported_headers) + 1;
$translations_table = $exported_headers . "\0";
foreach ($entries as $entry) {
$translations_table .= $this->export_translations($entry).chr(0);
$length = $reader->strlen($this->export_translations($entry));
$translations_table .= $this->export_translations($entry) . "\0";
$length = $reader->strlen($this->export_translations($entry));
fwrite($fh, pack('VV', $length, $current_addr));
$current_addr += $length + 1;
}
fwrite($fh, $originals_table);
fwrite($fh, $translations_table);
return true;
}
@ -181,15 +178,14 @@ class MO extends GettextTranslations
*/
public function export_original(EntryTranslations $entry)
{
//TODO: warnings for control characters
// TODO: Warnings for control characters.
$exported = $entry->singular;
if ($entry->is_plural) {
$exported .= chr(0).$entry->plural;
$exported .= "\0" . $entry->plural;
}
if (!is_null($entry->context)) {
$exported = $entry->context.chr(4).$exported;
if ($entry->context) {
$exported = $entry->context . "\4" . $exported;
}
return $exported;
}
@ -200,8 +196,8 @@ class MO extends GettextTranslations
*/
public function export_translations(EntryTranslations $entry)
{
//TODO: warnings for control characters
return $entry->is_plural ? implode(chr(0), $entry->translations) : $entry->translations[0];
// TODO: Warnings for control characters.
return $entry->is_plural ? implode("\0", $entry->translations) : $entry->translations[0];
}
/**
@ -213,22 +209,22 @@ class MO extends GettextTranslations
foreach ($this->headers as $header => $value) {
$exported .= "$header: $value\n";
}
return $exported;
}
/**
* @param int $magic
*
* @return string|false
*/
public function get_byteorder($magic)
{
// The magic is 0x950412de
$magic_little = (int) -1794895138;
// The magic is 0x950412de.
// bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565
$magic_little = (int) - 1794895138;
$magic_little_64 = (int) 2500072158;
// 0xde120495
$magic_big = ((int) -569244523) & 0xFFFFFFFF;
$magic_big = ((int) - 569244523) & 0xFFFFFFFF;
if ($magic_little == $magic || $magic_little_64 == $magic) {
return 'little';
} elseif ($magic_big == $magic) {
@ -240,8 +236,7 @@ class MO extends GettextTranslations
/**
* @param FileReader $reader
*
* @return bool
* @return bool True if the import was successful, otherwise false.
*/
public function import_from_reader(FileReader $reader)
{
@ -251,29 +246,29 @@ class MO extends GettextTranslations
}
$reader->setEndian($endian_string);
$endian = ('big' == $endian_string) ? 'N' : 'V';
$endian = ('big' === $endian_string) ? 'N' : 'V';
$header = $reader->read(24);
if ($reader->strlen($header) != 24) {
return false;
}
// parse header
$header = unpack("{$endian}revision/{$endian}total/{$endian}originals_lenghts_addr/{$endian}translations_lenghts_addr/{$endian}hash_length/{$endian}hash_addr", $header);
if (!is_array($header)) {
// Parse header.
$header = unpack("{$endian}revision/{$endian}total/{$endian}originals_lengths_addr/{$endian}translations_lengths_addr/{$endian}hash_length/{$endian}hash_addr", $header);
if (! is_array($header)) {
return false;
}
// support revision 0 of MO format specs, only
if ($header['revision'] != 0) {
// Support revision 0 of MO format specs, only.
if (0 != $header['revision']) {
return false;
}
// seek to data blocks
$reader->seekto($header['originals_lenghts_addr']);
// Seek to data blocks.
$reader->seekto($header['originals_lengths_addr']);
// read originals' indices
$originals_lengths_length = $header['translations_lenghts_addr'] - $header['originals_lenghts_addr'];
// Read originals' indices.
$originals_lengths_length = $header['translations_lengths_addr'] - $header['originals_lengths_addr'];
if ($originals_lengths_length != $header['total'] * 8) {
return false;
}
@ -283,22 +278,22 @@ class MO extends GettextTranslations
return false;
}
// read translations' indices
$translations_lenghts_length = $header['hash_addr'] - $header['translations_lenghts_addr'];
if ($translations_lenghts_length != $header['total'] * 8) {
// Read translations' indices.
$translations_lengths_length = $header['hash_addr'] - $header['translations_lengths_addr'];
if ($translations_lengths_length != $header['total'] * 8) {
return false;
}
$translations = $reader->read($translations_lenghts_length);
if ($reader->strlen($translations) != $translations_lenghts_length) {
$translations = $reader->read($translations_lengths_length);
if ($reader->strlen($translations) != $translations_lengths_length) {
return false;
}
// transform raw data into set of indices
$originals = $reader->str_split($originals, 8);
// Transform raw data into set of indices.
$originals = $reader->str_split($originals, 8);
$translations = $reader->str_split($translations, 8);
// skip hash table
// Skip hash table.
$strings_addr = $header['hash_addr'] + $header['hash_length'] * 4;
$reader->seekto($strings_addr);
@ -307,67 +302,63 @@ class MO extends GettextTranslations
$reader->close();
for ($i = 0; $i < $header['total']; $i++) {
$o = unpack("{$endian}length/{$endian}pos", $originals[$i]);
$t = unpack("{$endian}length/{$endian}pos", $translations[$i]);
if (!$o || !$t) {
$o = unpack("{$endian}length/{$endian}pos", $originals[ $i ]);
$t = unpack("{$endian}length/{$endian}pos", $translations[ $i ]);
if (! $o || ! $t) {
return false;
}
// adjust offset due to reading strings to separate space before
// Adjust offset due to reading strings to separate space before.
$o['pos'] -= $strings_addr;
$t['pos'] -= $strings_addr;
$original = $reader->substr($strings, $o['pos'], $o['length']);
$original = $reader->substr($strings, $o['pos'], $o['length']);
$translation = $reader->substr($strings, $t['pos'], $t['length']);
if ('' === $original) {
$this->set_headers($this->make_headers($translation));
} else {
$entry = &static::make_entry($original, $translation);
$this->entries[$entry->key()] = &$entry;
$entry = &static::make_entry($original, $translation);
$this->entries[ $entry->key() ] = &$entry;
}
}
return true;
}
/**
* Build a from original string and translation strings,
* found in a MO file.
* Build a EntryTranslations from original string and translation strings,
* found in a MO file
*
* @param string $original original string to translate from MO file.
* Might contain 0x04 as context separator or
* 0x00 as singular/plural separator
* @param string $translation translation string from MO file.Might contain
* 0x00 as a plural translations separator
*
* @return EntryTranslations New entry
* @static
* @param string $original original string to translate from MO file. Might contain
* 0x04 as context separator or 0x00 as singular/plural separator
* @param string $translation translation string from MO file. Might contain
* 0x00 as a plural translations separator
* @return EntryTranslations Entry instance.
*/
public static function &make_entry($original, $translation)
{
$entry = new EntryTranslations();
// look for context
$parts = explode(chr(4), $original);
// Look for context, separated by \4.
$parts = explode("\4", $original);
if (isset($parts[1])) {
$original = $parts[1];
$original = $parts[1];
$entry->context = $parts[0];
}
// look for plural original
$parts = explode(chr(0), $original);
// Look for plural original.
$parts = explode("\0", $original);
$entry->singular = $parts[0];
if (isset($parts[1])) {
$entry->is_plural = true;
$entry->plural = $parts[1];
$entry->plural = $parts[1];
}
// plural translations are also separated by \0
$entry->translations = explode(chr(0), $translation);
// Plural translations are also separated by \0.
$entry->translations = explode("\0", $translation);
return $entry;
}
/**
* @param int $count
*
* @return string
*/
public function select_plural_form($count)

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*
@ -23,10 +24,9 @@ class PO extends GettextTranslations
public $comments_before_headers = '';
/**
* Exports headers to a PO entry.
* Exports headers to a PO entry
*
* @return string msgid/msgstr PO entry for this PO file headers, doesn't
* contain newline at the end
* @return string msgid/msgstr PO entry for this PO file headers, doesn't contain newline at the end
*/
public function export_headers()
{
@ -36,40 +36,29 @@ class PO extends GettextTranslations
}
$poified = self::poify($header_string);
if ($this->comments_before_headers) {
$before_headers = self::prepend_each_line(
rtrim($this->comments_before_headers)."\n",
'# '
);
$before_headers = self::prepend_each_line(rtrim($this->comments_before_headers) . "\n", '# ');
} else {
$before_headers = '';
}
return rtrim("{$before_headers}msgid \"\"\nmsgstr $poified");
}
/**
* Exports all entries to PO format.
* Exports all entries to PO format
*
* @return string sequence of mgsgid/msgstr PO strings, doesn't containt
* newline at the end
* @return string sequence of mgsgid/msgstr PO strings, doesn't containt newline at the end
*/
public function export_entries()
{
//TODO: sorting
return implode("\n\n", array_map(
array(__NAMESPACE__.'\PO', 'export_entry'),
$this->entries
));
// TODO: Sorting.
return implode("\n\n", array_map(array(__NAMESPACE__ . '\PO', 'export_entry'), $this->entries));
}
/**
* Exports the whole PO file as a string.
* Exports the whole PO file as a string
*
* @param bool $include_headers whether to include the headers in the
* export
*
* @return string ready for inclusion in PO file string for headers and all
* the enrtries
* @param bool $include_headers whether to include the headers in the export
* @return string ready for inclusion in PO file string for headers and all the enrtries
*/
public function export($include_headers = true)
{
@ -79,17 +68,14 @@ class PO extends GettextTranslations
$res .= "\n\n";
}
$res .= $this->export_entries();
return $res;
}
/**
* Same as {@link export}, but writes the result to a file.
*
* @param string $filename where to write the PO string
* @param bool $include_headers whether to include tje headers in the
* export
* Same as {@link export}, but writes the result to a file
*
* @param string $filename Where to write the PO string.
* @param bool $include_headers Whether to include the headers in the export.
* @return bool true on success, false on error
*/
public function export_to_file($filename, $include_headers = true)
@ -99,7 +85,7 @@ class PO extends GettextTranslations
return false;
}
$export = $this->export($include_headers);
$res = fwrite($fh, $export);
$res = fwrite($fh, $export);
if (false === $res) {
return false;
}
@ -108,12 +94,11 @@ class PO extends GettextTranslations
}
/**
* Text to include as a comment before the start of the PO contents.
* Text to include as a comment before the start of the PO contents
*
* Doesn't need to include # in the beginning of lines, these are added
* automatically
* Doesn't need to include # in the beginning of lines, these are added automatically
*
* @param string $text Comment text
* @param string $text Text to include as a comment.
*/
public function set_comment_before_headers($text)
{
@ -121,120 +106,114 @@ class PO extends GettextTranslations
}
/**
* Formats a string in PO-style.
*
* @param string $string the string to format
* Formats a string in PO-style
*
* @param string $input_string the string to format
* @return string the poified string
*/
public static function poify($string)
public static function poify($input_string)
{
$quote = '"';
$slash = '\\';
$quote = '"';
$slash = '\\';
$newline = "\n";
$replaces = array(
"$slash" => "$slash$slash",
"$quote" => "$slash$quote",
"\t" => '\t',
"$slash" => "$slash$slash",
"$quote" => "$slash$quote",
"\t" => '\t',
);
$string = str_replace(
array_keys($replaces),
array_values($replaces),
$string
);
$input_string = str_replace(array_keys($replaces), array_values($replaces), $input_string);
$po = $quote.implode(
"${slash}n$quote$newline$quote",
explode($newline, $string)
).$quote;
// add empty string on first line for readbility
if (false !== strpos($string, $newline) &&
(substr_count($string, $newline) > 1 ||
!($newline === substr($string, -strlen($newline))))) {
$po = $quote . implode("{$slash}n{$quote}{$newline}{$quote}", explode($newline, $input_string)) . $quote;
// Add empty string on first line for readbility.
if (
false !== strpos($input_string, $newline) &&
(substr_count($input_string, $newline) > 1 || substr($input_string, -strlen($newline)) !== $newline)
) {
$po = "$quote$quote$newline$po";
}
// remove empty strings
// Remove empty strings.
$po = str_replace("$newline$quote$quote", '', $po);
return $po;
}
/**
* Gives back the original string from a PO-formatted string.
*
* @param string $string PO-formatted string
* Gives back the original string from a PO-formatted string
*
* @param string $input_string PO-formatted string
* @return string enascaped string
*/
public static function unpoify($string)
public static function unpoify($input_string)
{
$escapes = array('t' => "\t", 'n' => "\n", 'r' => "\r", '\\' => '\\');
$lines = array_map('trim', explode("\n", $string));
$lines = array_map(array(__NAMESPACE__.'\PO', 'trim_quotes'), $lines);
$unpoified = '';
$escapes = array(
't' => "\t",
'n' => "\n",
'r' => "\r",
'\\' => '\\',
);
$lines = array_map('trim', explode("\n", $input_string));
$lines = array_map(array(__NAMESPACE__ . '\PO', 'trim_quotes'), $lines);
$unpoified = '';
$previous_is_backslash = false;
foreach ($lines as $line) {
preg_match_all('/./u', $line, $chars);
$chars = $chars[0];
foreach ($chars as $char) {
if (!$previous_is_backslash) {
if ('\\' == $char) {
if (! $previous_is_backslash) {
if ('\\' === $char) {
$previous_is_backslash = true;
} else {
$unpoified .= $char;
}
} else {
$previous_is_backslash = false;
$unpoified .= isset($escapes[$char]) ? $escapes[$char] : $char;
$unpoified .= isset($escapes[ $char ]) ? $escapes[ $char ] : $char;
}
}
}
// Standardise the line endings on imported content, technically PO files shouldn't contain \r
// Standardize the line endings on imported content, technically PO files shouldn't contain \r.
$unpoified = str_replace(array("\r\n", "\r"), "\n", $unpoified);
return $unpoified;
}
/**
* Inserts $with in the beginning of every new line of $string and
* returns the modified string.
* Inserts $with in the beginning of every new line of $input_string and
* returns the modified string
*
* @param string $string prepend lines in this string
* @param string $with prepend lines with this string
*
* @return string The modified string
* @param string $input_string prepend lines in this string
* @param string $with prepend lines with this string
*/
public static function prepend_each_line($string, $with)
public static function prepend_each_line($input_string, $with)
{
$lines = explode("\n", $string);
$lines = explode("\n", $input_string);
$append = '';
if ("\n" === substr($string, -1) && '' === end($lines)) {
// Last line might be empty because $string was terminated
// with a newline, remove it from the $lines array,
// we'll restore state by re-terminating the string at the end
if ("\n" === substr($input_string, -1) && '' === end($lines)) {
/*
* Last line might be empty because $input_string was terminated
* with a newline, remove it from the $lines array,
* we'll restore state by re-terminating the string at the end.
*/
array_pop($lines);
$append = "\n";
}
foreach ($lines as &$line) {
$line = $with.$line;
$line = $with . $line;
}
unset($line);
return implode("\n", $lines).$append;
return implode("\n", $lines) . $append;
}
/**
* Prepare a text as a comment -- wraps the lines and prepends #
* and a special character to each line.
* and a special character to each line
*
* @param string $text the comment text
* @param string $char character to denote a special PO comment,
* like :, default is a space
*
* @return string The modified string
* like :, default is a space
*/
private static function comment_block($text, $char = ' ')
{
@ -244,14 +223,11 @@ class PO extends GettextTranslations
}
/**
* Builds a string from the entry for inclusion in PO file.
* Builds a string from the entry for inclusion in PO file
*
* @static
*
* @param EntryTranslations &$entry the entry to convert to po string
*
* @return false|string PO-style formatted string for the entry or
* false if the entry is empty
* @param EntryTranslations $entry the entry to convert to po string.
* @return string|false PO-style formatted string for the entry or
* false if the entry is empty
*/
public static function export_entry(EntryTranslations &$entry)
{
@ -259,67 +235,58 @@ class PO extends GettextTranslations
return false;
}
$po = array();
if (!empty($entry->translator_comments)) {
if (! empty($entry->translator_comments)) {
$po[] = self::comment_block($entry->translator_comments);
}
if (!empty($entry->extracted_comments)) {
if (! empty($entry->extracted_comments)) {
$po[] = self::comment_block($entry->extracted_comments, '.');
}
if (!empty($entry->references)) {
if (! empty($entry->references)) {
$po[] = self::comment_block(implode(' ', $entry->references), ':');
}
if (!empty($entry->flags)) {
if (! empty($entry->flags)) {
$po[] = self::comment_block(implode(', ', $entry->flags), ',');
}
if (!is_null($entry->context)) {
$po[] = 'msgctxt '.self::poify($entry->context);
if ($entry->context) {
$po[] = 'msgctxt ' . self::poify($entry->context);
}
$po[] = 'msgid '.self::poify($entry->singular);
if (!$entry->is_plural) {
$translation = empty($entry->translations) ?
'' :
$entry->translations[0];
$po[] = 'msgid ' . self::poify($entry->singular);
if (! $entry->is_plural) {
$translation = empty($entry->translations) ? '' : $entry->translations[0];
$translation = self::match_begin_and_end_newlines($translation, $entry->singular);
$po[] = 'msgstr '.self::poify($translation);
$po[] = 'msgstr ' . self::poify($translation);
} else {
$po[] = 'msgid_plural '.self::poify($entry->plural);
$translations = empty($entry->translations) ?
array('', '') :
$entry->translations;
$po[] = 'msgid_plural ' . self::poify($entry->plural);
$translations = empty($entry->translations) ? array( '', '' ) : $entry->translations;
foreach ($translations as $i => $translation) {
$translation = self::match_begin_and_end_newlines($translation, $entry->plural);
$po[] = "msgstr[$i] ".self::poify($translation);
$po[] = "msgstr[$i] " . self::poify($translation);
}
}
return implode("\n", $po);
}
/**
* @param $translation
* @param $original
*
* @return string
*/
public static function match_begin_and_end_newlines($translation, $original)
{
if ('' === $translation) {
return $translation;
}
$original_begin = "\n" === substr($original, 0, 1);
$original_end = "\n" === substr($original, -1);
$original_begin = "\n" === substr($original, 0, 1);
$original_end = "\n" === substr($original, -1);
$translation_begin = "\n" === substr($translation, 0, 1);
$translation_end = "\n" === substr($translation, -1);
$translation_end = "\n" === substr($translation, -1);
if ($original_begin) {
if (!$translation_begin) {
$translation = "\n".$translation;
if (! $translation_begin) {
$translation = "\n" . $translation;
}
} elseif ($translation_begin) {
$translation = ltrim($translation, "\n");
}
if ($original_end) {
if (!$translation_end) {
if (! $translation_end) {
$translation .= "\n";
}
} elseif ($translation_end) {
@ -337,20 +304,17 @@ class PO extends GettextTranslations
public function import_from_file($filename)
{
$f = fopen($filename, 'r');
if (!$f) {
if (! $f) {
return false;
}
$lineno = 0;
$res = false;
while (true) {
$res = $this->read_entry($f, $lineno);
if (!$res) {
if (! $res) {
break;
}
if ($res['entry']->singular == '') {
$this->set_headers(
$this->make_headers($res['entry']->translations[0])
);
if ('' === $res['entry']->singular) {
$this->set_headers($this->make_headers($res['entry']->translations[0]));
} else {
$this->add_entry($res['entry']);
}
@ -359,47 +323,44 @@ class PO extends GettextTranslations
if (false === $res) {
return false;
}
if (!$this->headers && !$this->entries) {
if (! $this->headers && ! $this->entries) {
return false;
}
return true;
}
/**
* Helper function for read_entry.
* Helper function for read_entry
*
* @param string $context
*
* @return bool
*/
protected static function is_final($context)
{
return ($context === 'msgstr') || ($context === 'msgstr_plural');
return ('msgstr' === $context) || ('msgstr_plural' === $context);
}
/**
* @param resource $f
* @param int $lineno
*
* @return null|false|array
*/
public function read_entry($f, $lineno = 0)
{
$entry = new EntryTranslations();
// where were we in the last step
// can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural
$context = '';
// Where were we in the last step.
// Can be: comment, msgctxt, msgid, msgid_plural, msgstr, msgstr_plural.
$context = '';
$msgstr_index = 0;
while (true) {
$lineno++;
$line = self::read_line($f);
if (!$line) {
if (! $line) {
if (feof($f)) {
if (self::is_final($context)) {
break;
} elseif (!$context) { // we haven't read a line and eof came
return;
} elseif (! $context) { // We haven't read a line and EOF came.
return null;
} else {
return false;
}
@ -407,23 +368,22 @@ class PO extends GettextTranslations
return false;
}
}
if ($line == "\n") {
if ("\n" === $line) {
continue;
}
$line = trim($line);
if (preg_match('/^#/', $line, $m)) {
// the comment is the start of a new entry
// The comment is the start of a new entry.
if (self::is_final($context)) {
self::read_line($f, 'put-back');
$lineno--;
break;
}
// comments have to be at the beginning
if ($context && $context != 'comment') {
// Comments have to be at the beginning.
if ($context && 'comment' !== $context) {
return false;
}
// add comment
// Add comment.
$this->add_comment_to_entry($entry, $line);
} elseif (preg_match('/^msgctxt\s+(".*")/', $line, $m)) {
if (self::is_final($context)) {
@ -431,10 +391,10 @@ class PO extends GettextTranslations
$lineno--;
break;
}
if ($context && $context != 'comment') {
if ($context && 'comment' !== $context) {
return false;
}
$context = 'msgctxt';
$context = 'msgctxt';
$entry->context .= self::unpoify($m[1]);
} elseif (preg_match('/^msgid\s+(".*")/', $line, $m)) {
if (self::is_final($context)) {
@ -442,32 +402,30 @@ class PO extends GettextTranslations
$lineno--;
break;
}
if ($context &&
$context != 'msgctxt' &&
$context != 'comment') {
if ($context && 'msgctxt' !== $context && 'comment' !== $context) {
return false;
}
$context = 'msgid';
$context = 'msgid';
$entry->singular .= self::unpoify($m[1]);
} elseif (preg_match('/^msgid_plural\s+(".*")/', $line, $m)) {
if ($context != 'msgid') {
if ('msgid' !== $context) {
return false;
}
$context = 'msgid_plural';
$context = 'msgid_plural';
$entry->is_plural = true;
$entry->plural .= self::unpoify($m[1]);
$entry->plural .= self::unpoify($m[1]);
} elseif (preg_match('/^msgstr\s+(".*")/', $line, $m)) {
if ($context != 'msgid') {
if ('msgid' !== $context) {
return false;
}
$context = 'msgstr';
$context = 'msgstr';
$entry->translations = array(self::unpoify($m[1]));
} elseif (preg_match('/^msgstr\[(\d+)\]\s+(".*")/', $line, $m)) {
if ($context != 'msgid_plural' && $context != 'msgstr_plural') {
if ('msgid_plural' !== $context && 'msgstr_plural' !== $context) {
return false;
}
$context = 'msgstr_plural';
$msgstr_index = $m[1];
$context = 'msgstr_plural';
$msgstr_index = $m[1];
$entry->translations[$m[1]] = self::unpoify($m[2]);
} elseif (preg_match('/^".*"$/', $line)) {
$unpoified = self::unpoify($line);
@ -506,36 +464,33 @@ class PO extends GettextTranslations
$entry->translations = array();
}
return array('entry' => $entry, 'lineno' => $lineno);
return array(
'entry' => $entry,
'lineno' => $lineno,
);
}
/**
* @param resource $f
* @param string $action
*
* @return bool
*/
public static function read_line($f, $action = 'read')
{
static $last_line = '';
static $last_line = '';
static $use_last_line = false;
if ('clear' == $action) {
if ('clear' === $action) {
$last_line = '';
return true;
}
if ('put-back' == $action) {
if ('put-back' === $action) {
$use_last_line = true;
return true;
}
$line = $use_last_line ? $last_line : fgets($f);
$line = ("\r\n" == substr($line, -2)) ?
rtrim($line, "\r\n")."\n" :
$line;
$last_line = $line;
$line = $use_last_line ? $last_line : fgets($f);
$line = ("\r\n" === substr($line, -2)) ? rtrim($line, "\r\n") . "\n" : $line;
$last_line = $line;
$use_last_line = false;
return $line;
}
@ -546,42 +501,30 @@ class PO extends GettextTranslations
public function add_comment_to_entry(EntryTranslations &$entry, $po_comment_line)
{
$first_two = substr($po_comment_line, 0, 2);
$comment = trim(substr($po_comment_line, 2));
if ('#:' == $first_two) {
$entry->references = array_merge(
$entry->references,
preg_split('/\s+/', $comment)
);
} elseif ('#.' == $first_two) {
$entry->extracted_comments = trim(
$entry->extracted_comments."\n".$comment
);
} elseif ('#,' == $first_two) {
$entry->flags = array_merge(
$entry->flags,
preg_split('/,\s*/', $comment)
);
$comment = trim(substr($po_comment_line, 2));
if ('#:' === $first_two) {
$entry->references = array_merge($entry->references, preg_split('/\s+/', $comment));
} elseif ('#.' === $first_two) {
$entry->extracted_comments = trim($entry->extracted_comments . "\n" . $comment);
} elseif ('#,' === $first_two) {
$entry->flags = array_merge($entry->flags, preg_split('/,\s*/', $comment));
} else {
$entry->translator_comments = trim(
$entry->translator_comments."\n".$comment
);
$entry->translator_comments = trim($entry->translator_comments . "\n" . $comment);
}
}
/**
* @param string $s
*
* @return string
*/
public static function trim_quotes($s)
{
if (substr($s, 0, 1) == '"') {
if ('"' === substr($s, 0, 1)) {
$s = substr($s, 1);
}
if (substr($s, -1, 1) == '"') {
if ('"' === substr($s, -1, 1)) {
$s = substr($s, 0, -1);
}
return $s;
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/
@ -89,9 +90,9 @@ class PluralForms
* Uses the shunting-yard algorithm to convert the string to Reverse Polish
* Notation tokens.
*
* @param string $str String to parse.
* @throws Exception If there is a syntax or parsing error with the string.
*
* @throws Exception
* @param string $str String to parse.
*/
protected function parse($str)
{
@ -230,6 +231,7 @@ class PluralForms
/**
* Get the plural form for a number.
*
* Caches the value for repeated calls.
*
* @param int $num Number to get plural form for.
@ -248,10 +250,9 @@ class PluralForms
/**
* Execute the plural form function.
*
* @throws Exception If the plural form value cannot be calculated.
*
* @param int $n Variable "n" to substitute.
*
* @throws Exception
*
* @return int PluralForms form value.
*/
public function execute($n)

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/
@ -7,8 +8,6 @@ namespace POMO\Streams;
/**
* Reads the contents of the file in the beginning.
*
* @author Danilo Segan <danilo@kvota.net>
*/
class CachedFileReader extends StringReader implements StreamInterface
{

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/
@ -14,6 +15,13 @@ namespace POMO\Streams;
*/
class FileReader extends Reader implements StreamInterface
{
/**
* File pointer resource.
*
* @var resource|false
*/
public $_f;
/**
* @param string $filename
*/
@ -23,21 +31,31 @@ class FileReader extends Reader implements StreamInterface
$this->_f = fopen($filename, 'rb');
}
/**
* @param int $bytes
* @return string|false Returns read string, otherwise false.
*/
public function read($bytes)
{
return fread($this->_f, $bytes);
}
/**
* @param int $pos
* @return bool
*/
public function seekto($pos)
{
if (-1 == fseek($this->_f, $pos, SEEK_SET)) {
return false;
}
$this->_pos = $pos;
return true;
}
/**
* @return bool
*/
public function is_resource()
{
return is_resource($this->_f);
@ -51,18 +69,19 @@ class FileReader extends Reader implements StreamInterface
return feof($this->_f);
}
/**
* @return bool
*/
public function close()
{
return fclose($this->_f);
}
/**
* @return string
*/
public function read_all()
{
$all = '';
while (!$this->feof()) {
$all .= $this->read(4096);
}
return $all;
return stream_get_contents($this->_f);
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/
@ -12,89 +13,137 @@ namespace POMO\Streams;
* @property int $_pos
* @author Danilo Segan <danilo@kvota.net>
*/
#[AllowDynamicProperties]
abstract class Reader implements StreamInterface
{
public $endian = 'little';
public $_post = '';
public $_pos;
public $is_overloaded;
public function __construct()
{
$this->is_overloaded = ((ini_get('mbstring.func_overload') & 2) != 0) &&
function_exists('mb_substr');
if (
function_exists('mb_substr')
&& ((int) ini_get('mbstring.func_overload') & 2) // phpcs:ignore PHPCompatibility.IniDirectives.RemovedIniDirectives.mbstring_func_overloadDeprecated
) {
$this->is_overloaded = true;
} else {
$this->is_overloaded = false;
}
$this->_pos = 0;
}
public function setEndian($endian)
/**
* Sets the endianness of the file.
*
* @param string $endian Set the endianness of the file. Accepts 'big', or 'little'.
*/
public function setEndian($endian) // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
{
$this->endian = $endian;
}
/**
* Reads a 32bit Integer from the Stream
*
* @return mixed The integer, corresponding to the next 32 bits from
* the stream of false if there are not enough bytes or on error
*/
public function readint32()
{
$bytes = $this->read(4);
if (4 != $this->strlen($bytes)) {
return false;
}
$endian_letter = ('big' == $this->endian) ? 'N' : 'V';
$int = unpack($endian_letter, $bytes);
$endian_letter = ('big' === $this->endian) ? 'N' : 'V';
$int = unpack($endian_letter, $bytes);
return reset($int);
}
/**
* Reads an array of 32-bit Integers from the Stream
*
* @param int $count How many elements should be read
* @return mixed Array of integers or false if there isn't
* enough data or on error
*/
public function readint32array($count)
{
$bytes = $this->read(4 * $count);
if (4 * $count != $this->strlen($bytes)) {
return false;
}
$endian_letter = ('big' == $this->endian) ? 'N' : 'V';
return unpack($endian_letter.$count, $bytes);
$endian_letter = ('big' === $this->endian) ? 'N' : 'V';
return unpack($endian_letter . $count, $bytes);
}
public function substr($string, $start, $length)
/**
* @param string $input_string
* @param int $start
* @param int $length
* @return string
*/
public function substr($input_string, $start, $length)
{
if ($this->is_overloaded) {
return mb_substr($string, $start, $length, 'ascii');
return mb_substr($input_string, $start, $length, 'ascii');
} else {
return substr($string, $start, $length);
return substr($input_string, $start, $length);
}
}
public function strlen($string)
/**
* @param string $input_string
* @return int
*/
public function strlen($input_string)
{
if ($this->is_overloaded) {
return mb_strlen($string, 'ascii');
return mb_strlen($input_string, 'ascii');
} else {
return strlen($string);
return strlen($input_string);
}
}
public function str_split($string, $chunk_size)
/**
* @param string $input_string
* @param int $chunk_size
* @return array
*/
public function str_split($input_string, $chunk_size)
{
if (!function_exists('str_split')) {
$length = $this->strlen($string);
$out = array();
if (! function_exists('str_split')) {
$length = $this->strlen($input_string);
$out = array();
for ($i = 0; $i < $length; $i += $chunk_size) {
$out[] = $this->substr($string, $i, $chunk_size);
$out[] = $this->substr($input_string, $i, $chunk_size);
}
return $out;
} else {
return str_split($string, $chunk_size);
return str_split($input_string, $chunk_size);
}
}
/**
* @return int
*/
public function pos()
{
return $this->_pos;
}
/**
* @return true
*/
public function is_resource()
{
return true;
}
/**
* @return true
*/
public function close()
{
return true;

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*/
@ -10,25 +11,24 @@ interface StreamInterface
/**
* Sets the endianness of the file.
*
* @param $endian string 'big' or 'little'
* @param string $endian Set the endianness of the file. Accepts 'big', or 'little'.
*/
public function setEndian($endian);
/**
* Reads a 32bit Integer from the Stream.
* Reads a 32bit Integer from the Stream
*
* @return mixed The integer, corresponding to the next 32 bits from the
* stream of false if there are not enough bytes or on error
* @return mixed The integer, corresponding to the next 32 bits from
* the stream of false if there are not enough bytes or on error
*/
public function readint32();
/**
* Reads an array of 32-bit Integers from the Stream.
* Reads an array of 32-bit Integers from the Stream
*
* @param int $count How many elements should be read
*
* @return mixed Array of integers or false if there isn't
* enough data or on error
* enough data or on error
*/
public function readint32array($count);

View File

@ -1,16 +1,15 @@
<?php
/**
* This file is part of the POMO package.
*/
namespace POMO\Streams;
/**
* Provides file-like methods for manipulating a string instead
* of a physical file.
*
* @author Danilo Segan <danilo@kvota.net>
*/
/**
* Provides file-like methods for manipulating a string instead
* of a physical file.
*/
class StringReader extends Reader implements StreamInterface
{
public $_str = '';
@ -22,24 +21,30 @@ class StringReader extends Reader implements StreamInterface
$this->_pos = 0;
}
/**
* @param string $bytes
* @return string
*/
public function read($bytes)
{
$data = $this->substr($this->_str, $this->_pos, $bytes);
$data = $this->substr($this->_str, $this->_pos, $bytes);
$this->_pos += $bytes;
if ($this->strlen($this->_str) < $this->_pos) {
$this->_pos = $this->strlen($this->_str);
}
return $data;
}
/**
* @param int $pos
* @return int
*/
public function seekto($pos)
{
$this->_pos = $pos;
if ($this->strlen($this->_str) < $this->_pos) {
$this->_pos = $this->strlen($this->_str);
}
return $this->_pos;
}
@ -51,12 +56,11 @@ class StringReader extends Reader implements StreamInterface
return $this->strlen($this->_str);
}
/**
* @return string
*/
public function read_all()
{
return $this->substr(
$this->_str,
$this->_pos,
$this->strlen($this->_str)
);
return $this->substr($this->_str, $this->_pos, $this->strlen($this->_str));
}
}

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*
@ -9,9 +10,9 @@
namespace POMO\Translations;
/**
* Contains EntryTranslations class
* EntryTranslations class encapsulates a translatable string.
*/
#[AllowDynamicProperties]
class EntryTranslations
{
/**
@ -21,46 +22,54 @@ class EntryTranslations
*/
public $is_plural = false;
public $context = null;
public $singular = null;
public $plural = null;
public $translations = array();
public $context = null;
public $singular = null;
public $plural = null;
public $translations = array();
public $translator_comments = '';
public $extracted_comments = '';
public $references = array();
public $flags = array();
public $extracted_comments = '';
public $references = array();
public $flags = array();
/**
* @param array $args associative array, support following keys:
* - singular (string) -- the string to translate, if omitted and empty entry will be created
* - plural (string) -- the plural form of the string, setting this will set {@link $is_plural} to true
* - translations (array) -- translations of the string and possibly -- its plural forms
* - context (string) -- a string differentiating two equal strings used in different contexts
* - translator_comments (string) -- comments left by translators
* - extracted_comments (string) -- comments left by developers
* - references (array) -- places in the code this strings is used, in relative_to_root_path/file.php:linenum form
* - flags (array) -- flags like php-format
* @param array $args {
* Arguments array, supports the following keys:
*
* @type string $singular The string to translate, if omitted an
* empty entry will be created.
* @type string $plural The plural form of the string, setting
* this will set `$is_plural` to true.
* @type array $translations Translations of the string and possibly
* its plural forms.
* @type string $context A string differentiating two equal strings
* used in different contexts.
* @type string $translator_comments Comments left by translators.
* @type string $extracted_comments Comments left by developers.
* @type array $references Places in the code this string is used, in
* relative_to_root_path/file.php:linenum form.
* @type array $flags Flags like php-format.
* }
*/
public function __construct($args = array())
{
// if no singular -- empty object
if (!isset($args['singular'])) {
// If no singular -- empty object.
if (! isset($args['singular'])) {
return;
}
// get member variable values from args hash
// Get member variable values from args hash.
foreach ($args as $varname => $value) {
$this->$varname = $value;
}
if (isset($args['plural']) && $args['plural']) {
$this->is_plural = true;
}
if (!is_array($this->translations)) {
if (! is_array($this->translations)) {
$this->translations = array();
}
if (!is_array($this->references)) {
if (! is_array($this->references)) {
$this->references = array();
}
if (!is_array($this->flags)) {
if (! is_array($this->flags)) {
$this->flags = array();
}
}
@ -68,18 +77,18 @@ class EntryTranslations
/**
* Generates a unique key for this entry.
*
* @return string|bool the key or false if the entry is empty
* @return string|false The key or false if the entry is null.
*/
public function key()
{
if (null === $this->singular || '' === $this->singular) {
if (null === $this->singular) {
return false;
}
// Prepend context and EOT, like in MO files
$key = !$this->context ? $this->singular : $this->context.chr(4).$this->singular;
// Standardize on \n line endings
$key = str_replace(array("\r\n", "\r"), "\n", $key);
// Prepend context and EOT, like in MO files.
$key = ! $this->context ? $this->singular : $this->context . "\4" . $this->singular;
// Standardize on \n line endings.
$key = str_replace(array( "\r\n", "\r" ), "\n", $key);
return $key;
}
@ -89,7 +98,7 @@ class EntryTranslations
*/
public function merge_with(&$other)
{
$this->flags = array_unique(array_merge($this->flags, $other->flags));
$this->flags = array_unique(array_merge($this->flags, $other->flags));
$this->references = array_unique(array_merge($this->references, $other->references));
if ($this->extracted_comments != $other->extracted_comments) {
$this->extracted_comments .= $other->extracted_comments;

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*
@ -12,12 +13,23 @@ use POMO\Parser\PluralForms;
/**
* Class for a set of entries for translation and their associated headers.
*
* @property mixed $_nplurals
* @property callable $_gettext_select_plural_form
*/
class GettextTranslations extends Translations implements TranslationsInterface
{
/**
* Number of plural forms.
*
* @var int
*/
public $_nplurals;
/**
* Callback to retrieve the plural form.
*
* @var callable
*/
public $_gettext_select_plural_form;
/**
* The gettext implementation of select_plural_form.
*
@ -30,8 +42,10 @@ class GettextTranslations extends Translations implements TranslationsInterface
*/
public function gettext_select_plural_form($count)
{
if (!isset($this->_gettext_select_plural_form)
|| is_null($this->_gettext_select_plural_form)) {
if (
!isset($this->_gettext_select_plural_form)
|| is_null($this->_gettext_select_plural_form)
) {
list($nplurals, $expression) = $this->nplurals_and_expression_from_header($this->get_header('Plural-Forms'));
$this->_nplurals = $nplurals;
$this->_gettext_select_plural_form = $this->make_plural_form_function($nplurals, $expression);
@ -103,7 +117,7 @@ class GettextTranslations extends Translations implements TranslationsInterface
$res .= ') : (';
break;
case ';':
$res .= str_repeat(')', $depth).';';
$res .= str_repeat(')', $depth) . ';';
$depth = 0;
break;
default:

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*
@ -11,6 +12,7 @@ namespace POMO\Translations;
/**
* Class for a set of entries for translation and their associated headers.
*/
#[AllowDynamicProperties]
class Translations implements TranslationsInterface
{
public $entries = array();
@ -114,9 +116,11 @@ class Translations implements TranslationsInterface
$translated = $this->translate_entry($entry);
$index = $this->select_plural_form($count);
$total_plural_forms = $this->get_plural_forms_count();
if ($translated && 0 <= $index && $index < $total_plural_forms &&
if (
$translated && 0 <= $index && $index < $total_plural_forms &&
is_array($translated->translations) &&
isset($translated->translations[$index])) {
isset($translated->translations[$index])
) {
return $translated->translations[$index];
} else {
return 1 == $count ? $singular : $plural;

View File

@ -1,4 +1,5 @@
<?php
/**
* This file is part of the POMO package.
*