Skip to content

Instantly share code, notes, and snippets.

@soen
Last active June 26, 2016 14:53
Show Gist options
  • Save soen/ee45076ebda979fdc7316a28fc89b570 to your computer and use it in GitHub Desktop.
Save soen/ee45076ebda979fdc7316a28fc89b570 to your computer and use it in GitHub Desktop.
using System;
using System.Text.RegularExpressions;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Pipelines.ExpandInitialFieldValue;
namespace CustomExpandTokenProcessors.Pipelines
{
public class QueryTokenReplacer : ExpandInitialFieldValueProcessor
{
private const string Token = "$query";
private const string Pattern = @"(\$query\((.*[^\|])\|(\w*)\))";
private const string ItemId = "id";
private const string ItemName = "name";
public override void Process(ExpandInitialFieldValueArgs args)
{
Assert.ArgumentNotNull(args, "args");
if (args.SourceField.Value.Length == 0 || args.Result.Contains(Token) == false)
return;
string fieldValue = args.Result;
var regex = new Regex(Pattern, RegexOptions.IgnoreCase);
Match match = regex.Match(fieldValue);
if (match.Success)
{
string token = match.Groups[1].Value;
string query = match.Groups[2].Value;
string fieldName = match.Groups[3].Value;
if (query.Length <= 0 || fieldName.Length <= 0)
return;
Item resultItem = GetItemFromQuery(query, args.TargetItem);
if (resultItem != null)
ReplaceTokenValue(args, token, fieldName, resultItem);
}
else
Log.Error("Invalid $query() token. Expected format: $query(<query>|<fieldName>)", this);
}
private static void ReplaceTokenValue(ExpandInitialFieldValueArgs args, string token, string fieldName, Item resultItem)
{
Assert.ArgumentNotNull(args, "args");
Assert.IsNotNullOrEmpty(token, "token");
Assert.IsNotNullOrEmpty(fieldName, "fieldName");
Assert.ArgumentNotNull(resultItem, "resultItem");
switch (fieldName.ToLowerInvariant())
{
case ItemId:
args.Result = args.Result.Replace(token, resultItem.ID.ToString());
break;
case ItemName:
args.Result = args.Result.Replace(token, resultItem.Name);
break;
default:
args.Result = string.IsNullOrEmpty(resultItem[fieldName])
? args.Result.Replace(token, string.Empty)
: args.Result.Replace(token, resultItem[fieldName]);
break;
}
}
private Item GetItemFromQuery(string query, Item item)
{
Assert.ArgumentNotNull(item, "item");
Item queryResultItem = null;
try
{
queryResultItem = item.Axes.SelectSingleItem(query);
}
catch
{
Log.Error(string.Format("Failed to execute query [{0}]", query) , this);
}
return queryResultItem;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment