|
| 1 | +<?php |
| 2 | +declare(strict_types = 1); |
| 3 | + |
| 4 | +namespace Gettext\Generator; |
| 5 | + |
| 6 | +use Gettext\Headers; |
| 7 | +use Gettext\Translation; |
| 8 | +use Gettext\Translations; |
| 9 | + |
| 10 | +final class JsonGenerator extends Generator |
| 11 | +{ |
| 12 | + private $jsonOptions = 0; |
| 13 | + |
| 14 | + public function jsonOptions(int $jsonOptions): self |
| 15 | + { |
| 16 | + $this->jsonOptions = $jsonOptions; |
| 17 | + |
| 18 | + return $this; |
| 19 | + } |
| 20 | + |
| 21 | + public function generateString(Translations $translations): string |
| 22 | + { |
| 23 | + $array = $this->generateArray($translations); |
| 24 | + |
| 25 | + return json_encode($array, $this->jsonOptions); |
| 26 | + } |
| 27 | + |
| 28 | + public function generateArray(Translations $translations): array |
| 29 | + { |
| 30 | + $pluralForm = $translations->getHeaders()->getPluralForm(); |
| 31 | + $pluralSize = is_array($pluralForm) ? ($pluralForm[0] - 1) : null; |
| 32 | + $messages = []; |
| 33 | + |
| 34 | + foreach ($translations as $translation) { |
| 35 | + if (!$translation->getTranslation() || $translation->isDisabled()) { |
| 36 | + continue; |
| 37 | + } |
| 38 | + |
| 39 | + $context = $translation->getContext() ?: ''; |
| 40 | + $original = $translation->getOriginal(); |
| 41 | + |
| 42 | + if (!isset($messages[$context])) { |
| 43 | + $messages[$context] = []; |
| 44 | + } |
| 45 | + |
| 46 | + if (self::hasPluralTranslations($translation)) { |
| 47 | + $messages[$context][$original] = $translation->getPluralTranslations($pluralSize); |
| 48 | + array_unshift($messages[$context][$original], $translation->getTranslation()); |
| 49 | + } else { |
| 50 | + $messages[$context][$original] = $translation->getTranslation(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return [ |
| 55 | + 'domain' => $translations->getDomain(), |
| 56 | + 'plural-forms' => $translations->getHeaders()->get(Headers::HEADER_PLURAL), |
| 57 | + 'messages' => $messages, |
| 58 | + ]; |
| 59 | + } |
| 60 | + |
| 61 | + private static function hasPluralTranslations(Translation $translation): bool |
| 62 | + { |
| 63 | + return implode('', $translation->getPluralTranslations()) !== ''; |
| 64 | + } |
| 65 | +} |
0 commit comments