Files
Umbraco-CMS/src/Umbraco.Core/Models/PublishedContent/PublishedContentExtensionsForModels.cs

40 lines
1.5 KiB
C#
Raw Normal View History

2014-07-24 11:59:37 +02:00
using System;
2017-05-30 15:46:25 +02:00
using Umbraco.Core.Composing;
2014-07-24 11:59:37 +02:00
namespace Umbraco.Core.Models.PublishedContent
2014-05-18 21:23:09 +02:00
{
/// <summary>
/// Provides strongly typed published content models services.
/// </summary>
internal static class PublishedContentExtensionsForModels
{
/// <summary>
/// Creates a strongly typed published content model for an internal published content.
/// </summary>
/// <param name="content">The internal published content.</param>
/// <returns>The strongly typed published content model.</returns>
public static IPublishedContent CreateModel(this IPublishedContent content)
{
2014-07-24 11:59:37 +02:00
if (content == null)
return null;
// in order to provide a nice, "fluent" experience, this extension method
// needs to access Current, which is not always initialized in tests - not
// very elegant, but works
if (!Current.HasContainer) return content;
2014-07-24 11:59:37 +02:00
// get model
// if factory returns nothing, throw
2017-09-26 14:57:50 +02:00
var model = Current.PublishedModelFactory.CreateModel(content);
2014-07-24 11:59:37 +02:00
if (model == null)
throw new Exception("Factory returned null.");
2014-07-24 11:59:37 +02:00
// if factory returns a different type, throw
2017-09-26 14:57:50 +02:00
if (!(model is IPublishedContent publishedContent))
throw new Exception($"Factory returned model of type {model.GetType().FullName} which does not implement IPublishedContent.");
return publishedContent;
2014-05-18 21:23:09 +02:00
}
}
}