Files
Umbraco-CMS/src/Umbraco.Web/PublishedContentPropertyExtension.cs

61 lines
2.4 KiB
C#
Raw Normal View History

2013-11-07 17:16:22 +01:00
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
2013-11-07 17:16:22 +01:00
namespace Umbraco.Web
{
/// <summary>
/// Provides extension methods for <c>IPublishedProperty</c>.
/// </summary>
public static class PublishedPropertyExtension
{
#region Value<T>
2013-11-07 17:16:22 +01:00
2018-04-21 09:57:28 +02:00
public static T Value<T>(this IPublishedProperty property, string culture = null, string segment = null)
2013-11-07 17:16:22 +01:00
{
2018-04-21 09:57:28 +02:00
return property.Value(false, default(T), culture, segment);
2013-11-07 17:16:22 +01:00
}
2018-04-21 09:57:28 +02:00
public static T Value<T>(this IPublishedProperty property, T defaultValue, string culture = null, string segment = null)
2013-11-07 17:16:22 +01:00
{
2018-04-21 09:57:28 +02:00
return property.Value(true, defaultValue, culture, segment);
2013-11-07 17:16:22 +01:00
}
2018-04-21 09:57:28 +02:00
internal static T Value<T>(this IPublishedProperty property, bool withDefaultValue, T defaultValue, string culture = null, string segment = null)
2013-11-07 17:16:22 +01:00
{
2018-04-21 09:57:28 +02:00
if (property.HasValue(culture, segment) == false && withDefaultValue) return defaultValue;
2013-11-07 17:16:22 +01:00
// else we use .Value so we give the converter a chance to handle the default value differently
// eg for IEnumerable<T> it may return Enumerable<T>.Empty instead of null
2018-04-21 09:57:28 +02:00
var value = property.GetValue(culture, segment);
2013-11-07 17:16:22 +01:00
// if value is null (strange but why not) it still is OK to call TryConvertTo
// because it's an extension method (hence no NullRef) which will return a
// failed attempt. So, no need to care for value being null here.
// if already the requested type, return
if (value is T) return (T)value;
// if can convert to requested type, return
var convert = value.TryConvertTo<T>();
if (convert.Success) return convert.Result;
// at that point, the code tried with the raw value
// that makes no sense because it sort of is unpredictable,
// you wouldn't know when the converters run or don't run.
// so, it's commented out now.
// try with the raw value
//var source = property.ValueSource;
//if (source is string) source = TextValueConverterHelper.ParseStringValueSource((string)source);
//if (source is T) return (T)source;
//convert = source.TryConvertTo<T>();
//if (convert.Success) return convert.Result;
return defaultValue;
}
#endregion
}
}