BigW Consortium Gitlab

translation_entry.rb 2.1 KB
Newer Older
1 2
module Gitlab
  module I18n
3
    class TranslationEntry
4 5
      PERCENT_REGEX = /(?:^|[^%])%(?!{\w*}|[a-z%])/.freeze

6 7 8 9 10 11 12
      attr_reader :nplurals, :entry_data

      def initialize(entry_data, nplurals)
        @entry_data = entry_data
        @nplurals = nplurals
      end

13 14 15 16 17 18 19 20
      def msgid
        entry_data[:msgid]
      end

      def plural_id
        entry_data[:msgid_plural]
      end

21
      def has_plural?
22 23 24 25
        plural_id.present?
      end

      def singular_translation
26
        all_translations.first if has_singular_translation?
27 28 29
      end

      def all_translations
30 31
        @all_translations ||= entry_data.fetch_values(*translation_keys)
                                .reject(&:empty?)
32 33 34 35 36 37 38
      end

      def translated?
        all_translations.any?
      end

      def plural_translations
39
        return [] unless has_plural?
40 41
        return [] unless translated?

42 43 44 45 46
        @plural_translations ||= if has_singular_translation?
                                   all_translations.drop(1)
                                 else
                                   all_translations
                                 end
47 48 49 50 51 52
      end

      def flag
        entry_data[:flag]
      end

53 54
      def has_singular_translation?
        nplurals > 1 || !has_plural?
55 56
      end

57 58 59 60 61 62 63 64 65 66 67 68
      def msgid_contains_newlines?
        msgid.is_a?(Array)
      end

      def plural_id_contains_newlines?
        plural_id.is_a?(Array)
      end

      def translations_contain_newlines?
        all_translations.any? { |translation| translation.is_a?(Array) }
      end

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
      def msgid_contains_unescaped_chars?
        contains_unescaped_chars?(msgid)
      end

      def plural_id_contains_unescaped_chars?
        contains_unescaped_chars?(plural_id)
      end

      def translations_contain_unescaped_chars?
        all_translations.any? { |translation| contains_unescaped_chars?(translation) }
      end

      def contains_unescaped_chars?(string)
        string =~ PERCENT_REGEX
      end

85 86 87
      private

      def translation_keys
88
        @translation_keys ||= entry_data.keys.select { |key| key.to_s =~ /\Amsgstr(\[\d+\])?\z/ }
89 90 91 92
      end
    end
  end
end