Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Конина Анастасия #197

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions ObjectPrinting/IPropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace ObjectPrinting
{
public interface IPropertyPrintingConfig<TOwner, TPropType>
{
PrintingConfig<TOwner> ParentConfig { get; }
}
}
12 changes: 12 additions & 0 deletions ObjectPrinting/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;

namespace ObjectPrinting
{
public static class ObjectExtensions
{
public static string PrintToString<T>(this T obj)
{
return ObjectPrinter.For<T>().PrintToString(obj);
}
}
}
1 change: 1 addition & 0 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
</ItemGroup>
Expand Down
123 changes: 95 additions & 28 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,108 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using ObjectPrinting.Solved;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner>
{
private readonly Type[] finalTypes =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не используется

{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};

private readonly HashSet<Type> excludedTypes = new HashSet<Type>();
private readonly HashSet<MemberInfo> excludedMembers = new HashSet<MemberInfo>();

private readonly Dictionary<Type, Func<object, string>> typePrintingRules =
new Dictionary<Type, Func<object, string>>();

private readonly Dictionary<MemberInfo, Func<object, string>> memberPrintingRules =
new Dictionary<MemberInfo, Func<object, string>>();

private readonly Dictionary<Type, CultureInfo> typeCultures = new Dictionary<Type, CultureInfo>();
private readonly Dictionary<MemberInfo, CultureInfo> memberCultures = new Dictionary<MemberInfo, CultureInfo>();

private readonly Dictionary<MemberInfo, Func<string, string>> memberTrimToLength =
new Dictionary<MemberInfo, Func<string, string>>();

private Func<string, string> globalTrimToLength = x => x;
private MemberInfo currentMember;

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>()
{
return new PropertyPrintingConfig<TOwner, TPropType>(this);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(
Expression<Func<TOwner, TPropType>> memberSelector)
{
currentMember = ((MemberExpression) memberSelector.Body).Member;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а что если пользователь сделает так?

            person.PrintToString(config => config.Printing(x => x.Name + 1).SetMaxLength(1));

            person.PrintToString(
                config => config
                    .Printing(x => x.Name[2])
                    .Using(x => ""));

итд

return new PropertyPrintingConfig<TOwner, TPropType>(this);
}

public PrintingConfig<TOwner> Excluding<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
currentMember = ((MemberExpression) memberSelector.Body).Member;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лишнее

вообще канеш так делать не гуд, эту штука скорее должна вернуть какой то контекст, в котором будут настраивать параметры конкретного поля
хотя исходя из текущей архитектуры класса кажется проблем с этим не будет, но это скорее всего приведет к осложнениям при добавлении новых методов, вообще изменение состояния не оч крутая вещь в "не контрактах", надо постоянно помнить в других методах что надо засетить в поле новое значение, удалить когда нужно, все это приводит к усложнениям

excludedMembers.Add(currentMember);
return this;
}

public PrintingConfig<TOwner> Excluding<TPropType>()
{
excludedTypes.Add(typeof(TPropType));
return this;
}


public void SetPrintingRule<TPropType>(Func<TPropType, string> print)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот эта штука сейчас торчит наружу, не оч хорошо, синтаксис твоей либы позволяет написать вот так, и это ничего не дает

ObjectPrinter.For<Person>().SetPrintingRule<int>(x => "int here")

{
if (currentMember == null)
typePrintingRules[typeof(TPropType)] = x => print((TPropType) x);
else
memberPrintingRules[currentMember] = x => print((TPropType) x);
currentMember = null;
}

public void SetCulture<TPropType>(CultureInfo culture)
{
if (currentMember == null)
typeCultures[typeof(TPropType)] = culture;
else
memberCultures[currentMember] = culture;
currentMember = null;
}

public void SetMaxLength(int maxLen)
{
if (currentMember == null)
globalTrimToLength = x => x.Substring(0, Math.Min(x.Length, maxLen));

else
memberTrimToLength[currentMember] = x => x.Substring(0, Math.Min(x.Length, maxLen));


currentMember = null;
}

public string PrintToString(TOwner obj)
{
return PrintToString(obj, 0);
}

private string PrintToString(object obj, int nestingLevel)
{
//TODO apply configurations
if (obj == null)
return "null" + Environment.NewLine;

var finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;

var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
var type = obj.GetType();
sb.AppendLine(type.Name);
foreach (var propertyInfo in type.GetProperties())
{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
}
return sb.ToString();
var serialization = new Serialization(new SerializationConfig(excludedTypes,
excludedMembers,
typePrintingRules,
memberPrintingRules,
typeCultures,
memberCultures,
memberTrimToLength,
globalTrimToLength));
return serialization.Serialize(obj);
}
}
}
23 changes: 23 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Globalization;

namespace ObjectPrinting
{
public class PropertyPrintingConfig<TOwner, TPropType> : IPropertyPrintingConfig<TOwner, TPropType>
{
private readonly PrintingConfig<TOwner> printingConfig;

public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig)
{
this.printingConfig = printingConfig;
}

public PrintingConfig<TOwner> Using(Func<TPropType, string> print)
{
printingConfig.SetPrintingRule(print);
return printingConfig;
}

PrintingConfig<TOwner> IPropertyPrintingConfig<TOwner, TPropType>.ParentConfig => printingConfig;
}
}
31 changes: 31 additions & 0 deletions ObjectPrinting/PropertyPrintingConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using System;
using System.Globalization;

namespace ObjectPrinting
{
public static class PropertyPrintingConfigExtensions
{
public static string PrintToString<T>(this T obj, Func<PrintingConfig<T>, PrintingConfig<T>> config)
{
return config(ObjectPrinter.For<T>()).PrintToString(obj);
}

public static PrintingConfig<TOwner> SetMaxLength<TOwner>(
this PropertyPrintingConfig<TOwner, string> propConfig, int maxLen)
{
var propertyConfig = ((IPropertyPrintingConfig<TOwner, string>) propConfig).ParentConfig;

propertyConfig.SetMaxLength(maxLen);
return propertyConfig;
}

public static PrintingConfig<TOwner> Using<TOwner, TPropType>(
this PropertyPrintingConfig<TOwner, TPropType> propConfig, CultureInfo culture)
where TPropType : IFormattable
{
var printingConfig = ((IPropertyPrintingConfig<TOwner, TPropType>) propConfig).ParentConfig;
printingConfig.SetCulture<TPropType>(culture);
return printingConfig;
}
}
}
150 changes: 150 additions & 0 deletions ObjectPrinting/Serialization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
using System;
using System.Collections;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ObjectPrinting
{
public class Serialization
{
private readonly SerializationConfig serializationConfig;
public Serialization(SerializationConfig serializationConfig)
{
this.serializationConfig = serializationConfig;
}

public string Serialize(object obj)
{
return PrintToString(obj, 0);
}

private string PrintToString(object obj, int nestingLevel)
{
if (nestingLevel > 100)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот тут не оч хорошо
если вложенность превысить захардкоженно езначение то пользователь никак не поймет что случилось, лучше кинуть понятную ошибку
ну и совсем беспомощным пользователя оставлять на такие случаи тоже не оч, лучше дать ему возможность конфигурировать это значение, можно сделать дефолтный параметр равный 100

return "";

if (obj == null)
return "null";


if (serializationConfig.TypePrintingRules.TryGetValue(obj.GetType(), out var typePrintingRule))
return typePrintingRule(obj).ToString();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tostring лишнее


if (serializationConfig.FinalTypes.Contains(obj.GetType()))
{
if (serializationConfig.TypeCultures.TryGetValue(obj.GetType(), out var cultureInfo))
return ((dynamic) obj).ToString(cultureInfo);
return obj.ToString();
}

return obj switch
{
IDictionary dictionary => SerializeDictionary(dictionary, nestingLevel),
IEnumerable enumerable => SerializeIEnumerable(enumerable, nestingLevel),
_ => SerializeMembers(obj, nestingLevel)
};
}

private string SerializeDictionary(IDictionary dictionary, int nestingLevel)
{
var sb = new StringBuilder();
var identation = new string('\t', nestingLevel + 1);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давай это уже куда нибудь в константу уберем

sb.AppendLine("{");
foreach (var key in dictionary.Keys)
{
sb.Append(identation + "{" + PrintToString(key, nestingLevel + 1) + Environment.NewLine

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем тебе тогда StringBuilder раз ты используешь конкатенирование строк

+ identation + ":" + PrintToString(dictionary[key], nestingLevel + 1) + "},"
+ Environment.NewLine);
}

sb.Append(identation + "}");
return sb.ToString();
}

private string SerializeIEnumerable(IEnumerable obj, int nestingLevel)
{
var identation = new string('\t', nestingLevel + 1);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

очепятка

var stringBuilder = new StringBuilder();
stringBuilder.AppendLine("[");
foreach (var key in obj)
stringBuilder.AppendLine(identation + PrintToString(key, nestingLevel + 1) + ",");

stringBuilder.Append(identation + "]");
var serializedIEnumerable = stringBuilder.ToString();

var lastIndexOf = serializedIEnumerable.LastIndexOf(",", StringComparison.Ordinal);
if (lastIndexOf != -1)
return serializedIEnumerable.Remove(lastIndexOf, 1);
return serializedIEnumerable;
}

private bool IsExcludedMember(MemberInfo memberInfo)
{
if ((memberInfo.MemberType & MemberTypes.Field) != 0)
return serializationConfig.ExcludedTypes.Contains((memberInfo as FieldInfo)?.FieldType) ||
serializationConfig.ExcludedMembers.Contains(memberInfo);

if ((memberInfo.MemberType & MemberTypes.Property) != 0)
return serializationConfig.ExcludedTypes.Contains((memberInfo as PropertyInfo)?.PropertyType) ||
serializationConfig.ExcludedMembers.Contains(memberInfo);

return false;
}


private string SerializeMembers(object obj, int nestingLevel)
{
var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
var type = obj.GetType();
sb.Append(type.Name);
foreach (var memberInfo in type.GetMembers()
.Where(IsFieldOrProperty).Where(x => !IsExcludedMember(x)))
{
var value = GetValue(obj, memberInfo);

if (value != null && value.Equals(obj))
continue;

sb.Append(Environment.NewLine + identation + memberInfo.Name + " = " +
SerializeValue(nestingLevel, memberInfo, value));
}

return sb.ToString();
}

private string SerializeValue(int nestingLevel, MemberInfo memberInfo, object value)
{
var sb = "";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не надо так, и не привыкай, здесь из контекста конечно понятно что видимо должно было быть на этом месте, но это не StringBuilder, а вообще таким сокращениям не место в коде, через полгода когда вернешься к подобным вещам будешь сожалеть что у переменных кривой нейминг


if (serializationConfig.MemberPrintingRules.TryGetValue(memberInfo, out var rule))
sb = rule(value);
else if (serializationConfig.MemberCultures.TryGetValue(memberInfo, out var cultureInfo))
sb = ((dynamic) value).ToString(cultureInfo);
else
sb = (PrintToString(value, nestingLevel + 1));

sb = serializationConfig.GlobalTrimToLength(sb);

if (serializationConfig.MemberTrimToLength.TryGetValue(memberInfo, out var trimRule))
return trimRule(sb);
return sb;
}

private static bool IsFieldOrProperty(MemberInfo memberInfo) =>
memberInfo.MemberType == MemberTypes.Field || memberInfo.MemberType == MemberTypes.Property;


private static object GetValue(object obj, MemberInfo memberInfo)
{
if ((memberInfo.MemberType & MemberTypes.Field) != 0)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

немного странно выглядит что здесь сравниваешь побитово а в методе выше прямое равенство, давай как то однообразно

return (memberInfo as FieldInfo)?.GetValue(obj);

if ((memberInfo.MemberType & MemberTypes.Property) != 0)
return (memberInfo as PropertyInfo)?.GetValue(obj);

return null;
}
}
}
Loading