| | | 1 | | using System.Collections; |
| | | 2 | | using System.ComponentModel; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Expressions.Helpers; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Provides a set of static methods for formatting objects. |
| | | 9 | | /// </summary> |
| | | 10 | | public static class ObjectFormatter |
| | | 11 | | { |
| | | 12 | | /// <summary> |
| | | 13 | | /// Formats the specified value as a string. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <param name="value">The value.</param> |
| | | 16 | | /// <returns>A string representation of the value.</returns> |
| | | 17 | | public static string? Format(this object? value) |
| | | 18 | | { |
| | 187 | 19 | | if (value == null) |
| | 98 | 20 | | return null; |
| | | 21 | | |
| | 89 | 22 | | if (value is string s) |
| | 3 | 23 | | return s; |
| | | 24 | | |
| | 86 | 25 | | var sourceType = value.GetType(); |
| | 86 | 26 | | var underlyingSourceType = Nullable.GetUnderlyingType(sourceType) ?? sourceType; |
| | | 27 | | |
| | 86 | 28 | | if (underlyingSourceType == typeof(string)) |
| | 0 | 29 | | return value as string; |
| | | 30 | | |
| | | 31 | | // Byte arrays are base64-encoded for serialization |
| | 86 | 32 | | if (value is byte[] byteArray) |
| | 0 | 33 | | return Convert.ToBase64String(byteArray); |
| | | 34 | | |
| | | 35 | | // Memory-like types are preserved via TypeDescriptor |
| | 86 | 36 | | if (IsMemoryLike(sourceType)) |
| | | 37 | | { |
| | 0 | 38 | | var sourceTypeConverter = TypeDescriptor.GetConverter(underlyingSourceType); |
| | 0 | 39 | | if (sourceTypeConverter.CanConvertTo(typeof(string))) |
| | 0 | 40 | | return (string?)sourceTypeConverter.ConvertTo(value, typeof(string)); |
| | | 41 | | |
| | 0 | 42 | | return value.ToString(); |
| | | 43 | | } |
| | | 44 | | |
| | | 45 | | // Serialize arrays and collections to JSON instead of "T[] Array" or "(Collection)". |
| | | 46 | | // Fixes GitHub issue #7019. |
| | 86 | 47 | | if (value is IEnumerable) |
| | | 48 | | { |
| | 8 | 49 | | return JsonSerializer.Serialize(value); |
| | | 50 | | } |
| | | 51 | | |
| | 78 | 52 | | var converter = TypeDescriptor.GetConverter(underlyingSourceType); |
| | | 53 | | |
| | 78 | 54 | | if (converter.CanConvertTo(typeof(string))) |
| | 78 | 55 | | return (string?)converter.ConvertTo(value, typeof(string)); |
| | | 56 | | |
| | 0 | 57 | | return value.ToString(); |
| | | 58 | | } |
| | | 59 | | |
| | | 60 | | private static bool IsMemoryLike(Type type) |
| | | 61 | | { |
| | 86 | 62 | | if (!type.IsGenericType) |
| | 86 | 63 | | return false; |
| | | 64 | | |
| | 0 | 65 | | var genericTypeDef = type.GetGenericTypeDefinition(); |
| | 0 | 66 | | return genericTypeDef == typeof(Memory<>) || genericTypeDef == typeof(ReadOnlyMemory<>); |
| | | 67 | | } |
| | | 68 | | } |