// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Newtonsoft.Json.Linq; using Squidex.Domain.Apps.Core.Schemas.Validators; namespace Squidex.Domain.Apps.Core.Schemas { public sealed class AssetsField : Field, IReferenceField { private static readonly ImmutableList EmptyIds = ImmutableList.Empty; public AssetsField(long id, string name, Partitioning partitioning) : this(id, name, partitioning, new AssetsFieldProperties()) { } public AssetsField(long id, string name, Partitioning partitioning, AssetsFieldProperties properties) : base(id, name, partitioning, properties) { } protected override IEnumerable CreateValidators() { if (Properties.IsRequired || Properties.MinItems.HasValue || Properties.MaxItems.HasValue) { yield return new CollectionValidator(Properties.IsRequired, Properties.MinItems, Properties.MaxItems); } yield return new AssetsValidator(); } public IEnumerable GetReferencedIds(JToken value) { IEnumerable result = null; try { result = value?.ToObject>(); } catch { result = EmptyIds; } return result ?? EmptyIds; } public JToken RemoveDeletedReferences(JToken value, ISet deletedReferencedIds) { if (value == null || value.Type == JTokenType.Null) { return null; } var oldAssetIds = GetReferencedIds(value).ToArray(); var newAssetIds = oldAssetIds.Where(x => !deletedReferencedIds.Contains(x)).ToList(); return newAssetIds.Count != oldAssetIds.Length ? JToken.FromObject(newAssetIds) : value; } public override object ConvertValue(JToken value) { return value.ToObject>(); } public override T Accept(IFieldVisitor visitor) { return visitor.Visit(this); } } }