PromotionTranslations.php 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace App\Support;
  3. /** Text variants share one campaign identity and one set of financial rules. */
  4. final class PromotionTranslations
  5. {
  6. public const LANGUAGES = ['zh', 'en', 'vi'];
  7. public const FIELDS = ['title', 'content'];
  8. public static function all(array $activity): array
  9. {
  10. $stored = $activity['translations'] ?? null;
  11. if (is_string($stored)) $stored = json_decode($stored, true);
  12. if (!is_array($stored) || !$stored) {
  13. $lang = in_array($activity['lang'] ?? '', self::LANGUAGES, true) ? $activity['lang'] : 'zh';
  14. $stored = [$lang => array_intersect_key($activity, array_flip(self::FIELDS))];
  15. }
  16. $result = [];
  17. foreach (self::LANGUAGES as $lang) {
  18. foreach (self::FIELDS as $field) $result[$lang][$field] = (string) ($stored[$lang][$field] ?? '');
  19. }
  20. return $result;
  21. }
  22. public static function select(array $activity, string $lang): ?array
  23. {
  24. $text = self::all($activity)[$lang] ?? null;
  25. if (!$text || trim($text['title']) === '') return null;
  26. return ['lang' => $lang, 'title' => $text['title'],
  27. 'content' => $text['content'] === '' ? null : $text['content']];
  28. }
  29. }