Skip to content

Commit

Permalink
feature: content type service extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
jcdcdev committed Nov 8, 2023
1 parent 0b87b77 commit 90e1c44
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -355,3 +355,4 @@ MigrationBackup/
# Rider
src/.idea
*.sqlite.db*
.idea/
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Services;
using Umbraco.Extensions;

namespace jcdcdev.Umbraco.Core.Extensions;

public static class ContentTypeBaseServiceExtensions
{
public static IEnumerable<EntityContainer> GetAllContainers<T>(this IContentTypeBaseService<T> service) where T : IContentTypeComposition =>
service.GetContainers(Array.Empty<int>());

public static void DeleteAllEmptyContainers<T>(this IContentTypeBaseService<T> service) where T : IContentTypeComposition
{
var contentTypes = service.GetAll();
var lookup = contentTypes.GroupBy(x => x.ParentId).ToLookup(x => x.Key, x => x.Count());
var containers = service.GetAllContainers();

foreach (var container in containers)
{
var hasChildren = lookup.Contains(container.Id);

if (hasChildren)
{
continue;
}

service.DeleteContainer(container.Id);
}
}

public static EntityContainer GetOrCreateFolder<T>(this IContentTypeBaseService<T> service, string folder, int parentId = -1) where T : IContentTypeComposition
{
var container = service
.GetAllContainers()
.FirstOrDefault(x => x.ParentId == parentId && x.Name.InvariantEquals(folder));

if (container == null)
{
container = service.CreateContainer(parentId, new Guid(), folder).Result?.Entity;
}

return container ?? throw new Exception();
}
}

0 comments on commit 90e1c44

Please sign in to comment.