PromotionTranslations.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. /** Upgrade invite (type 10) shows only body text; it has no title in any language. */
  23. public const CONTENT_ONLY = [10];
  24. public static function fields(int $type): array
  25. {
  26. return in_array($type, self::CONTENT_ONLY, true) ? ['content'] : self::FIELDS;
  27. }
  28. public static function select(array $activity, string $lang): ?array
  29. {
  30. $text = self::all($activity)[$lang] ?? null;
  31. if ($text && in_array((int)($activity['type'] ?? 0), self::CONTENT_ONLY, true)) {
  32. return trim($text['content']) === '' ? null : ['lang' => $lang, 'content' => $text['content']];
  33. }
  34. if (!$text || trim($text['title']) === '') return null;
  35. return ['lang' => $lang, 'title' => $text['title'],
  36. 'content' => $text['content'] === '' ? null : $text['content']];
  37. }
  38. }