Esempio n. 1
0
        public void ExportClass(Type translatable, Catalog catalog)
        {
            var properties = translatable.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            var obj = Activator.CreateInstance(translatable);

            foreach (var property in properties)
            {
                if (TypeHelper.IsType(property.PropertyType, typeof(IPluralBuilder)))
                {
                    continue;
                }

                // TODO: allow to access private setters of inherited fields
                if (!property.CanRead)
                {
                    throw new InvalidOperationException($"The property {property.Name} in type {translatable.FullName} is not readable!");
                }

                if (!property.CanWrite)
                {
                    throw new InvalidOperationException($"The property {property.Name} in type {translatable.FullName} is not writable!");
                }

                var comment = TypeHelper.GetTranslatorCommentAttributeValue(property);
                var context = EscapeString(TypeHelper.GetContextAttributeValue(property));

                if (property.PropertyType == typeof(string))
                {
                    var escapedMessage = EscapeString(property.GetValue(obj, null).ToString());

                    catalog.AddEntry(escapedMessage, comment, translatable.FullName, context);

                    continue;
                }

                if (property.PropertyType == typeof(string[]))
                {
                    var value = (string[])property.GetValue(obj, null);

                    if (value.Length != 2)
                    {
                        throw new InvalidDataException($"The plural string for {property.Name} must contain two strings: a singular and a plural form. It contained {value.Length} strings.");
                    }

                    var escapedSingular = EscapeString(value[0]);
                    var escapedPlural   = EscapeString(value[1]);

                    catalog.AddPluralEntry(escapedSingular, escapedPlural, comment, translatable.FullName);

                    continue;
                }

                if (property.PropertyType.IsArray && property.PropertyType.GetElementType().Name == typeof(EnumTranslation <>).Name)
                {
                    // translatable enums will be exported by inspecting all enums with the TranslatableAttribute
                    continue;
                }

                throw new InvalidOperationException($"The type {property.PropertyType} in {translatable.FullName}.{property.Name} is not supported in ITranslatables.");
            }
        }