1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Gettext\Generators; |
4
|
|
|
|
5
|
|
|
use Gettext\Translations; |
6
|
|
|
|
7
|
|
|
class PhpArray extends Generator implements GeneratorInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* {@inheritdoc} |
11
|
|
|
*/ |
12
|
|
|
public static function toString(Translations $translations) |
13
|
|
|
{ |
14
|
|
|
$array = self::toArray($translations); |
15
|
|
|
|
16
|
|
|
return '<?php return '.var_export($array, true).';'; |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Generates an array with the translations. |
21
|
|
|
* |
22
|
|
|
* @param Translations $translations |
23
|
|
|
* |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
|
|
private static function toArray(Translations $translations) |
27
|
|
|
{ |
28
|
|
|
return [ |
29
|
|
|
'domain' => $translations->getDomain() ?: 'messages', |
30
|
|
|
'lang' => $translations->getLanguage() ?: 'en', |
31
|
|
|
'plural-forms' => $translations->getHeader('Plural-Forms') ?: 'nplurals=2; plural=(n != 1);', |
32
|
|
|
'messages' => self::buildMessages($translations) |
33
|
|
|
]; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Generates an array with all translations. |
38
|
|
|
* |
39
|
|
|
* @param Translations $translations |
40
|
|
|
* |
41
|
|
|
* @return array |
42
|
|
|
*/ |
43
|
|
|
private static function buildMessages(Translations $translations) |
44
|
|
|
{ |
45
|
|
|
$pluralForm = $translations->getPluralForms(); |
46
|
|
|
$pluralLimit = is_array($pluralForm) ? ($pluralForm[0] - 1) : null; |
47
|
|
|
$messages = []; |
48
|
|
|
|
49
|
|
|
foreach ($translations as $translation) { |
50
|
|
|
$context = (string) $translation->getContext(); |
51
|
|
|
|
52
|
|
|
if (!isset($messages[$context])) { |
53
|
|
|
$messages[$context] = []; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
View Code Duplication |
if ($translation->hasPluralTranslations()) { |
|
|
|
|
57
|
|
|
$message = $translation->getPluralTranslations($pluralLimit); |
58
|
|
|
array_unshift($message, $translation->getTranslation()); |
59
|
|
|
} else { |
60
|
|
|
$message = [$translation->getTranslation()]; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$messages[$context][$translation->getOriginal()] = $message; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $messages; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.