/
Po.php
87 lines (77 loc) · 2.91 KB
/
Po.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace Transvision;
use Gettext\Translations;
/**
* Po class
*
* This class is used to manipulate translation files in Gettext (.po) format.
*
* @package Transvision
*/
class Po
{
/**
*
* Loads strings from a .po file
*
* @param string $po_path Path to the .po to load
* @param string $file_name Name of the file extracted
* @param string $project_name The project this string belongs to
* @param boolean $template If I'm looking at templates
*
* @return array Array of strings as [string_id => translation]
*/
public static function getStrings($po_path, $file_name, $project_name, $template = false)
{
$translations = Translations::fromPoFile($po_path);
$strings = [];
foreach ($translations as $translation_obj) {
$translated_string = $translation_obj->getTranslation();
// Ignore fuzzy strings
if (in_array('fuzzy', $translation_obj->getFlags())) {
continue;
}
// Ignore empty (untranslated) strings
if ($translated_string == '' && ! $template) {
continue;
}
// In templates, use the original string as translation
if ($template) {
$translated_string = $translation_obj->getOriginal();
}
$string_id = self::generateStringID(
$project_name,
$file_name,
$translation_obj->getContext() . '-' . $translation_obj->getOriginal()
);
$translated_string = str_replace("'", "\\'", $translated_string);
$strings[$string_id] = $translated_string;
// Check if there are plurals, in case put them as translation of
// the only English plural form
if ($translation_obj->hasPluralTranslations()) {
$string_id = self::generateStringID(
$project_name,
$file_name,
$translation_obj->getContext() . '-' . $translation_obj->getPlural()
);
$translated_string = implode("\n", $translation_obj->getPluralTranslations());
$translated_string = str_replace("'", "\\'", $translated_string);
$strings[$string_id] = $translated_string;
}
}
return $strings;
}
/**
* Generate a unique ID for a string to store in Transvision.
*
* @param string $project_name The project this string belongs to
* @param string $file_name .po file name
* @param string $string_id String ID (context-original text)
*
* @return string unique ID such as focus_android/app.po:1dafea7725862ca854c408f0e2df9c88
*/
public static function generateStringID($project_name, $file_name, $string_id)
{
return "{$project_name}/{$file_name}:" . hash('md5', $string_id);
}
}