Add GetAncestorIds extension method

This commit is contained in:
nikolajlauridsen
2021-10-06 14:30:26 +02:00
parent 9e05bf156f
commit 7b6bf780ce
2 changed files with 24 additions and 14 deletions

View File

@@ -3,15 +3,15 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.Membership;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Serialization;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
@@ -165,7 +165,15 @@ namespace Umbraco.Extensions
return ContentStatus.Unpublished;
}
/// <summary>
/// Gets a collection containing the ids of all ancestors.
/// </summary>
/// <param name="content"><see cref="IContent"/> to retrieve ancestors for</param>
/// <returns>An Enumerable list of integer ids</returns>
public static IEnumerable<int> GetAncestorIds(this IContent content) =>
content.Path.Split(Constants.CharArrays.Comma)
.Where(x => x != Constants.System.RootString && x != content.Id.ToString(CultureInfo.InvariantCulture)).Select(s =>
int.Parse(s, CultureInfo.InvariantCulture));
#endregion

View File

@@ -531,18 +531,20 @@ namespace Umbraco.Cms.Core.Services.Implement
public IEnumerable<IContent> GetAncestors(IContent content)
{
//null check otherwise we get exceptions
if (content.Path.IsNullOrWhiteSpace()) return Enumerable.Empty<IContent>();
var rootId = Cms.Core.Constants.System.RootString;
var ids = content.Path.Split(Constants.CharArrays.Comma)
.Where(x => x != rootId && x != content.Id.ToString(CultureInfo.InvariantCulture)).Select(s =>
int.Parse(s, CultureInfo.InvariantCulture)).ToArray();
if (ids.Any() == false)
return new List<IContent>();
using (var scope = ScopeProvider.CreateScope(autoComplete: true))
if (content.Path.IsNullOrWhiteSpace())
{
scope.ReadLock(Cms.Core.Constants.Locks.ContentTree);
return Enumerable.Empty<IContent>();
}
var ids = content.GetAncestorIds().ToArray();
if (ids.Any() == false)
{
return new List<IContent>();
}
using (IScope scope = ScopeProvider.CreateScope(autoComplete: true))
{
scope.ReadLock(Constants.Locks.ContentTree);
return _documentRepository.GetMany(ids);
}
}