Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 10 additions & 0 deletions ObjectPrinting/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace ObjectPrinting
{
public static class ObjectExtensions
{
public static string ToString<T>(this T obj)
{
return ObjectPrinter.For<T>().ToString(obj);
}
}
}
1 change: 1 addition & 0 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
Expand Down
3 changes: 3 additions & 0 deletions ObjectPrinting/PrintedObject.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
namespace ObjectPrinting;

public record PrintedObject(string Name, object Current, object Parent);
221 changes: 205 additions & 16 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,230 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner>
{
public string PrintToString(TOwner obj)
private readonly HashSet<Type> _excludedTypes;
private readonly HashSet<string> _excludedProperties;

private readonly Dictionary<Type, Func<object, string>> _typeSerializers;
private readonly Dictionary<string, Func<TOwner, string>> _propertySerializers;

private readonly HashSet<PrintedObject> _printedObjects = [];
private readonly Type[] finalTypes =
[
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
];

public Dictionary<Type, Func<object, string>> GetTypeSerializers => _typeSerializers;
public Dictionary<string, Func<TOwner, string>> GetPropertySerializers => _propertySerializers;


public PrintingConfig() : this(null)
{ }

private PrintingConfig(
HashSet<Type>? excludedTypes = null,
HashSet<string>? excludedProperties = null,
Dictionary<Type, Func<object, string>>? typeSerializers = null,
Dictionary<string, Func<TOwner, string>>? propertySerializers = null
)
{
return PrintToString(obj, 0);
_excludedTypes = excludedTypes ?? new HashSet<Type>();
_excludedProperties = excludedProperties ?? new HashSet<string>();
_typeSerializers = typeSerializers ?? new Dictionary<Type, Func<object, string>>();
_propertySerializers = propertySerializers ?? new Dictionary<string, Func<TOwner, string>>();
}

private string PrintToString(object obj, int nestingLevel)
internal PrintingConfig<TOwner> CopyWithChanges(
HashSet<Type>? excludedTypes = null,
HashSet<string>? excludedProperties = null,
Dictionary<Type, Func<object, string>>? typeSerializers = null,
Dictionary<string, Func<TOwner, string>>? propertySerializers = null
) {
return new PrintingConfig<TOwner>(
excludedTypes ?? _excludedTypes,
excludedProperties ?? _excludedProperties,
typeSerializers ?? _typeSerializers,
propertySerializers ?? _propertySerializers
);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>()
{
//TODO apply configurations
if (obj == null)
return "null" + Environment.NewLine;
return new PropertyPrintingConfig<TOwner, TPropType>(
CopyWithChanges(),
null!
);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
return new PropertyPrintingConfig<TOwner, TPropType>(
CopyWithChanges(),
memberSelector
);
}

var finalTypes = new[]
public PrintingConfig<TOwner> Excluding<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
var excludedProperties = new HashSet<string>(_excludedProperties)
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
GetPropertyNameFromSelector(memberSelector)
};
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;

return CopyWithChanges(
excludedProperties: excludedProperties
);
}

public PrintingConfig<TOwner> Excluding<TPropType>()
{
var excludedTypes = new HashSet<Type>(_excludedTypes)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

а зачем мы тут пересоздаем hashset?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Для иммутабельности PrintingConfig

{
typeof(TPropType)
};

return CopyWithChanges(
excludedTypes: excludedTypes
);
}

public string GetPropertyNameFromSelector<TProperty>(
Expression<Func<TOwner, TProperty>> propertySelector)
{
if (propertySelector.Body is MemberExpression memberExpression)
{
if (memberExpression.Member is PropertyInfo propertyInfo)
{
return propertyInfo.Name;
}
}

throw new ArgumentException(
"Expression must be a property selector: x => x.PropertyName",
nameof(propertySelector));
}

public string ToString(TOwner obj, int nestingLevel = 0)
{
return ToString((object)obj!, nestingLevel);
}

private string ToString(object obj, int nestingLevel)
{
if (obj == null!)
return "null" + Environment.NewLine;

var type = obj.GetType();
if (_typeSerializers.TryGetValue(type, out var serializer))
{
return serializer(obj) + Environment.NewLine;
}

if (finalTypes.Contains(type))
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())

var collectionToString = CollectionToString(obj, identation, nestingLevel);
if (collectionToString is not null)
sb.Append(collectionToString);

foreach (var propertyInfo in GetOrderedProperties(obj))
{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
if (IsExcluded(propertyInfo)) {
continue;
}
var propertyForPrint = PropertyToString(obj, nestingLevel, propertyInfo);
if (propertyForPrint is not null)
sb.Append(identation + propertyInfo.Name + " = " + propertyForPrint);
}
return sb.ToString();
}

private IOrderedEnumerable<PropertyInfo> GetOrderedProperties(object obj)
{
return obj.GetType()
.GetProperties()
.Where(p => p.GetIndexParameters().Length == 0)
.OrderBy(x =>
{
var value = x.GetValue(obj);
if (value is null)
return int.MaxValue;
return value.GetType().GetProperties().Length;
});
}

private string? CollectionToString(object obj, string identation, int nestingLevel)
{
if (IsCollection(obj.GetType()))
{
var sb = new StringBuilder();
sb.AppendLine(identation + "{");
foreach (var item in (IEnumerable)obj)
{
var itemToPrint = ToString(item, nestingLevel + 1);
if (itemToPrint is not null)
sb.Append(identation + itemToPrint);
}
sb.AppendLine(identation + "}");
return sb.ToString();
}

return null;
}

private string? PropertyToString(object obj, int nestingLevel, PropertyInfo propertyInfo)
{
if (
_propertySerializers.TryGetValue(propertyInfo.Name, out var propertySerializer)
&& obj.GetType() == typeof(TOwner)
) {
return propertySerializer((TOwner)obj) + Environment.NewLine;
}

var printedObject = new PrintedObject(propertyInfo.Name, propertyInfo.GetValue(obj)!, obj);
if (!_printedObjects.Contains(printedObject))
{
_printedObjects.Add(printedObject);
return ToString(
propertyInfo.GetValue(obj)!,
nestingLevel + 1);
}

return null;
}

private bool IsExcluded(PropertyInfo propertyInfo)
{
return _excludedProperties.Contains(propertyInfo.Name)
|| _excludedTypes.Contains(propertyInfo.PropertyType);
}

private bool IsCollection(Type type)
{
if (type == typeof(string))
return false;

if (typeof(IEnumerable).IsAssignableFrom(type))
return true;

if (type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
return true;

return false;
}
}
}
105 changes: 105 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq.Expressions;

namespace ObjectPrinting
{
public class PropertyPrintingConfig<TOwner, TPropType> : IPropertyPrintingConfig<TOwner, TPropType>
{
private readonly PrintingConfig<TOwner> _printingConfig;
private Expression<Func<TOwner, TPropType>>? _memberSelector;

public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig, Expression<Func<TOwner, TPropType>> memberSelector)
{
_memberSelector = memberSelector;
_printingConfig = printingConfig;
}

public PrintingConfig<TOwner> Using(Func<TPropType, string> print)
{
if (_memberSelector == null)
{
return UsingForType(print);
}
else
{
if (typeof(TPropType) == typeof(string))
return UsingForProperty(print as Func<string, string>);
return UsingForProperty(print);
}
}

private PrintingConfig<TOwner> UsingForType(Func<TPropType, string> print)
{
var serializers = new Dictionary<Type, Func<object, string>>(_printingConfig.GetTypeSerializers);
Func<object, string> serializer = obj => print((TPropType)obj);

if (serializers.ContainsKey(typeof(TPropType)))
{
var oldSerializer = serializers[typeof(TPropType)];
serializers[typeof(TPropType)] = obj => serializer(oldSerializer(obj));
}
else
serializers[typeof(TPropType)] = serializer;
return _printingConfig.CopyWithChanges(typeSerializers: serializers);
}

private PrintingConfig<TOwner> UsingForProperty(Func<TPropType, string> print)
{
if (_memberSelector == null)
return _printingConfig;

var serializers = new Dictionary<string, Func<TOwner, string>>(_printingConfig.GetPropertySerializers);
var propertyName = _printingConfig.GetPropertyNameFromSelector(_memberSelector);
var memberSelector = _memberSelector.Compile();

Func<TOwner, string> ownerSerializer = owner =>
{
TPropType propertyValue = memberSelector(owner);
return print(propertyValue);
};
serializers[propertyName] = ownerSerializer;
return _printingConfig.CopyWithChanges(propertySerializers: serializers);
}

private PrintingConfig<TOwner> UsingForProperty(Func<string, string> print)
{
if (_memberSelector == null)
return _printingConfig;

var serializers = new Dictionary<string, Func<TOwner, string>>(_printingConfig.GetPropertySerializers);
var propertyName = _printingConfig.GetPropertyNameFromSelector(_memberSelector);
if (!serializers.ContainsKey(propertyName))
{
return UsingForProperty(print as Func<TPropType, string>);
}
var oldSerializer = serializers[propertyName];
Func<TOwner, string> ownerSerializer = owner =>
{
return print(oldSerializer(owner));
};
serializers[propertyName] = ownerSerializer;
return _printingConfig.CopyWithChanges(propertySerializers: serializers);
}


public PrintingConfig<TOwner> Using(CultureInfo culture)
{
if (!typeof(TPropType).IsNumericType())
{
throw new InvalidOperationException($"{typeof(TPropType).Name} is not numeric.");
}
var print = (TPropType p) => ((IFormattable)p!).ToString(null, culture);

return Using(print);
}

public PrintingConfig<TOwner> ParentConfig => _printingConfig;
}

public interface IPropertyPrintingConfig<TOwner, TPropType>
{
PrintingConfig<TOwner> ParentConfig { get; }
}
}
Loading