|
| 1 | +<?php |
| 2 | +namespace Transvision; |
| 3 | + |
| 4 | +/** |
| 5 | + * Xliff class |
| 6 | + * |
| 7 | + * This class is used to manipulate translation files in XLIFF format |
| 8 | + * used in Firefox for iOS. |
| 9 | + * |
| 10 | + * @package Transvision |
| 11 | + */ |
| 12 | +class Xliff |
| 13 | +{ |
| 14 | + /** |
| 15 | + * |
| 16 | + * Loads strings from a .xliff file |
| 17 | + * |
| 18 | + * @param string $xliff_path Path to the .xliff to load |
| 19 | + * @param string $project_name The project this string belongs to |
| 20 | + * |
| 21 | + * @return array Array of strings as [string_id => translation] |
| 22 | + */ |
| 23 | + public static function getStrings($xliff_path, $project_name) |
| 24 | + { |
| 25 | + $strings = []; |
| 26 | + if ($xml = simplexml_load_file($xliff_path)) { |
| 27 | + $namespaces = $xml->getDocNamespaces(); |
| 28 | + $xml->registerXPathNamespace('x', $namespaces['']); |
| 29 | + /* Get all trans-units, which include both reference (source) and |
| 30 | + /* translation (target) |
| 31 | + */ |
| 32 | + $trans_units = $xml->xpath('//x:trans-unit'); |
| 33 | + foreach ($trans_units as $trans_unit) { |
| 34 | + /* File's name is 2 levels above in the hierarchy, stored as |
| 35 | + * 'original' attribute of the <file> element. |
| 36 | + */ |
| 37 | + $file_node = $trans_unit->xpath('../..'); |
| 38 | + $file_name = $file_node[0]['original']; |
| 39 | + |
| 40 | + $string_id = self::generateStringID($project_name, $file_name, $trans_unit['id']); |
| 41 | + $translation = str_replace("'", "\\'", $trans_unit->target); |
| 42 | + |
| 43 | + $strings[$string_id] = $translation; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return $strings; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Generate a unique id for a string to store in Transvision. |
| 52 | + * String ID can be identical to the source string in iOS, so it's more |
| 53 | + * reliable to generate a unique ID from it. |
| 54 | + * |
| 55 | + * @param string $project_name The project this string belongs to |
| 56 | + * @param string $file_name 'original' attribute of the <file> element |
| 57 | + * @param string $string_id 'id' attribute of the <trans-unit> element |
| 58 | + * |
| 59 | + * @return string unique ID such as firefox_ios/Client/Intro.strings:1cd1dc4e |
| 60 | + */ |
| 61 | + public static function generateStringID($project_name, $file_name, $string_id) |
| 62 | + { |
| 63 | + return "{$project_name}/{$file_name}:" . hash('crc32', $string_id); |
| 64 | + } |
| 65 | +} |
0 commit comments