2019-06-24 11:58:36 +02:00
|
|
|
|
using System;
|
|
|
|
|
|
using System.Linq.Expressions;
|
|
|
|
|
|
using System.Reflection;
|
|
|
|
|
|
using Umbraco.Core.Models.PublishedContent;
|
2019-10-29 00:25:03 +11:00
|
|
|
|
using Umbraco.ModelsBuilder.Embedded;
|
2019-06-24 11:58:36 +02:00
|
|
|
|
|
|
|
|
|
|
// same namespace as original Umbraco.Web PublishedElementExtensions
|
|
|
|
|
|
// ReSharper disable once CheckNamespace
|
2020-07-13 13:38:41 +02:00
|
|
|
|
namespace Umbraco.Core
|
2019-06-24 11:58:36 +02:00
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Provides extension methods to models.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static class PublishedElementExtensions
|
|
|
|
|
|
{
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Gets the value of a property.
|
|
|
|
|
|
/// </summary>
|
2020-07-13 13:38:41 +02:00
|
|
|
|
public static TValue ValueFor<TModel, TValue>(this TModel model, IPublishedValueFallback publishedValueFallback, Expression<Func<TModel, TValue>> property, string culture = null, string segment = null, Fallback fallback = default, TValue defaultValue = default)
|
2019-06-24 11:58:36 +02:00
|
|
|
|
where TModel : IPublishedElement
|
|
|
|
|
|
{
|
|
|
|
|
|
var alias = GetAlias(model, property);
|
2020-07-13 13:38:41 +02:00
|
|
|
|
return model.Value<TValue>(publishedValueFallback, alias, culture, segment, fallback, defaultValue);
|
2019-06-24 11:58:36 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2020-01-20 14:09:13 +01:00
|
|
|
|
// fixme that one should be public so ppl can use it
|
2019-06-24 11:58:36 +02:00
|
|
|
|
private static string GetAlias<TModel, TValue>(TModel model, Expression<Func<TModel, TValue>> property)
|
|
|
|
|
|
{
|
|
|
|
|
|
if (property.NodeType != ExpressionType.Lambda)
|
|
|
|
|
|
throw new ArgumentException("Not a proper lambda expression (lambda).", nameof(property));
|
|
|
|
|
|
|
|
|
|
|
|
var lambda = (LambdaExpression) property;
|
|
|
|
|
|
var lambdaBody = lambda.Body;
|
|
|
|
|
|
|
|
|
|
|
|
if (lambdaBody.NodeType != ExpressionType.MemberAccess)
|
|
|
|
|
|
throw new ArgumentException("Not a proper lambda expression (body).", nameof(property));
|
|
|
|
|
|
|
|
|
|
|
|
var memberExpression = (MemberExpression) lambdaBody;
|
|
|
|
|
|
if (memberExpression.Expression.NodeType != ExpressionType.Parameter)
|
|
|
|
|
|
throw new ArgumentException("Not a proper lambda expression (member).", nameof(property));
|
|
|
|
|
|
|
|
|
|
|
|
var member = memberExpression.Member;
|
|
|
|
|
|
|
|
|
|
|
|
var attribute = member.GetCustomAttribute<ImplementPropertyTypeAttribute>();
|
|
|
|
|
|
if (attribute == null)
|
|
|
|
|
|
throw new InvalidOperationException("Property is not marked with ImplementPropertyType attribute.");
|
2020-01-24 09:19:29 +01:00
|
|
|
|
|
2019-06-24 11:58:36 +02:00
|
|
|
|
return attribute.Alias;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|