Skip to content
This repository has been archived by the owner on Dec 13, 2021. It is now read-only.

XPath Processor #209

Merged
merged 4 commits into from
Feb 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Web;

namespace Our.Umbraco.Ditto
{
/// <summary>
/// A processor that queries the Umbraco content cache using an XPath expression.
/// </summary>
public class UmbracoXPathAttribute : DittoProcessorAttribute
{
/// <summary>
/// A dictionary lookup of XPath variable names, along with corresponding functions.
/// </summary>
protected Dictionary<string, Func<IPublishedContent, string>> Lookup { get; set; }

/// <summary>
/// The XPath expression used to query the Umbraco content cache.
/// </summary>
public string XPath { get; set; }

/// <summary>
/// Initializes a new instance of the <see cref="UmbracoXPathAttribute"/> class.
/// </summary>
public UmbracoXPathAttribute()
{
// This lookup attempts to simplify how Umbraco core handles the XPath syntax parsing
// ref: https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Core/Xml/UmbracoXPathPathSyntaxParser.cs

Lookup = new Dictionary<string, Func<IPublishedContent, string>>()
{
{ "$current", x => string.Format("id({0})", x.Id) },
{ "$parent", x => string.Format("id({0})", x.Parent.Id) },
{ "$site", x => string.Format("id({0})", x.Path.ToDelimitedList().ElementAtOrDefault(1) ?? "-1") },
{ "$root", x => "/root" },
};
}

/// <summary>
/// Initializes a new instance of the <see cref="UmbracoXPathAttribute"/> class.
/// </summary>
/// <param name="xpath">The XPath expression used to query the Umbraco content cache.</param>
public UmbracoXPathAttribute(string xpath)
: this()
{
XPath = xpath;
}

/// <summary>
/// Processes the value.
/// </summary>
/// <returns>
/// Returns the objects that match the XPath expression from the Umbraco content cache.
/// </returns>
public override object ProcessValue()
{
if (string.IsNullOrWhiteSpace(XPath))
return Value;

var content = GetPublishedContent(Value);

if ((content == null || content.Id == 0) && UmbracoContext.Current.PageId.HasValue)
content = UmbracoContext.Current.ContentCache.GetById(UmbracoContext.Current.PageId.Value);

var xparam = Lookup.FirstOrDefault(x => XPath.StartsWith(x.Key));

var xpath = xparam.Key != null
? XPath.Replace(xparam.Key, xparam.Value(content))
: XPath;

return UmbracoContext
.Current
.ContentCache
.GetByXPath(xpath);
}

/// <summary>
/// Attempts to get the current IPublishedContent object from the value.
/// </summary>
/// <param name="value">The processor's input value.</param>
/// <returns>Returns an IPublishedContent object.</returns>
private IPublishedContent GetPublishedContent(object value)
{
if (value is IEnumerable<IPublishedContent>)
return ((IEnumerable<IPublishedContent>)value).FirstOrDefault();

if (value is IPublishedContent)
return (IPublishedContent)value;

return this.Context.Content;
}
}
}
1 change: 1 addition & 0 deletions src/Our.Umbraco.Ditto/Our.Umbraco.Ditto.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
<Compile Include="ComponentModel\ConversionHandlers\DittoConversionHandler.cs" />
<Compile Include="ComponentModel\Processors\DittoProcessorRegistry.cs" />
<Compile Include="ComponentModel\Processors\Contexts\DittoProcessorContext.cs" />
<Compile Include="ComponentModel\Processors\UmbracoXPathAttribute.cs" />
<Compile Include="Ditto.cs" />
<Compile Include="DittoChainContext.cs" />
<Compile Include="Extensions\Internal\AssemblyExtensions.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@
<Compile Include="CacheTests.cs" />
<Compile Include="ProcessorContextTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="XPathProcessorTests.cs" />
<Compile Include="ValueTypesTests.cs" />
<Compile Include="SingularityMappingTests.cs" />
<Compile Include="TypeInferenceTests.cs" />
Expand Down
25 changes: 24 additions & 1 deletion tests/Our.Umbraco.Ditto.Tests/UmbracoPickerProcessorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Umbraco.Core.Models;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Profiling;
using Umbraco.Core.Xml;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Routing;
Expand Down Expand Up @@ -48,6 +49,27 @@ public void Init()
.Setup(x => x.GetById(It.IsAny<UmbracoContext>(), It.IsAny<bool>(), It.IsAny<int>()))
.Returns<UmbracoContext, bool, int>((ctx, preview, id) => new MockPublishedContent { Id = id });

// NOTE: The `GetByXPath` mock method is duplicated from the XPathProcessorTests.
// We need to perform a full review of the mocking objects so that they work across all the unit-tests. [LK:2017-02-10]
mockPublishedContentCache
.Setup(x => x.GetByXPath(It.IsAny<UmbracoContext>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<XPathVariable[]>()))
.Returns<UmbracoContext, bool, string, XPathVariable[]>(
(ctx, preview, xpath, vars) =>
{
switch (xpath)
{
case "/root":
case "id(1111)":
return new MockPublishedContent { Id = 1111 }.AsEnumerableOfOne();

case "id(2222)":
return new MockPublishedContent { Id = 2222 }.AsEnumerableOfOne();

default:
return Enumerable.Empty<IPublishedContent>();
}
});

PublishedCachesResolver.Current =
new PublishedCachesResolver(new PublishedCaches(mockPublishedContentCache.Object, new Mock<IPublishedMediaCache>().Object));
}
Expand All @@ -60,7 +82,8 @@ public void Init()
urlProviders: Enumerable.Empty<IUrlProvider>(),
replaceContext: true);

Resolution.Freeze();
if (!Resolution.IsFrozen)
Resolution.Freeze();

NodeId = 1234;

Expand Down
109 changes: 109 additions & 0 deletions tests/Our.Umbraco.Ditto.Tests/XPathProcessorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using System.Linq;
using System.Web;
using Moq;
using NUnit.Framework;
using Our.Umbraco.Ditto.Tests.Mocks;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.ObjectResolution;
using Umbraco.Core.Profiling;
using Umbraco.Core.Xml;
using Umbraco.Web;
using Umbraco.Web.PublishedCache;
using Umbraco.Web.Routing;
using Umbraco.Web.Security;

namespace Our.Umbraco.Ditto.Tests
{
[TestFixture]
[Category("Processors")]
public class XPathProcessorTests
{
//
// This unit-test is to prove that the XPath processor will parse the variable names
// and return an IEnumerable<IPublishedContent> from the content cache.
//

public class MyModel
{
[UmbracoXPath("$current")]
public IPublishedContent Self { get; set; }

[UmbracoXPath("$parent")]
public IPublishedContent Parent { get; set; }

[UmbracoXPath("$site")]
public IPublishedContent Site { get; set; }

[UmbracoXPath("$root")]
public IPublishedContent Root { get; set; }
}

[TestFixtureSetUp]
public void Init()
{
if (!PublishedCachesResolver.HasCurrent)
{
var mockPublishedContentCache = new Mock<IPublishedContentCache>();

mockPublishedContentCache
.Setup(x => x.GetByXPath(It.IsAny<UmbracoContext>(), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<XPathVariable[]>()))
.Returns<UmbracoContext, bool, string, XPathVariable[]>(
(ctx, preview, xpath, vars) =>
{
switch (xpath)
{
case "/root":
case "id(1111)":
return new MockPublishedContent { Id = 1111 }.AsEnumerableOfOne();

case "id(2222)":
return new MockPublishedContent { Id = 2222 }.AsEnumerableOfOne();

default:
return Enumerable.Empty<IPublishedContent>();
}
});

PublishedCachesResolver.Current =
new PublishedCachesResolver(new PublishedCaches(mockPublishedContentCache.Object, new Mock<IPublishedMediaCache>().Object));
}

UmbracoContext.EnsureContext(
httpContext: Mock.Of<HttpContextBase>(),
applicationContext: new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())),
webSecurity: new Mock<WebSecurity>(null, null).Object,
umbracoSettings: Mock.Of<IUmbracoSettingsSection>(),
urlProviders: Enumerable.Empty<IUrlProvider>(),
replaceContext: true);

if (!Resolution.IsFrozen)
Resolution.Freeze();
}

[Test]
public void XPath_Processes_PublishedContent()
{
var parent = new MockPublishedContent { Id = 1111, Path = "-1,1111" };
var content = new MockPublishedContent { Id = 2222, Path = "-1,1111,2222", Parent = parent };

var model = content.As<MyModel>();

Assert.That(model, Is.Not.Null);

Assert.That(model.Self, Is.Not.Null);
Assert.That(model.Self.Id, Is.EqualTo(content.Id));

Assert.That(model.Parent, Is.Not.Null);
Assert.That(model.Parent.Id, Is.EqualTo(parent.Id));

Assert.That(model.Site, Is.Not.Null);
Assert.That(model.Site.Id, Is.EqualTo(parent.Id));

Assert.That(model.Root, Is.Not.Null);
Assert.That(model.Root.Id, Is.EqualTo(parent.Id));
}
}
}