2021-03-01 17:05:59 +01:00
|
|
|
// Copyright (c) Umbraco.
|
|
|
|
|
// See LICENSE for more details.
|
|
|
|
|
|
|
|
|
|
using System.Collections.Generic;
|
2022-01-21 12:40:18 +01:00
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
using Newtonsoft.Json.Linq;
|
2021-03-01 17:05:59 +01:00
|
|
|
using Umbraco.Cms.Core.Events;
|
|
|
|
|
using Umbraco.Cms.Core.Models;
|
2021-05-11 14:33:49 +02:00
|
|
|
using Umbraco.Cms.Core.Notifications;
|
2021-03-01 17:05:59 +01:00
|
|
|
using Umbraco.Extensions;
|
|
|
|
|
|
|
|
|
|
namespace Umbraco.Cms.Core.PropertyEditors
|
|
|
|
|
{
|
|
|
|
|
public abstract class ComplexPropertyEditorContentNotificationHandler :
|
2021-03-16 06:55:55 +01:00
|
|
|
INotificationHandler<ContentSavingNotification>,
|
|
|
|
|
INotificationHandler<ContentCopyingNotification>
|
2021-03-01 17:05:59 +01:00
|
|
|
{
|
|
|
|
|
protected abstract string EditorAlias { get; }
|
|
|
|
|
|
|
|
|
|
protected abstract string FormatPropertyValue(string rawJson, bool onlyMissingKeys);
|
|
|
|
|
|
2021-03-16 06:55:55 +01:00
|
|
|
public void Handle(ContentSavingNotification notification)
|
2021-03-01 17:05:59 +01:00
|
|
|
{
|
|
|
|
|
foreach (var entity in notification.SavedEntities)
|
|
|
|
|
{
|
|
|
|
|
var props = entity.GetPropertiesByEditor(EditorAlias);
|
|
|
|
|
UpdatePropertyValues(props, true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-03-16 06:55:55 +01:00
|
|
|
public void Handle(ContentCopyingNotification notification)
|
2021-03-01 17:05:59 +01:00
|
|
|
{
|
|
|
|
|
var props = notification.Copy.GetPropertiesByEditor(EditorAlias);
|
|
|
|
|
UpdatePropertyValues(props, false);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void UpdatePropertyValues(IEnumerable<IProperty> props, bool onlyMissingKeys)
|
|
|
|
|
{
|
|
|
|
|
foreach (var prop in props)
|
|
|
|
|
{
|
|
|
|
|
// A Property may have one or more values due to cultures
|
|
|
|
|
var propVals = prop.Values;
|
|
|
|
|
foreach (var cultureVal in propVals)
|
|
|
|
|
{
|
|
|
|
|
// Remove keys from published value & any nested properties
|
2022-01-21 12:40:18 +01:00
|
|
|
var publishedValue = cultureVal.PublishedValue is JToken jsonPublishedValue ? jsonPublishedValue.ToString(Formatting.None) : cultureVal.PublishedValue?.ToString();
|
2022-02-22 13:35:32 +01:00
|
|
|
var updatedPublishedVal = FormatPropertyValue(publishedValue!, onlyMissingKeys).NullOrWhiteSpaceAsNull();
|
2021-03-01 17:05:59 +01:00
|
|
|
cultureVal.PublishedValue = updatedPublishedVal;
|
|
|
|
|
|
|
|
|
|
// Remove keys from edited/draft value & any nested properties
|
2022-01-21 12:40:18 +01:00
|
|
|
var editedValue = cultureVal.EditedValue is JToken jsonEditedValue ? jsonEditedValue.ToString(Formatting.None) : cultureVal.EditedValue?.ToString();
|
2022-02-22 13:35:32 +01:00
|
|
|
var updatedEditedVal = FormatPropertyValue(editedValue!, onlyMissingKeys).NullOrWhiteSpaceAsNull();
|
2021-03-01 17:05:59 +01:00
|
|
|
cultureVal.EditedValue = updatedEditedVal;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|