Skip to content

Instantly share code, notes, and snippets.

@MattisOlsson
Last active June 10, 2022 12:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattisOlsson/76cdd081d754526ddd07face35aeb2a5 to your computer and use it in GitHub Desktop.
Save MattisOlsson/76cdd081d754526ddd07face35aeb2a5 to your computer and use it in GitHub Desktop.
public class GenericLinkPropertyModel<T> : PropertyModel<T, PropertyLinkData<T>>, IExpandableProperty<T> where T: LinkData, new()
{
private readonly IUrlResolver _urlResolver;
public GenericLinkPropertyModel(PropertyLinkData<T> propertyLinkData, IUrlResolver urlResolver) : base(propertyLinkData)
{
_urlResolver = urlResolver;
Value = GetValue(propertyLinkData?.Link);
ExpandedValue = Value;
}
private T GetValue(T link)
{
if (link == null) return null;
link.Href = _urlResolver.GetUrl(link.GetMappedHref());
return link;
}
public void Expand(CultureInfo language)
{
}
public T ExpandedValue { get; set; }
}
public class GenericLinksConverterProvider : IPropertyConverterProvider
{
private readonly IServiceProvider _serviceProvider;
public GenericLinksConverterProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IPropertyConverter Resolve(PropertyData propertyData)
{
if (!typeof (LinkData).IsAssignableFrom(propertyData.PropertyValueType)
|| !typeof(PropertyLinkData<>).MakeGenericType(propertyData.PropertyValueType).IsAssignableFrom(propertyData.GetOriginalType()))
{
return null;
}
var converter = typeof(PropertyGenericLinkConverter<>).MakeGenericType(propertyData.PropertyValueType);
return ActivatorUtilities.CreateInstance(_serviceProvider, converter) as IPropertyConverter;
}
public int SortOrder => 100;
}
public class PropertyGenericLinkConverter<T> : IPropertyConverter where T: LinkData, new()
{
private readonly IUrlResolver _urlResolver;
public PropertyGenericLinkConverter(IUrlResolver urlResolver)
{
_urlResolver = urlResolver;
}
public IPropertyModel Convert(PropertyData propertyData, ConverterContext contentMappingContext)
{
var propertyModel = new GenericLinkPropertyModel<T>(propertyData as PropertyLinkData<T>, _urlResolver);
return propertyModel;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment