From 9e458305176b68091204b4d8ac7fe26f04a65bf7 Mon Sep 17 00:00:00 2001 From: Damien Date: Tue, 27 Aug 2024 19:36:42 +0200 Subject: [PATCH] Suppression de IFieldProperty (et donc alias de compositions) --- TopModel.Core/EndpointExtensions.cs | 2 +- TopModel.Core/Model/AliasProperty.cs | 13 +- TopModel.Core/Model/AssociationProperty.cs | 10 +- TopModel.Core/Model/Class.cs | 18 +-- TopModel.Core/Model/ClassMappings.cs | 2 +- TopModel.Core/Model/ClassValue.cs | 2 +- TopModel.Core/Model/CompositionProperty.cs | 10 +- TopModel.Core/Model/DataFlow.cs | 10 +- TopModel.Core/Model/DataFlowSource.cs | 4 +- TopModel.Core/Model/IFieldProperty.cs | 22 --- TopModel.Core/Model/IProperty.cs | 22 ++- TopModel.Core/Model/MappingExtensions.cs | 2 +- TopModel.Core/Model/RegularProperty.cs | 6 +- TopModel.Core/ModelExtensions.cs | 125 +++++++-------- TopModel.Core/Resolvers/ClassResolver.cs | 24 +-- TopModel.Core/Resolvers/DataFlowResolver.cs | 4 +- TopModel.Core/Resolvers/EndpointResolver.cs | 4 +- TopModel.Core/Resolvers/MapperResolver.cs | 68 +++++--- TopModel.Core/Resolvers/PropertyResolver.cs | 5 +- TopModel.Core/TranslationStore.cs | 2 +- TopModel.Generator.Core/GeneratorBase.cs | 2 +- .../GeneratorConfigBase.cs | 51 +++--- TopModel.Generator.Core/TemplateExtensions.cs | 150 ++++++------------ .../TranslationGeneratorBase.cs | 18 +-- .../CSharpApiClientGenerator.cs | 7 +- .../CSharpApiServerGenerator.cs | 4 +- .../CSharpClassGenerator.cs | 67 ++++---- TopModel.Generator.Csharp/CsharpConfig.cs | 8 +- .../DbContextGenerator.cs | 10 +- TopModel.Generator.Csharp/MapperGenerator.cs | 39 +++-- .../AngularApiClientGenerator.cs | 2 +- .../JavascriptApiClientGenerator.cs | 4 +- .../JavascriptConfig.cs | 8 +- .../JavascriptResourceGenerator.cs | 12 +- .../NuxtApiClientGenerator.cs | 2 +- .../TypescriptDefinitionGenerator.cs | 28 ++-- .../TypescriptReferenceGenerator.cs | 2 +- .../ImportsJpaExtensions.cs | 49 +++--- TopModel.Generator.Jpa/JpaConfig.cs | 6 +- TopModel.Generator.Jpa/JpaEnumGenerator.cs | 8 +- TopModel.Generator.Jpa/JpaMapperGenerator.cs | 10 +- .../JpaModelConstructorGenerator.cs | 3 +- .../JpaModelPropertyGenerator.cs | 21 ++- .../JpaResourceGenerator.cs | 6 +- .../SpringClientApiGenerator.cs | 12 +- .../SpringDataFlowGenerator.cs | 2 +- .../SpringRestTemplateApiGenerator.cs | 5 +- .../SpringServerApiGenerator.cs | 12 +- TopModel.Generator.Php/PhpConfig.cs | 2 +- TopModel.Generator.Php/PhpModelGenerator.cs | 3 +- .../PhpModelPropertyGenerator.cs | 10 +- .../Procedural/AbstractSchemaGenerator.cs | 14 +- TopModel.Generator.Sql/SqlConfig.cs | 4 +- .../Scripter/InitReferenceListScripter.cs | 2 +- .../Ssdt/Scripter/SqlTableScripter.cs | 4 +- .../Ssdt/Scripter/SqlTableTypeScripter.cs | 4 +- .../TranslationOutGenerator.cs | 6 +- TopModel.LanguageServer/CompletionHandler.cs | 21 +-- TopModel.UI/Graphing/Label.cs | 2 +- .../src/appgenerated/resources/securite.json | 3 + .../generators/focus/src/locale/securite.ts | 3 + .../resources/i18n/model/securite.properties | 1 + .../src/Model/Securite/Profil/ProfilRead.php | 2 +- .../i18n/de_DE/out/securite_de_DE.properties | 1 + .../i18n/en_US/out/securite_en_US.properties | 1 + 65 files changed, 468 insertions(+), 518 deletions(-) delete mode 100644 TopModel.Core/Model/IFieldProperty.cs diff --git a/TopModel.Core/EndpointExtensions.cs b/TopModel.Core/EndpointExtensions.cs index 5e92cce2..65e55616 100644 --- a/TopModel.Core/EndpointExtensions.cs +++ b/TopModel.Core/EndpointExtensions.cs @@ -11,7 +11,7 @@ public static class EndpointExtensions return null; } - var bodyParams = endpoint.Params.Where(param => param is CompositionProperty || param is IFieldProperty { Domain.BodyParam: true }); + var bodyParams = endpoint.Params.Where(param => param is CompositionProperty or { Domain.BodyParam: true }); return bodyParams.Count() > 1 ? throw new ModelException(endpoint, $"L'endpoint '{endpoint.Name}' doit avoir une seule propriété dans le body. Propriétés trouvées : {string.Join(", ", bodyParams)}") : bodyParams.SingleOrDefault(); diff --git a/TopModel.Core/Model/AliasProperty.cs b/TopModel.Core/Model/AliasProperty.cs index 1b997cb3..02f1ea4b 100644 --- a/TopModel.Core/Model/AliasProperty.cs +++ b/TopModel.Core/Model/AliasProperty.cs @@ -3,7 +3,7 @@ namespace TopModel.Core; -public class AliasProperty : IFieldProperty +public class AliasProperty : IProperty { private string? _comment; private string? _defaultValue; @@ -13,11 +13,11 @@ public class AliasProperty : IFieldProperty private string? _name; #nullable disable - private IFieldProperty _property; + private IProperty _property; private bool? _readonly; private bool? _required; - public IFieldProperty Property + public IProperty Property { get { @@ -133,9 +133,9 @@ public string? DefaultValue public string? As { get; set; } - public IFieldProperty? OriginalProperty => _property; + public IProperty? OriginalProperty => _property; - public IFieldProperty? PersistentProperty => (Class?.IsPersistent ?? false) + public IProperty? PersistentProperty => (Class?.IsPersistent ?? false) ? this : OriginalProperty is AliasProperty op ? op.PersistentProperty @@ -165,6 +165,7 @@ public string? DefaultValue internal AliasProperty? OriginalAliasProperty { get; private set; } + /// public IProperty CloneWithClassOrEndpoint(Class? classe = null, Endpoint? endpoint = null) { var alp = new AliasProperty @@ -211,7 +212,7 @@ public override string ToString() return Name; } - internal AliasProperty Clone(IFieldProperty prop, Reference? includeReference) + internal AliasProperty Clone(IProperty prop, Reference? includeReference) { var alp = new AliasProperty { diff --git a/TopModel.Core/Model/AssociationProperty.cs b/TopModel.Core/Model/AssociationProperty.cs index 4c3679c4..f82bba87 100644 --- a/TopModel.Core/Model/AssociationProperty.cs +++ b/TopModel.Core/Model/AssociationProperty.cs @@ -4,16 +4,16 @@ namespace TopModel.Core; -public class AssociationProperty : IFieldProperty +public class AssociationProperty : IProperty { - private IFieldProperty? _property; + private IProperty? _property; public LocatedString? Trigram { get; set; } #nullable disable public Class Association { get; set; } - public IFieldProperty Property + public IProperty Property { get { @@ -152,7 +152,7 @@ public string NameCamel public Domain Domain => Type.IsToMany() && (Property?.Domain?.AsDomains.TryGetValue(As, out var ld) ?? false) ? ld : Property?.Domain!; - public string[] DomainParameters => Property?.DomainParameters ?? Array.Empty(); + public string[] DomainParameters => Property?.DomainParameters ?? []; public bool PrimaryKey { get; set; } @@ -165,7 +165,9 @@ public string NameCamel internal Reference Location { get; set; } #nullable enable +#pragma warning disable KTA1600 + /// public IProperty CloneWithClassOrEndpoint(Class? classe = null, Endpoint? endpoint = null) { return new AssociationProperty diff --git a/TopModel.Core/Model/Class.cs b/TopModel.Core/Model/Class.cs index 9fa1b7d4..de4923f5 100644 --- a/TopModel.Core/Model/Class.cs +++ b/TopModel.Core/Model/Class.cs @@ -35,13 +35,13 @@ public class Class : IPropertyContainer public bool Abstract { get; set; } - public IFieldProperty? OrderProperty { get; set; } + public IProperty? OrderProperty { get; set; } - public IFieldProperty? DefaultProperty { get; set; } + public IProperty? DefaultProperty { get; set; } - public IFieldProperty? FlagProperty { get; set; } + public IProperty? FlagProperty { get; set; } - public IList Properties { get; } = new List(); + public IList Properties { get; } = []; public IList ExtendedProperties => Extends != null ? Properties.Concat(Extends.ExtendedProperties).ToList() : Properties; @@ -49,20 +49,20 @@ public class Class : IPropertyContainer public Namespace Namespace { get; set; } - public IEnumerable PrimaryKey => Properties.OfType().Where(p => p.PrimaryKey); + public IEnumerable PrimaryKey => Properties.Where(p => p.PrimaryKey); - public IFieldProperty? ReferenceKey => + public IProperty? ReferenceKey => PrimaryKey.Count() <= 1 - ? PrimaryKey.SingleOrDefault() ?? Extends?.PrimaryKey.SingleOrDefault() ?? Properties.OfType().FirstOrDefault() + ? PrimaryKey.SingleOrDefault() ?? Extends?.PrimaryKey.SingleOrDefault() ?? Properties.FirstOrDefault() : null; - public IFieldProperty? EnumKey => Enum ? ReferenceKey : null; + public IProperty? EnumKey => Enum ? ReferenceKey : null; public bool Enum { get; set; } public List Values { get; } = []; - public List> UniqueKeys { get; } = []; + public List> UniqueKeys { get; } = []; public List FromMappers { get; } = []; diff --git a/TopModel.Core/Model/ClassMappings.cs b/TopModel.Core/Model/ClassMappings.cs index 148dabaa..716dab6a 100644 --- a/TopModel.Core/Model/ClassMappings.cs +++ b/TopModel.Core/Model/ClassMappings.cs @@ -25,7 +25,7 @@ public class ClassMappings public IEnumerable MissingRequiredProperties => Class.Properties .Where(p => p.Required - && (p is not IFieldProperty fp || fp.DefaultValue == null) + && (p is CompositionProperty or AliasProperty { Property: CompositionProperty } || p.DefaultValue == null) && !(p.Class.IsPersistent && p.PrimaryKey && p.Class.PrimaryKey.Count() == 1 && p.Domain.AutoGeneratedValue)) .Except(Mappings.Select(m => m.Value)); } diff --git a/TopModel.Core/Model/ClassValue.cs b/TopModel.Core/Model/ClassValue.cs index de258ca4..bdfbd257 100644 --- a/TopModel.Core/Model/ClassValue.cs +++ b/TopModel.Core/Model/ClassValue.cs @@ -11,7 +11,7 @@ public class ClassValue public Reference Reference { get; set; } - public Dictionary Value { get; } = new(); + public Dictionary Value { get; } = new(); public string ResourceKey => $"{Class.Namespace.ModuleCamel}.{Class.NameCamel}.values.{Name}"; diff --git a/TopModel.Core/Model/CompositionProperty.cs b/TopModel.Core/Model/CompositionProperty.cs index 51ce58b1..4d8d2bff 100644 --- a/TopModel.Core/Model/CompositionProperty.cs +++ b/TopModel.Core/Model/CompositionProperty.cs @@ -20,7 +20,7 @@ public class CompositionProperty : IProperty public Domain Domain { get; set; } - public string[] DomainParameters { get; set; } = Array.Empty(); + public string[] DomainParameters { get; set; } = []; public string Comment { get; set; } @@ -36,7 +36,7 @@ public class CompositionProperty : IProperty public string Label => Name; - public bool IsMultipart => Composition.Properties.Any(cpp => cpp is IFieldProperty fp && fp.Domain.IsMultipart); + public bool IsMultipart => Composition.Properties.Any(cpp => cpp.Domain?.IsMultipart ?? false); public bool PrimaryKey => false; @@ -44,13 +44,15 @@ public class CompositionProperty : IProperty #nullable enable + public string DefaultValue => throw new NotImplementedException(); + public LocatedString? Trigram { get; set; } - public IFieldProperty? CompositionPrimaryKey + public IProperty? CompositionPrimaryKey { get { - var cpPks = Composition.ExtendedProperties.OfType().Where(p => p.PrimaryKey); + var cpPks = Composition.ExtendedProperties.Where(p => p.PrimaryKey); if (!cpPks.Any()) { cpPks = Composition.ExtendedProperties.OfType().Where(p => p.AliasedPrimaryKey); diff --git a/TopModel.Core/Model/DataFlow.cs b/TopModel.Core/Model/DataFlow.cs index e638ea69..6774ed73 100644 --- a/TopModel.Core/Model/DataFlow.cs +++ b/TopModel.Core/Model/DataFlow.cs @@ -20,17 +20,17 @@ public class DataFlow public DataFlowType Type { get; set; } #nullable enable - public List DependsOn { get; set; } = new(); + public List DependsOn { get; set; } = []; - public List DependsOnReference { get; set; } = new(); + public List DependsOnReference { get; set; } = []; - public List Hooks { get; set; } = new(); + public List Hooks { get; set; } = []; - public IFieldProperty? ActiveProperty { get; set; } + public IProperty? ActiveProperty { get; set; } public Reference? ActivePropertyReference { get; set; } - public List Sources { get; set; } = new(); + public List Sources { get; set; } = []; public override string ToString() { diff --git a/TopModel.Core/Model/DataFlowSource.cs b/TopModel.Core/Model/DataFlowSource.cs index 158f56c7..a2bca1e4 100644 --- a/TopModel.Core/Model/DataFlowSource.cs +++ b/TopModel.Core/Model/DataFlowSource.cs @@ -13,9 +13,9 @@ public class DataFlowSource public DataFlowSourceMode Mode { get; set; } - public List JoinProperties { get; set; } = new(); + public List JoinProperties { get; set; } = []; - public List JoinPropertyReferences { get; set; } = new(); + public List JoinPropertyReferences { get; set; } = []; public bool InnerJoin { get; set; } diff --git a/TopModel.Core/Model/IFieldProperty.cs b/TopModel.Core/Model/IFieldProperty.cs deleted file mode 100644 index 3b44cda2..00000000 --- a/TopModel.Core/Model/IFieldProperty.cs +++ /dev/null @@ -1,22 +0,0 @@ -namespace TopModel.Core; - -public interface IFieldProperty : IProperty -{ - string? DefaultValue { get; } - - IFieldProperty ResourceProperty => Decorator != null && Parent != Decorator - ? Decorator.Properties.OfType().First(p => p.Name == Name).ResourceProperty - : this is AliasProperty alp && alp.Label == alp.OriginalProperty?.Label - ? alp.OriginalProperty!.ResourceProperty - : this; - - string ResourceKey => $"{ResourceProperty.Parent.Namespace.ModuleCamel}.{ResourceProperty.Parent.NameCamel}.{ResourceProperty.NameCamel}"; - - IFieldProperty CommentResourceProperty => Decorator != null && Parent != Decorator - ? Decorator.Properties.OfType().First(p => p.Name == Name).CommentResourceProperty - : this is AliasProperty alp && alp.Comment == alp.OriginalProperty?.Comment - ? alp.OriginalProperty!.CommentResourceProperty - : this; - - string CommentResourceKey => $"comments.{CommentResourceProperty.Parent.Namespace.ModuleCamel}.{CommentResourceProperty.Parent.NameCamel}.{CommentResourceProperty.NameCamel}"; -} \ No newline at end of file diff --git a/TopModel.Core/Model/IProperty.cs b/TopModel.Core/Model/IProperty.cs index 48137729..539e4689 100644 --- a/TopModel.Core/Model/IProperty.cs +++ b/TopModel.Core/Model/IProperty.cs @@ -26,6 +26,8 @@ public interface IProperty string Comment { get; } + string? DefaultValue { get; } + bool Readonly { get; set; } LocatedString? Trigram { get; set; } @@ -50,8 +52,8 @@ string SqlName var apPk = ap switch { - { Property: IFieldProperty p } => p, - { Association: Class classe } => classe.Properties.OfType().FirstOrDefault(), + { Property: IProperty p } => p, + { Association: Class classe } => classe.Properties.FirstOrDefault(), _ => null }; @@ -78,6 +80,22 @@ string SqlName } } + IProperty ResourceProperty => Decorator != null && Parent != Decorator + ? Decorator.Properties.First(p => p.Name == Name).ResourceProperty + : this is AliasProperty alp && alp.Label == alp.OriginalProperty?.Label + ? alp.OriginalProperty!.ResourceProperty + : this; + + string ResourceKey => $"{ResourceProperty.Parent.Namespace.ModuleCamel}.{ResourceProperty.Parent.NameCamel}.{ResourceProperty.NameCamel}"; + + IProperty CommentResourceProperty => Decorator != null && Parent != Decorator + ? Decorator.Properties.First(p => p.Name == Name).CommentResourceProperty + : this is AliasProperty alp && alp.Comment == alp.OriginalProperty?.Comment + ? alp.OriginalProperty!.CommentResourceProperty + : this; + + string CommentResourceKey => $"comments.{CommentResourceProperty.Parent.Namespace.ModuleCamel}.{CommentResourceProperty.Parent.NameCamel}.{CommentResourceProperty.NameCamel}"; + bool UseLegacyRoleName { get; init; } IProperty CloneWithClassOrEndpoint(Class? classe = null, Endpoint? endpoint = null); diff --git a/TopModel.Core/Model/MappingExtensions.cs b/TopModel.Core/Model/MappingExtensions.cs index 7b0d38c7..da1d6a4b 100644 --- a/TopModel.Core/Model/MappingExtensions.cs +++ b/TopModel.Core/Model/MappingExtensions.cs @@ -21,6 +21,6 @@ public static string GetNameCamel(this OneOf map public static bool GetRequired(this OneOf mapping) { - return mapping.Match(c => c.Required, p => p.Property.Required && p.Property is not IFieldProperty { DefaultValue: not null }); + return mapping.Match(c => c.Required, p => p.Property.Required && p.Property is CompositionProperty or AliasProperty { Property: CompositionProperty } or { DefaultValue: null }); } } diff --git a/TopModel.Core/Model/RegularProperty.cs b/TopModel.Core/Model/RegularProperty.cs index 1c352c54..9a7a99a4 100644 --- a/TopModel.Core/Model/RegularProperty.cs +++ b/TopModel.Core/Model/RegularProperty.cs @@ -3,7 +3,7 @@ namespace TopModel.Core; -public class RegularProperty : IFieldProperty +public class RegularProperty : IProperty { #nullable disable public string Name { get; set; } @@ -31,7 +31,7 @@ public class RegularProperty : IFieldProperty #nullable disable public Domain Domain { get; set; } - public string[] DomainParameters { get; set; } = Array.Empty(); + public string[] DomainParameters { get; set; } = []; public string Comment { get; set; } @@ -54,7 +54,9 @@ public class RegularProperty : IFieldProperty #nullable disable internal Reference Location { get; set; } #nullable enable +#pragma warning disable KTA1600 + /// public IProperty CloneWithClassOrEndpoint(Class? classe = null, Endpoint? endpoint = null) { return new RegularProperty diff --git a/TopModel.Core/ModelExtensions.cs b/TopModel.Core/ModelExtensions.cs index b897b7d5..a8810828 100644 --- a/TopModel.Core/ModelExtensions.cs +++ b/TopModel.Core/ModelExtensions.cs @@ -154,105 +154,102 @@ public static ModelFile GetFile(this object? objet) } } - if (property is IFieldProperty fp) + foreach (var alp in modelStore.Files.SelectMany(c => c.Properties).OfType()) { - foreach (var alp in modelStore.Files.SelectMany(c => c.Properties).OfType()) + if (alp.OriginalProperty == property) { - if (alp.OriginalProperty == fp) + var reference = alp.PropertyReference ?? alp.Reference; + if (reference != null) { - var reference = alp.PropertyReference ?? alp.Reference; - if (reference != null) - { - yield return (reference, alp.GetFile()); - } + yield return (reference, alp.GetFile()); + } - if (collectForward) + if (collectForward) + { + foreach (var result in modelStore.GetPropertyReferencesCore(alp, collectForward: true)) { - foreach (var result in modelStore.GetPropertyReferencesCore(alp, collectForward: true)) - { - yield return result; - } + yield return result; } } - else if (alp.OriginalProperty?.Class == fp.Class) + } + else if (alp.OriginalProperty?.Class == property.Class) + { + var excludeReference = alp.OriginalAliasProperty?.Reference?.ExcludeReferences.FirstOrDefault(er => er.ReferenceName == property.Name); + if (excludeReference != null) { - var excludeReference = alp.OriginalAliasProperty?.Reference?.ExcludeReferences.FirstOrDefault(er => er.ReferenceName == fp.Name); - if (excludeReference != null) - { - yield return (excludeReference, alp.GetFile()); - } + yield return (excludeReference, alp.GetFile()); } } + } - if (fp.Class != null) + if (property.Class != null) + { + foreach (var uk in property.Class.UniqueKeyReferences) { - foreach (var uk in fp.Class.UniqueKeyReferences) + foreach (var prop in uk) { - foreach (var prop in uk) + if (prop.ReferenceName == property.Name) { - if (prop.ReferenceName == fp.Name) - { - yield return (prop, fp.Class.GetFile()); - } + yield return (prop, property.Class.GetFile()); } } + } - if (fp.Class.DefaultPropertyReference?.ReferenceName == fp.Name) - { - yield return (fp.Class.DefaultPropertyReference, fp.Class.GetFile()); - } + if (property.Class.DefaultPropertyReference?.ReferenceName == property.Name) + { + yield return (property.Class.DefaultPropertyReference, property.Class.GetFile()); + } - if (fp.Class.OrderPropertyReference?.ReferenceName == fp.Name) - { - yield return (fp.Class.OrderPropertyReference, fp.Class.GetFile()); - } + if (property.Class.OrderPropertyReference?.ReferenceName == property.Name) + { + yield return (property.Class.OrderPropertyReference, property.Class.GetFile()); + } - if (fp.Class.FlagPropertyReference?.ReferenceName == fp.Name) - { - yield return (fp.Class.FlagPropertyReference, fp.Class.GetFile()); - } + if (property.Class.FlagPropertyReference?.ReferenceName == property.Name) + { + yield return (property.Class.FlagPropertyReference, property.Class.GetFile()); } + } - foreach (var classe in modelStore.Classes) + foreach (var classe in modelStore.Classes) + { + foreach (var mappings in classe.FromMappers.SelectMany(m => m.ClassParams).Concat(classe.ToMappers)) { - foreach (var mappings in classe.FromMappers.SelectMany(m => m.ClassParams).Concat(classe.ToMappers)) + if (mappings.Mappings.ContainsKey(property)) { - if (mappings.Mappings.ContainsKey(fp)) + var reference = mappings.MappingReferences.Keys.FirstOrDefault(f => f.ReferenceName == property.Name); + if (reference != null) { - var reference = mappings.MappingReferences.Keys.FirstOrDefault(f => f.ReferenceName == fp.Name); - if (reference != null) - { - yield return (reference, classe.GetFile()); - } + yield return (reference, classe.GetFile()); } + } - if (mappings.Mappings.ContainsValue(fp)) + if (mappings.Mappings.ContainsValue(property)) + { + var reference = mappings.MappingReferences.Values.FirstOrDefault(f => f.ReferenceName == property.Name); + if (reference != null) { - var reference = mappings.MappingReferences.Values.FirstOrDefault(f => f.ReferenceName == fp.Name); - if (reference != null) - { - yield return (reference, classe.GetFile()); - } + yield return (reference, classe.GetFile()); } } } + } - foreach (var dataFlow in modelStore.DataFlows) + foreach (var dataFlow in modelStore.DataFlows) + { + if (dataFlow.ActiveProperty == property) { - if (dataFlow.ActiveProperty == fp) - { - yield return (dataFlow.ActivePropertyReference!, dataFlow.GetFile()); - } + yield return (dataFlow.ActivePropertyReference!, dataFlow.GetFile()); + } - foreach (var source in dataFlow.Sources) + foreach (var source in dataFlow.Sources) + { + if (source.JoinProperties.Contains(property)) { - if (source.JoinProperties.Contains(fp)) + var reference = source.JoinPropertyReferences.FirstOrDefault(f => f.ReferenceName == property.Name); + if (reference != null) { - var reference = source.JoinPropertyReferences.FirstOrDefault(f => f.ReferenceName == fp.Name); - if (reference != null) - { - yield return (reference, dataFlow.GetFile()); - } + yield return (reference, dataFlow.GetFile()); } } } diff --git a/TopModel.Core/Resolvers/ClassResolver.cs b/TopModel.Core/Resolvers/ClassResolver.cs index e7316719..544f1d65 100644 --- a/TopModel.Core/Resolvers/ClassResolver.cs +++ b/TopModel.Core/Resolvers/ClassResolver.cs @@ -33,7 +33,7 @@ public IEnumerable CheckResult() foreach (var classe in modelFile.Classes.Where(c => c.Values.Count > 0 && (c.IsPersistent || c.UniqueKeys.Count > 0))) { - var uks = new List>(); + var uks = new List>(); uks.AddRange(classe.UniqueKeys); if (classe.IsPersistent) { @@ -143,7 +143,7 @@ public IEnumerable ResolveSpecialProperties() { if (classe.DefaultPropertyReference != null) { - classe.DefaultProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.Name == classe.DefaultPropertyReference.ReferenceName); + classe.DefaultProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.Name == classe.DefaultPropertyReference.ReferenceName); if (classe.DefaultProperty == null) { yield return new ModelError(classe, $"La propriété '{classe.DefaultPropertyReference.ReferenceName}' n'existe pas sur la classe '{classe}'.", classe.DefaultPropertyReference) { ModelErrorType = ModelErrorType.TMD1011 }; @@ -152,12 +152,12 @@ public IEnumerable ResolveSpecialProperties() else { // Si la classe a une propriété "Label" ou "Libelle", alors on la considère par défaut (sic) comme propriété par défaut. - classe.DefaultProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.NamePascal == "Label" || fp.NamePascal == "Libelle"); + classe.DefaultProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.NamePascal == "Label" || fp.NamePascal == "Libelle"); } if (classe.OrderPropertyReference != null) { - classe.OrderProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.Name == classe.OrderPropertyReference.ReferenceName); + classe.OrderProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.Name == classe.OrderPropertyReference.ReferenceName); if (classe.OrderProperty == null) { yield return new ModelError(classe, $"La propriété '{classe.OrderPropertyReference.ReferenceName}' n'existe pas sur la classe '{classe}'.", classe.OrderPropertyReference) { ModelErrorType = ModelErrorType.TMD1011 }; @@ -166,12 +166,12 @@ public IEnumerable ResolveSpecialProperties() else { // Si la classe a une propriété "Order" ou "Ordre", alors on la considère par défaut comme propriété d'ordre. - classe.OrderProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.NamePascal == "Order" || fp.NamePascal == "Ordre"); + classe.OrderProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.NamePascal == "Order" || fp.NamePascal == "Ordre"); } if (classe.FlagPropertyReference != null) { - classe.FlagProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.Name == classe.FlagPropertyReference.ReferenceName); + classe.FlagProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.Name == classe.FlagPropertyReference.ReferenceName); if (classe.FlagProperty == null) { yield return new ModelError(classe, $"La propriété '{classe.FlagPropertyReference.ReferenceName}' n'existe pas sur la classe '{classe}'.", classe.FlagPropertyReference) { ModelErrorType = ModelErrorType.TMD1011 }; @@ -180,7 +180,7 @@ public IEnumerable ResolveSpecialProperties() else { // Si la classe a une propriété "Flag", alors on la considère par défaut comme propriété de flag. - classe.FlagProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.NamePascal == "Flag"); + classe.FlagProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.NamePascal == "Flag"); } } } @@ -194,7 +194,7 @@ public void ResolveTranslations(TranslationStore translationStore, string defaul { foreach (var classe in modelFile.Classes) { - foreach (var p in classe.Properties.OfType().Where(p => p.Label != null)) + foreach (var p in classe.Properties.Where(p => p.Label != null)) { translationStore.Translations[defaultLang][p.ResourceKey] = p.Label!; } @@ -224,12 +224,12 @@ public IEnumerable ResolveUniqueKeys() foreach (var ukRef in classe.UniqueKeyReferences) { - var uk = new List(); + var uk = new List(); classe.UniqueKeys.Add(uk); foreach (var ukPropRef in ukRef) { - var property = classe.Properties.OfType().FirstOrDefault(p => p.Name == ukPropRef.ReferenceName); + var property = classe.Properties.FirstOrDefault(p => p.Name == ukPropRef.ReferenceName); if (property == null) { @@ -261,7 +261,7 @@ public IEnumerable ResolveValues() foreach (var value in valueRef.Value) { - var property = classe.ExtendedProperties.OfType().FirstOrDefault(p => p.Name == value.Key.ReferenceName); + var property = classe.ExtendedProperties.FirstOrDefault(p => p.Name == value.Key.ReferenceName); if (property == null) { @@ -273,7 +273,7 @@ public IEnumerable ResolveValues() } } - var missingRequiredProperties = classe.ExtendedProperties.OfType() + var missingRequiredProperties = classe.ExtendedProperties .Where(p => p.Required && (!(p.Domain?.AutoGeneratedValue ?? false) || p is AssociationProperty or AliasProperty { Property: AssociationProperty }) diff --git a/TopModel.Core/Resolvers/DataFlowResolver.cs b/TopModel.Core/Resolvers/DataFlowResolver.cs index 2123bfcd..edac4709 100644 --- a/TopModel.Core/Resolvers/DataFlowResolver.cs +++ b/TopModel.Core/Resolvers/DataFlowResolver.cs @@ -22,7 +22,7 @@ public IEnumerable ResolveDataFlows() if (dataFlow.ActivePropertyReference != null) { - dataFlow.ActiveProperty = classe.ExtendedProperties.OfType().FirstOrDefault(fp => fp.Name == dataFlow.ActivePropertyReference.ReferenceName); + dataFlow.ActiveProperty = classe.ExtendedProperties.FirstOrDefault(fp => fp.Name == dataFlow.ActivePropertyReference.ReferenceName); if (dataFlow.ActiveProperty == null) { yield return new ModelError(dataFlow, $"La propriété '{dataFlow.ActivePropertyReference.ReferenceName}' n'existe pas sur la classe '{classe}'.", dataFlow.ActivePropertyReference) { ModelErrorType = ModelErrorType.TMD1011 }; @@ -55,7 +55,7 @@ public IEnumerable ResolveDataFlows() foreach (var joinPropertyReference in source.JoinPropertyReferences) { - var joinProperty = sourceClass.ExtendedProperties.OfType().FirstOrDefault(fp => fp.Name == joinPropertyReference.ReferenceName); + var joinProperty = sourceClass.ExtendedProperties.FirstOrDefault(fp => fp.Name == joinPropertyReference.ReferenceName); if (joinProperty == null) { yield return new ModelError(dataFlow, $"La propriété '{joinPropertyReference.ReferenceName}' n'existe pas sur la classe '{sourceClass}'.", joinPropertyReference) { ModelErrorType = ModelErrorType.TMD1011 }; diff --git a/TopModel.Core/Resolvers/EndpointResolver.cs b/TopModel.Core/Resolvers/EndpointResolver.cs index 17dae01f..3e40e0fe 100644 --- a/TopModel.Core/Resolvers/EndpointResolver.cs +++ b/TopModel.Core/Resolvers/EndpointResolver.cs @@ -29,11 +29,11 @@ public IEnumerable CheckResult() if (split[i].StartsWith('{')) { var routeParamName = split[i][1..^1]; - var param = endpoint.Params.OfType().SingleOrDefault(param => param.GetParamName() == routeParamName); + var param = endpoint.Params.SingleOrDefault(param => param.GetParamName() == routeParamName); if (param == null) { - yield return new ModelError(endpoint, $"Le endpoint '{endpoint.Name}' définit un paramètre '{routeParamName}' dans sa route qui n'existe pas dans la liste des paramètres. Les valeurs possibles sont : {string.Join(", ", endpoint.Params.OfType().Select(p => p.GetParamName()))}.") { ModelErrorType = ModelErrorType.TMD1027 }; + yield return new ModelError(endpoint, $"Le endpoint '{endpoint.Name}' définit un paramètre '{routeParamName}' dans sa route qui n'existe pas dans la liste des paramètres. Les valeurs possibles sont : {string.Join(", ", endpoint.Params.Select(p => p.GetParamName()))}.") { ModelErrorType = ModelErrorType.TMD1027 }; } } } diff --git a/TopModel.Core/Resolvers/MapperResolver.cs b/TopModel.Core/Resolvers/MapperResolver.cs index 4064b4a4..98f712fa 100644 --- a/TopModel.Core/Resolvers/MapperResolver.cs +++ b/TopModel.Core/Resolvers/MapperResolver.cs @@ -37,7 +37,7 @@ public IEnumerable ResolveMappers() continue; } - var mappedProperty = mappedClass.ExtendedProperties.OfType().FirstOrDefault(p => p.Name == mapping.Value.ReferenceName); + var mappedProperty = mappedClass.ExtendedProperties.FirstOrDefault(p => p.Name == mapping.Value.ReferenceName); if (mappedProperty == null) { yield return new ModelError(classe, $"La propriété '{{0}}' est introuvable sur la classe '{mappedClass}'.", mapping.Value) { ModelErrorType = ModelErrorType.TMD1004 }; @@ -56,34 +56,39 @@ public IEnumerable ResolveMappers() yield return new ModelError(classe, $"La propriété '{currentProperty.Name}' ne peut pas être la cible d'un mapping car elle a été marquée comme 'readonly'.", mapping.Key) { ModelErrorType = ModelErrorType.TMD1024 }; } - if (currentProperty is IFieldProperty fp) + if (currentProperty.Domain != mappedProperty.Domain + && !converters.Any(c => c.From.Any(cf => cf == (mappings.To ? currentProperty.Domain : mappedProperty.Domain)) && c.To.Any(ct => ct == (mappings.To ? mappedProperty.Domain : currentProperty.Domain)))) { - if (fp.Domain != mappedProperty.Domain - && !converters.Any(c => c.From.Any(cf => cf == (mappings.To ? fp.Domain : mappedProperty.Domain)) && c.To.Any(ct => ct == (mappings.To ? mappedProperty.Domain : fp.Domain)))) - { - yield return new ModelError(classe, $"La propriété '{mappedProperty.Name}' ne peut pas être mappée à '{currentProperty.Name}' car elle n'a pas le même domaine ('{mappedProperty.Domain.Name}' au lieu de '{fp.Domain.Name}') et qu'il n'existe pas de convertisseur entre les deux.", mapping.Value) { ModelErrorType = ModelErrorType.TMD1014 }; - } + yield return new ModelError(classe, $"La propriété '{mappedProperty.Name}' ne peut pas être mappée à '{currentProperty.Name}' car elle n'a pas le même domaine ('{mappedProperty.Domain.Name}' au lieu de '{currentProperty.Domain.Name}') et qu'il n'existe pas de convertisseur entre les deux.", mapping.Value) { ModelErrorType = ModelErrorType.TMD1014 }; } - else if (currentProperty is CompositionProperty cp) + + var sourceCp = currentProperty switch { - var mappedAp = mappedProperty switch - { - AssociationProperty ap => ap, - AliasProperty { Property: AssociationProperty ap } => ap, - _ => null - }; + CompositionProperty cp => cp, + AliasProperty { Property: CompositionProperty cp } => cp, + _ => null + }; + + var mappedAp = mappedProperty switch + { + AssociationProperty ap => ap, + AliasProperty { Property: AssociationProperty ap } => ap, + _ => null + }; + if (sourceCp != null) + { if (mappedAp == null) { yield return new ModelError(classe, $"La propriété '{mappedProperty.Name}' ne peut pas être mappée à la composition '{currentProperty.Name}' car ce n'est pas une association.", mapping.Value) { ModelErrorType = ModelErrorType.TMD1017 }; } - else if (!useLegacyAssociationCompositionMappers && (mappedAp.Type.IsToMany() || cp.Domain != null)) + else if (!useLegacyAssociationCompositionMappers && (mappedAp.Type.IsToMany() || sourceCp.Domain != null)) { yield return new ModelError(classe, $"L'association '{mappedProperty.Name}' ne peut pas être mappée à la composition '{currentProperty.Name}' car l'association et la composition doivent toutes les deux être simples.", mapping.Value) { ModelErrorType = ModelErrorType.TMD1018 }; } - else if (!useLegacyAssociationCompositionMappers && cp.CompositionPrimaryKey?.Domain != mappedAp.Domain && !converters.Any(c => c.From.Any(cf => cf == cp.CompositionPrimaryKey?.Domain) && c.To.Any(ct => ct == mappedAp.Domain))) + else if (!useLegacyAssociationCompositionMappers && sourceCp.CompositionPrimaryKey?.Domain != mappedAp.Domain && !converters.Any(c => c.From.Any(cf => cf == sourceCp.CompositionPrimaryKey?.Domain) && c.To.Any(ct => ct == mappedAp.Domain))) { - yield return new ModelError(classe, $"La propriété '{mappedProperty.Name}' ne peut pas être mappée à la composition '{currentProperty.Name}' car elle n'a pas le même domaine que la composition '{cp.Composition.Name}' ('{mappedProperty.Domain.Name}' au lieu de '{cp.CompositionPrimaryKey?.Domain?.Name ?? string.Empty}').", mapping.Value) { ModelErrorType = ModelErrorType.TMD1019 }; + yield return new ModelError(classe, $"La propriété '{mappedProperty.Name}' ne peut pas être mappée à la composition '{currentProperty.Name}' car elle n'a pas le même domaine que la composition '{sourceCp.Composition.Name}' ('{mappedProperty.Domain.Name}' au lieu de '{sourceCp.CompositionPrimaryKey?.Domain?.Name ?? string.Empty}').", mapping.Value) { ModelErrorType = ModelErrorType.TMD1019 }; } } } @@ -117,12 +122,25 @@ public IEnumerable ResolveMappers() if (mapping.TargetProperty != null) { - if (mapping.TargetProperty is not CompositionProperty && mapping.Property is CompositionProperty) + var sourceCp = mapping.Property switch + { + CompositionProperty cp => cp, + AliasProperty { Property: CompositionProperty cp } => cp, + _ => null + }; + var targetCp = mapping.TargetProperty switch + { + CompositionProperty cp => cp, + AliasProperty { Property: CompositionProperty cp } => cp, + _ => null + }; + + if (targetCp == null && sourceCp != null) { yield return new ModelError(classe, $"La propriété '{mapping.Property.Name}' ne peut pas être une composition pour définir un mapping vers '{mapping.TargetProperty.Name}'.", mapping.Property.GetLocation()) { ModelErrorType = ModelErrorType.TMD1033 }; } - if (mapping.TargetProperty is CompositionProperty { Composition: Class cpClass } && (mapping.Property is not CompositionProperty || ((CompositionProperty)mapping.Property).Composition != cpClass)) + if (targetCp != null && (sourceCp == null || targetCp.Composition != sourceCp.Composition)) { yield return new ModelError(classe, $"La propriété '{mapping.Property.Name}' doit être une composition de la même classe que '{mapping.TargetProperty.Name}' pour définir un mapping entre les deux.", mapping.Property.GetLocation()) { ModelErrorType = ModelErrorType.TMD1032 }; } @@ -172,7 +190,7 @@ public IEnumerable ResolveMappers() { foreach (var property in classe.ExtendedProperties.OfType().Where(property => !property.Readonly && !explicitMappings.Any(m => m.Key == property) && !param.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) { - var matchingProperties = param.Class.ExtendedProperties.OfType().Where(p => property.Property == p || p is AliasProperty alp && property == alp.Property || p is AliasProperty alp2 && property.Property == alp2.Property); + var matchingProperties = param.Class.ExtendedProperties.Where(p => property.Property == p || p is AliasProperty alp && property == alp.Property || p is AliasProperty alp2 && property.Property == alp2.Property); if (matchingProperties.Count() == 1) { var p = matchingProperties.First(); @@ -190,9 +208,9 @@ public IEnumerable ResolveMappers() foreach (var param in mapper.ClassParams.Where(p => p.Class != null)) { - foreach (var property in classe.ExtendedProperties.OfType().Where(property => !property.Readonly && !explicitAndAliasMappings.Any(m => m.Key == property) && !param.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) + foreach (var property in classe.ExtendedProperties.Where(property => !property.Readonly && !explicitAndAliasMappings.Any(m => m.Key == property) && !param.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) { - foreach (var p in param.Class.ExtendedProperties.OfType()) + foreach (var p in param.Class.ExtendedProperties) { if (!param.Mappings.ContainsKey(property) && p.Name == property.Name && p.Domain != null && (p.Domain == property.Domain || converters.Any(c => c.From.Any(cf => cf == p.Domain) && c.To.Any(ct => ct == property.Domain)))) { @@ -233,7 +251,7 @@ public IEnumerable ResolveMappers() foreach (var property in classe.ExtendedProperties.OfType().Where(property => !explicitMappings.ContainsKey(property) && !mapper.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) { - var matchingProperties = mapper.Class.ExtendedProperties.OfType().Where(p => property.Property == p || p is AliasProperty alp && property == alp.Property || p is AliasProperty alp2 && property.Property == alp2.Property); + var matchingProperties = mapper.Class.ExtendedProperties.Where(p => property.Property == p || p is AliasProperty alp && property == alp.Property || p is AliasProperty alp2 && property.Property == alp2.Property); if (matchingProperties.Count() == 1) { var p = matchingProperties.First(); @@ -246,9 +264,9 @@ public IEnumerable ResolveMappers() var explicitAndAliasMappings = mapper.Mappings.ToDictionary(p => p.Key, p => p.Value); - foreach (var property in classe.ExtendedProperties.OfType().Where(property => !explicitAndAliasMappings.ContainsKey(property) && !mapper.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) + foreach (var property in classe.ExtendedProperties.Where(property => !explicitAndAliasMappings.ContainsKey(property) && !mapper.MappingReferences.Any(m => m.Key.ReferenceName == property.Name && m.Value.ReferenceName == "false"))) { - foreach (var p in mapper.Class.ExtendedProperties.OfType()) + foreach (var p in mapper.Class.ExtendedProperties) { if (p.Name == property.Name && p.Domain != null diff --git a/TopModel.Core/Resolvers/PropertyResolver.cs b/TopModel.Core/Resolvers/PropertyResolver.cs index d26d44b4..5b786f29 100644 --- a/TopModel.Core/Resolvers/PropertyResolver.cs +++ b/TopModel.Core/Resolvers/PropertyResolver.cs @@ -129,8 +129,7 @@ public IEnumerable ResolveAliases(Func filter) (alp.Reference.IncludeReferences.Count > 0 ? alp.Reference.IncludeReferences.Select(p => aliasedClass.Properties.First(prop => prop.Name == p.ReferenceName)) : aliasedClass.Properties.Where(prop => !alp.Reference.ExcludeReferences.Select(p => p.ReferenceName).Contains(prop.Name))) - .Reverse() - .OfType(); + .Reverse(); foreach (var property in propertiesToAlias) { @@ -222,7 +221,7 @@ public IEnumerable ResolveAssociationProperties() if (ap.PropertyReference != null) { - var referencedProperty = ap.Association.ExtendedProperties.OfType().FirstOrDefault(p => p.Name == ap.PropertyReference!.ReferenceName); + var referencedProperty = ap.Association.ExtendedProperties.FirstOrDefault(p => p.Name == ap.PropertyReference!.ReferenceName); if (referencedProperty == null) { yield return new ModelError(ap, $"La propriété '{{0}}' est introuvable sur la classe '{ap.Association}'.", ap.PropertyReference) { ModelErrorType = ModelErrorType.TMD1004 }; diff --git a/TopModel.Core/TranslationStore.cs b/TopModel.Core/TranslationStore.cs index 21df68d0..e9b6298e 100644 --- a/TopModel.Core/TranslationStore.cs +++ b/TopModel.Core/TranslationStore.cs @@ -4,7 +4,7 @@ public class TranslationStore { public Dictionary> Translations { get; } = new(); - public string GetTranslation(IFieldProperty property, string lang) + public string GetTranslation(IProperty property, string lang) { return Translations.TryGetValue(lang, out var dict) && dict.TryGetValue(property.ResourceKey, out var translatedValue) diff --git a/TopModel.Generator.Core/GeneratorBase.cs b/TopModel.Generator.Core/GeneratorBase.cs index 4b3533c7..66e4d57d 100644 --- a/TopModel.Generator.Core/GeneratorBase.cs +++ b/TopModel.Generator.Core/GeneratorBase.cs @@ -52,7 +52,7 @@ public void OnFilesChanged(IEnumerable files, LoggingScope? storeConf if (!NoLanguage) { - var missingDomains = handledFiles.SelectMany(f => f.Properties).OfType().Where(fp => !PersistentOnly || (fp.Class?.IsPersistent ?? false)).Select(fp => fp.Domain) + var missingDomains = handledFiles.SelectMany(f => f.Properties).Where(fp => !PersistentOnly || (fp.Class?.IsPersistent ?? false)).Select(fp => fp.Domain) .Concat(PersistentOnly ? Array.Empty() : handledFiles.SelectMany(f => f.Properties).OfType().Select(fp => fp.Domain!)) .Where(domain => domain != null && Config.GetImplementation(domain) == null) .Distinct(); diff --git a/TopModel.Generator.Core/GeneratorConfigBase.cs b/TopModel.Generator.Core/GeneratorConfigBase.cs index 2fe0ac23..130dd954 100644 --- a/TopModel.Generator.Core/GeneratorConfigBase.cs +++ b/TopModel.Generator.Core/GeneratorConfigBase.cs @@ -93,7 +93,7 @@ public abstract class GeneratorConfigBase /// Classes disponibles. /// Propriété à vérifier (si c'est pas la clé primaire). /// Oui/non. - public virtual bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IFieldProperty? prop = null) + public virtual bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IProperty? prop = null) { if (availableClasses != null && !availableClasses.Contains(classe)) { @@ -102,7 +102,7 @@ public virtual bool CanClassUseEnums(Class classe, IEnumerable? available prop ??= classe.EnumKey; - bool CheckProperty(IFieldProperty fp) + bool CheckProperty(IProperty fp) { return (fp == classe.EnumKey || classe.UniqueKeys.Where(uk => uk.Count == 1).Select(uk => uk.Single()).Contains(prop)) && classe.Values.All(r => r.Value.ContainsKey(fp) && IsEnumNameValid(r.Value[fp].ToString())); @@ -181,20 +181,11 @@ public IEnumerable GetDecoratorImports(Endpoint endpoint, string tag) public IEnumerable GetDomainAnnotations(IProperty property, string tag) { - if (property is IFieldProperty fp) + if (property.Domain is not null) { - foreach (var annotation in GetImplementation(fp.Domain)!.Annotations - .Where(a => FilterAnnotations(a, fp, tag)) - .Select(a => a.Text.ParseTemplate(fp, this, tag))) - { - yield return annotation; - } - } - else if (property is CompositionProperty { Domain: not null } cp) - { - foreach (var annotation in GetImplementation(cp.Domain)!.Annotations - .Where(a => FilterAnnotations(a, cp, tag)) - .Select(a => a.Text.ParseTemplate(cp, this, tag))) + foreach (var annotation in GetImplementation(property.Domain)!.Annotations + .Where(a => FilterAnnotations(a, property, tag)) + .Select(a => a.Text.ParseTemplate(property, this, tag))) { yield return annotation; } @@ -228,7 +219,7 @@ public IEnumerable GetDomainImports(IProperty property, string tag) } } - public string GetEnumType(IFieldProperty fp, bool isPrimaryKeyDef = false) + public string GetEnumType(IProperty fp, bool isPrimaryKeyDef = false) { var op = fp switch { @@ -310,7 +301,7 @@ string HandleAUC(AssociationProperty ap) : ap.Association.NamePascal; } - string HandleEnum(IFieldProperty op) + string HandleEnum(IProperty op) { var type = op is AssociationProperty ap ? GetEnum(ap.Association.Name, ap.Property.Name) @@ -337,9 +328,11 @@ AssociationProperty ap when CanClassUseEnums(ap.Association, availableClasses, a RegularProperty { Class: not null } rp when CanClassUseEnums(rp.Class, availableClasses, rp) => HandleEnum(rp), AliasProperty { Property: RegularProperty { Class: not null } rp } when CanClassUseEnums(rp.Class, availableClasses, rp) => HandleEnum(rp), AliasProperty { As: not null } alp when GetImplementation(alp.Domain)?.GenericType != null => GetImplementation(alp.Domain)!.GenericType!.Replace("{T}", GetType(alp.OriginalProperty!, availableClasses, useClassForAssociation)), - IFieldProperty => (GetImplementation(property.Domain)?.Type ?? string.Empty).ParseTemplate(property, this), CompositionProperty { Domain: not null } => (GetImplementation(property.Domain)?.GenericType ?? "{T}").Replace("{T}", "{composition.name}").ParseTemplate(property, this), + AliasProperty { Property: CompositionProperty { Domain: not null } } => (GetImplementation(property.Domain)?.GenericType ?? "{T}").Replace("{T}", "{composition.name}").ParseTemplate(property, this), CompositionProperty cp => cp.Composition.NamePascal, + AliasProperty { Property: CompositionProperty cp } => cp.Composition.NamePascal, + IProperty => (GetImplementation(property.Domain)?.Type ?? string.Empty).ParseTemplate(property, this), _ => string.Empty }; } @@ -353,25 +346,23 @@ AssociationProperty ap when CanClassUseEnums(ap.Association, availableClasses, a /// La valeur. public virtual string GetValue(IProperty property, IEnumerable availableClasses, string? value = null) { - var fp = property as IFieldProperty; - - if (!IgnoreDefaultValues) + if (!IgnoreDefaultValues && property is not CompositionProperty and not AliasProperty { Property: CompositionProperty }) { - value ??= fp?.DefaultValue; + value ??= property?.DefaultValue; } - if (fp == null || value == null || value == "null" || value == "undefined") + if (property == null || value == null || value == "null" || value == "undefined") { return NullValue; } - var template = GetImplementation(fp.Domain)?.GetValueTemplate(value); + var template = GetImplementation(property.Domain)?.GetValueTemplate(value); if (template != null) { - return template.Value.Replace("{value}", value).ParseTemplate(fp, this); + return template.Value.Replace("{value}", value).ParseTemplate(property, this); } - var prop = fp is AliasProperty alp ? alp.Property : fp; + var prop = property is AliasProperty alp ? alp.Property : property; var ap = prop as AssociationProperty; var classe = ap != null ? ap.Association : prop.Class; @@ -393,7 +384,7 @@ public virtual string GetValue(IProperty property, IEnumerable availableC } } - if (ShouldQuoteValue(fp)) + if (ShouldQuoteValue(property)) { return QuoteValue(value); } @@ -401,9 +392,9 @@ public virtual string GetValue(IProperty property, IEnumerable availableC return value; } - public IEnumerable GetValueImports(IFieldProperty property, string? value = null) + public IEnumerable GetValueImports(IProperty property, string? value = null) { - if (!IgnoreDefaultValues) + if (!IgnoreDefaultValues && property is not CompositionProperty and not AliasProperty { Property: CompositionProperty }) { value ??= property.DefaultValue; } @@ -576,7 +567,7 @@ public virtual string ResolveVariables(string value, string? tag = null, string? /// /// Propriété. /// Oui/non. - public virtual bool ShouldQuoteValue(IFieldProperty property) + public virtual bool ShouldQuoteValue(IProperty property) { return GetImplementation(property.Domain)?.Type?.ToLower() == "string"; } diff --git a/TopModel.Generator.Core/TemplateExtensions.cs b/TopModel.Generator.Core/TemplateExtensions.cs index db20ae46..75c5e887 100644 --- a/TopModel.Generator.Core/TemplateExtensions.cs +++ b/TopModel.Generator.Core/TemplateExtensions.cs @@ -48,38 +48,18 @@ public static Func GetTransformation(this string input) public static string ParseTemplate(this string template, IProperty p, GeneratorConfigBase config, string? tag = null) { - if (p is IFieldProperty fp) + if (string.IsNullOrEmpty(template) || !template.Contains('{')) { - if (string.IsNullOrEmpty(template) || !template.Contains('{')) - { - return template; - } - - var result = template; - foreach (var t in template.ExtractVariables()) - { - result = result.Replace(t.Value, ResolveVariable(t.Value.Trim('{', '}'), fp, fp.DomainParameters, config, tag)); - } - - return result; + return template; } - else if (p is CompositionProperty cp) - { - if (string.IsNullOrEmpty(template) || !template.Contains('{')) - { - return template; - } - - var result = template; - foreach (var t in template.ExtractVariables()) - { - result = result.Replace(t.Value, ResolveVariable(t.Value.Trim('{', '}'), cp, cp.DomainParameters, config, tag)); - } - return result; + var result = template; + foreach (var t in template.ExtractVariables()) + { + result = result.Replace(t.Value, ResolveVariable(t.Value.Trim('{', '}'), p, p.DomainParameters, config, tag)); } - return template; + return result; } public static string ParseTemplate(this string template, Class c, string[] parameters, GeneratorConfigBase config, string? tag = null) @@ -152,28 +132,17 @@ private static string ResolveVariable(this string input, Domain domain, Generato }; } - private static string ResolveVariable(this string input, IProperty c, string[] parameters, GeneratorConfigBase config, string? tag = null) - { - switch (c) - { - case IFieldProperty fp: return ResolveVariable(input, fp, parameters, config, tag); - case CompositionProperty cp: return ResolveVariable(input, cp, parameters, config, tag); - default: return string.Empty; - } - } - private static string ResolveVariable(this string input, IPropertyContainer container, string[] parameters, GeneratorConfigBase config, string? tag = null) { - switch (container) + return container switch { - case Endpoint e: - return ResolveVariable(input, e, parameters, config, tag); - case Class c: return ResolveVariable(input, c, parameters, config, tag); - default: return string.Empty; - } + Endpoint e => ResolveVariable(input, e, parameters, config, tag), + Class c => ResolveVariable(input, c, parameters, config, tag), + _ => string.Empty, + }; } - private static string ResolveVariable(this string input, IFieldProperty fp, string[] parameters, GeneratorConfigBase config, string? tag = null) + private static string ResolveVariable(this string input, IProperty p, string[] parameters, GeneratorConfigBase config, string? tag = null) { if (input == null || input.Length == 0) { @@ -187,93 +156,68 @@ private static string ResolveVariable(this string input, IFieldProperty fp, stri if (input.StartsWith("parent.")) { - return ResolveVariable(input["parent.".Length..], fp.Parent, parameters, config, tag); + return ResolveVariable(input["parent.".Length..], p.Parent, parameters, config, tag); } if (input.StartsWith("class.")) { - return ResolveVariable(input["class.".Length..], fp.Parent, parameters, config, tag); + return ResolveVariable(input["class.".Length..], p.Parent, parameters, config, tag); } if (input.StartsWith("endpoint.")) { - return ResolveVariable(input["endpoint.".Length..], fp.Parent, parameters, config, tag); + return ResolveVariable(input["endpoint.".Length..], p.Parent, parameters, config, tag); } if (input.StartsWith("domain.")) { - return ResolveVariable(input["domain.".Length..], fp.Domain, config, tag); + return ResolveVariable(input["domain.".Length..], p.Domain, config, tag); } - if (input.StartsWith("association.") && (fp is AssociationProperty ap || fp is AliasProperty alp && alp.Property is AssociationProperty asp)) + if (input.StartsWith("association.")) { - var asso = fp switch + var association = p switch { - AssociationProperty assop => assop.Association, - AliasProperty { Property: AssociationProperty alip } => alip.Association, + AssociationProperty ap => ap.Association, + AliasProperty { Property: AssociationProperty ap } => ap.Association, _ => null // impossible }; - return ResolveVariable(input["association.".Length..], asso!, parameters, config, tag); - } - - var transform = input.GetTransformation(); - var result = input.Split(':').First() switch - { - "name" => transform(fp.Name ?? string.Empty), - "sqlName" => transform(fp.SqlName ?? string.Empty), - "paramName" => transform(fp.GetParamName().ToString()), - "trigram" => transform(fp.Trigram ?? fp.Class?.Trigram ?? string.Empty), - "label" => transform(fp.Label ?? string.Empty), - "comment" => transform(fp.Comment), - "required" => transform(fp.Required.ToString().ToLower()), - "resourceKey" => transform(fp.ResourceKey.ToString()), - "commentResourceKey" => transform(fp.CommentResourceKey.ToString()), - "defaultValue" => transform(fp.DefaultValue?.ToString() ?? string.Empty), - var i => config.ResolveVariables(config.ResolveGlobalVariables($@"{{{i}}}").Trim('{', '}'), module: fp.Parent.Namespace.Module, tag: tag) - }; - return result; - } - - private static string ResolveVariable(this string input, CompositionProperty cp, string[] parameters, GeneratorConfigBase config, string? tag = null) - { - if (input == null || input.Length == 0) - { - return string.Empty; - } - - for (var i = 0; i < parameters.Length; i++) - { - input = input.Replace($"${i}", parameters[i]); - } - - if (input.StartsWith("parent.")) - { - return ResolveVariable(input["parent.".Length..], cp.Class, parameters, config, tag); - } - - if (input.StartsWith("class.")) - { - return ResolveVariable(input["class.".Length..], cp.Class, parameters, config, tag); - } - - if (input.StartsWith("endpoint.")) - { - return ResolveVariable(input["endpoint.".Length..], cp.Class, parameters, config, tag); + if (association != null) + { + return ResolveVariable(input["association.".Length..], association, parameters, config, tag); + } } if (input.StartsWith("composition.")) { - return ResolveVariable(input["composition.".Length..], cp.Composition, parameters, config, tag); + var composition = p switch + { + CompositionProperty cp => cp.Composition, + AliasProperty { Property: CompositionProperty cp } => cp.Composition, + _ => null // impossible + }; + + if (composition != null) + { + return ResolveVariable(input["composition.".Length..], composition, parameters, config, tag); + } } var transform = input.GetTransformation(); var result = input.Split(':').First() switch { - "name" => transform(cp.Name ?? string.Empty), - "label" => transform(cp.Label ?? string.Empty), - "comment" => transform(cp.Comment), - var i => config.ResolveVariables(config.ResolveGlobalVariables($@"{{{i}}}").Trim('{', '}'), module: cp.Class.Namespace.Module, tag: tag) + "name" => transform(p.Name ?? string.Empty), + "sqlName" => transform(p.SqlName ?? string.Empty), + "paramName" => transform(p.GetParamName().ToString()), + "trigram" => transform(p.Trigram ?? p.Class?.Trigram ?? string.Empty), + "label" => transform(p.Label ?? string.Empty), + "comment" => transform(p.Comment), + "required" => transform(p.Required.ToString().ToLower()), + "resourceKey" => transform(p.ResourceKey.ToString()), + "commentResourceKey" => transform(p.CommentResourceKey.ToString()), + "defaultValue" => transform(p.DefaultValue?.ToString() ?? string.Empty), + var i => config.ResolveVariables(config.ResolveGlobalVariables($@"{{{i}}}").Trim('{', '}'), module: p.Parent.Namespace.Module, tag: tag) }; return result; diff --git a/TopModel.Generator.Core/TranslationGeneratorBase.cs b/TopModel.Generator.Core/TranslationGeneratorBase.cs index ca1fa52f..7a9b9194 100644 --- a/TopModel.Generator.Core/TranslationGeneratorBase.cs +++ b/TopModel.Generator.Core/TranslationGeneratorBase.cs @@ -20,7 +20,7 @@ public TranslationGeneratorBase(ILogger> logger, Tra { var properties = Classes .Where(c => c.Tags.Contains(tag)) - .SelectMany(c => c.Properties.OfType()); + .SelectMany(c => c.Properties); return properties .SelectMany(p => GetResourceFileNames(p, tag)) @@ -30,7 +30,7 @@ public TranslationGeneratorBase(ILogger> logger, Tra }) .Distinct(); - protected virtual string? GetCommentResourceFilePath(IFieldProperty property, string tag, string lang) + protected virtual string? GetCommentResourceFilePath(IProperty property, string tag, string lang) { return null; } @@ -40,9 +40,9 @@ public TranslationGeneratorBase(ILogger> logger, Tra return null; } - protected abstract string? GetResourceFilePath(IFieldProperty property, string tag, string lang); + protected abstract string? GetResourceFilePath(IProperty property, string tag, string lang); - protected virtual void HandleCommentResourceFile(string filePath, string lang, IEnumerable properties) + protected virtual void HandleCommentResourceFile(string filePath, string lang, IEnumerable properties) { } @@ -53,7 +53,7 @@ protected override void HandleFiles(IEnumerable files) Parallel.ForEach( Classes .SelectMany(classe => Config.Tags.Intersect(classe.Tags) - .SelectMany(tag => classe.Properties.OfType() + .SelectMany(tag => classe.Properties.OfType() .SelectMany(p => GetResourceFileNames(p, tag) .Select(f => (key: (MainFilePath: GetMainResourceFilePath(tag, f.Lang), ModuleFilePath: f.FilePath, f.Lang), p))))) .GroupBy(f => f.key), @@ -71,7 +71,7 @@ protected override void HandleFiles(IEnumerable files) Parallel.ForEach( Classes .SelectMany(classe => Config.Tags.Intersect(classe.Tags) - .SelectMany(tag => classe.Properties.OfType() + .SelectMany(tag => classe.Properties.OfType() .SelectMany(p => GetCommentResourceFileNames(p, tag) .Select(f => (key: (MainFilePath: GetMainResourceFilePath(tag, f.Lang), ModuleFilePath: f.FilePath, f.Lang), p))))) .GroupBy(f => f.key), @@ -97,9 +97,9 @@ protected virtual void HandleMainResourceFile(string mainFilePath, IEnumerable<( { } - protected abstract void HandleResourceFile(string filePath, string lang, IEnumerable properties); + protected abstract void HandleResourceFile(string filePath, string lang, IEnumerable properties); - private IEnumerable<(string Lang, string FilePath)> GetCommentResourceFileNames(IFieldProperty property, string tag) + private IEnumerable<(string Lang, string FilePath)> GetCommentResourceFileNames(IProperty property, string tag) { if (Config.TranslateProperties != true) { @@ -118,7 +118,7 @@ protected virtual void HandleMainResourceFile(string mainFilePath, IEnumerable<( .Where(g => g.file != null); } - private IEnumerable<(string Lang, string FilePath)> GetResourceFileNames(IFieldProperty property, string tag) + private IEnumerable<(string Lang, string FilePath)> GetResourceFileNames(IProperty property, string tag) { if (Config.TranslateProperties != true && (Config.TranslateReferences != true || !(property.Class?.Values.Any() ?? false))) { diff --git a/TopModel.Generator.Csharp/CSharpApiClientGenerator.cs b/TopModel.Generator.Csharp/CSharpApiClientGenerator.cs index 85d6aec2..e2a4736b 100644 --- a/TopModel.Generator.Csharp/CSharpApiClientGenerator.cs +++ b/TopModel.Generator.Csharp/CSharpApiClientGenerator.cs @@ -72,9 +72,9 @@ protected override void HandleFile(string filePath, string fileName, string tag, { usings.AddRange(Config.GetDomainImports(property, tag)); - if (property is IFieldProperty fp && fp.IsQueryParam()) + if (property.IsQueryParam()) { - usings.AddRange(Config.GetValueImports(fp)); + usings.AddRange(Config.GetValueImports(property)); } switch (property) @@ -91,6 +91,9 @@ protected override void HandleFile(string filePath, string fileName, string tag, case CompositionProperty cp: usings.Add(GetNamespace(cp.Composition, tag)); break; + case AliasProperty { Property: CompositionProperty cp }: + usings.Add(GetNamespace(cp.Composition, tag)); + break; } } diff --git a/TopModel.Generator.Csharp/CSharpApiServerGenerator.cs b/TopModel.Generator.Csharp/CSharpApiServerGenerator.cs index cb1dbc2e..70660f7d 100644 --- a/TopModel.Generator.Csharp/CSharpApiServerGenerator.cs +++ b/TopModel.Generator.Csharp/CSharpApiServerGenerator.cs @@ -76,7 +76,7 @@ public class {className} : Controller wd.AppendLine($"{indent}/// {(endpoint.Returns != null ? endpoint.Returns.Comment : "Task.")}"); } - if (endpoint.Returns is IFieldProperty { Domain.MediaType: string mediaType }) + if (endpoint.Returns is { Domain.MediaType: string mediaType }) { wd.AppendLine($@"{indent}[Produces(""{mediaType}"")]"); } @@ -164,7 +164,7 @@ private string GetRoute(Endpoint endpoint) if (split[i].StartsWith('{')) { var routeParamName = split[i][1..^1]; - var param = endpoint.Params.OfType().Single(param => param.GetParamName() == routeParamName); + var param = endpoint.Params.Single(param => param.GetParamName() == routeParamName); var paramType = Config.GetType(param) switch { diff --git a/TopModel.Generator.Csharp/CSharpClassGenerator.cs b/TopModel.Generator.Csharp/CSharpClassGenerator.cs index 4e22f0bd..422c4081 100644 --- a/TopModel.Generator.Csharp/CSharpClassGenerator.cs +++ b/TopModel.Generator.Csharp/CSharpClassGenerator.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.Logging; +using System.Data; +using Microsoft.Extensions.Logging; using TopModel.Core; using TopModel.Core.Model.Implementation; using TopModel.Generator.Core; @@ -64,12 +65,11 @@ private static void GenerateEnumCols(CSharpWriter w, Class item) w.WriteLine(1, "{"); - var cols = item.Properties.OfType().ToList(); - foreach (var property in cols) + foreach (var property in item.Properties) { w.WriteSummary(2, "Nom de la colonne en base associée à la propriété " + property.NamePascal + "."); w.WriteLine(2, $"{property.SqlName},"); - if (cols.IndexOf(property) != cols.Count - 1) + if (item.Properties.IndexOf(property) != item.Properties.Count - 1) { w.WriteLine(); } @@ -210,7 +210,7 @@ private void GenerateClassDeclaration(CSharpWriter w, Class item, string tag) /// La classe générée. private void GenerateConstProperties(CSharpWriter w, Class item) { - var consts = new List<(IFieldProperty Prop, string Name, string Code, string Label)>(); + var consts = new List<(IProperty Prop, string Name, string Code, string Label)>(); foreach (var refValue in item.Values) { @@ -281,7 +281,7 @@ private void GenerateCreateMethod(CSharpWriter w, Class item) /// La classe générée. private void GenerateEnumValues(CSharpWriter w, Class item) { - bool WriteEnum(IFieldProperty prop) + bool WriteEnum(IProperty prop) { if (item.Extends != null && Config.CanClassUseEnums(item.Extends, Classes, prop)) { @@ -339,7 +339,7 @@ bool WriteEnum(IFieldProperty prop) /// Tag. private void GenerateProperties(CSharpWriter w, Class item, string tag) { - var sameColumnSet = new HashSet(item.Properties.OfType() + var sameColumnSet = new HashSet(item.Properties .GroupBy(g => g.SqlName).Where(g => g.Count() > 1).Select(g => g.Key)); foreach (var property in item.Properties.Where(p => p is not CompositionProperty cp || Classes.Contains(cp.Composition))) @@ -364,7 +364,14 @@ private void GenerateProperty(CSharpWriter w, IProperty property, HashSet c, + AliasProperty { Property: CompositionProperty c } => c, + _ => null + }; + + var type = Config.GetType(property, Classes, nonNullable: cp != null && cp.Required || property.Required && Config.RequiredNonNullable(tag)); if (!property.Class.Abstract) { @@ -400,7 +407,7 @@ private void GenerateProperty(CSharpWriter w, IProperty property, HashSet().Any(p => p.Required || p.PrimaryKey || Config.GetType(p)?.TrimEnd('?') == "string" && p.Domain.Length != null)) + if (item.Properties.Any(p => p.Required || p.PrimaryKey || Config.GetType(p)?.TrimEnd('?') == "string" && p.Domain.Length != null)) { usings.Add("System.ComponentModel.DataAnnotations"); } - if (item.Properties.OfType().Any(fp => + if (item.Properties.Any(fp => { var prop = (fp as AliasProperty)?.PersistentProperty ?? fp; return (fp.Class.IsPersistent || fp is AliasProperty { PersistentProperty: not null, As: null } && !Config.NoColumnOnAlias) @@ -486,7 +493,7 @@ private void GenerateUsings(CSharpWriter w, Class item, string tag) usings.Add("System.ComponentModel.DataAnnotations.Schema"); } - if (item.Properties.OfType().Any() && Config.Kinetix) + if (item.Properties.Any(p => p is not CompositionProperty and not AliasProperty { Property: CompositionProperty }) && Config.Kinetix) { usings.Add("Kinetix.Modeling.Annotations"); usings.Add(Config.DomainNamespace); @@ -506,11 +513,7 @@ private void GenerateUsings(CSharpWriter w, Class item, string tag) foreach (var property in item.Properties) { usings.AddRange(Config.GetDomainImports(property, tag)); - - if (property is IFieldProperty fp) - { - usings.AddRange(Config.GetValueImports(fp)); - } + usings.AddRange(Config.GetValueImports(property)); switch (property) { @@ -526,6 +529,9 @@ private void GenerateUsings(CSharpWriter w, Class item, string tag) case CompositionProperty cp when Classes.Contains(cp.Composition): usings.Add(GetNamespace(cp.Composition, tag)); break; + case AliasProperty { Property: CompositionProperty cp } when Classes.Contains(cp.Composition): + usings.Add(GetNamespace(cp.Composition, tag)); + break; } } @@ -547,22 +553,19 @@ private string GetNamespace(Class classe, string tag) return Config.GetNamespace(classe, classe.Tags.Contains(tag) ? tag : classe.Tags.Intersect(Config.Tags).FirstOrDefault() ?? tag); } - private string? GetNewableType(IProperty property) + private string? GetNewableType(CompositionProperty property) { - if (property is CompositionProperty cp) - { - var type = Config.GetType(property, nonNullable: true); - var genericType = type.Split('<').First(); + var type = Config.GetType(property, nonNullable: true); + var genericType = type.Split('<').First(); - if (cp.Domain == null) - { - return type; - } + if (property.Domain == null) + { + return type; + } - if (_newableTypes.TryGetValue(genericType, out var newableType)) - { - return type.Replace(genericType, newableType); - } + if (_newableTypes.TryGetValue(genericType, out var newableType)) + { + return type.Replace(genericType, newableType); } return null; diff --git a/TopModel.Generator.Csharp/CsharpConfig.cs b/TopModel.Generator.Csharp/CsharpConfig.cs index bba337c7..767b2c12 100644 --- a/TopModel.Generator.Csharp/CsharpConfig.cs +++ b/TopModel.Generator.Csharp/CsharpConfig.cs @@ -215,7 +215,7 @@ public class CsharpConfig : GeneratorConfigBase nameof(DataFlowsPath) ]; - public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses, IFieldProperty? prop = null) + public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses, IProperty? prop = null) { return EnumsForStaticReferences && base.CanClassUseEnums(classe, availableClasses, prop); } @@ -511,7 +511,7 @@ public string GetType(IProperty prop, IEnumerable? availableClasses = nul { var type = base.GetType(prop, availableClasses, useClassForAssociation); - if (!nonNullable && (NullableEnable || AllValueTypes.Contains(type) || prop is IFieldProperty f && GetEnumType(f, f is RegularProperty) == type)) + if (!nonNullable && (NullableEnable || AllValueTypes.Contains(type) || GetEnumType(prop, prop is RegularProperty) == type)) { type += "?"; } @@ -532,8 +532,8 @@ AssociationProperty ap when CanClassUseEnums(ap.Association, availableClasses, a AliasProperty { Property: AssociationProperty ap } when CanClassUseEnums(ap.Association, availableClasses) => true, RegularProperty { Class: not null } rp when CanClassUseEnums(rp.Class, availableClasses, rp) => true, AliasProperty { Property: RegularProperty { Class: not null } rp } when CanClassUseEnums(rp.Class, availableClasses, rp) => true, - IFieldProperty => AllValueTypes.Contains(GetType(prop, availableClasses, nonNullable: true)), - _ => false + CompositionProperty => false, + _ => AllValueTypes.Contains(GetType(prop, availableClasses, nonNullable: true)) }; } diff --git a/TopModel.Generator.Csharp/DbContextGenerator.cs b/TopModel.Generator.Csharp/DbContextGenerator.cs index 9c8e4249..93a74a61 100644 --- a/TopModel.Generator.Csharp/DbContextGenerator.cs +++ b/TopModel.Generator.Csharp/DbContextGenerator.cs @@ -55,7 +55,7 @@ protected override void HandleFile(string fileType, string fileName, string tag, } } - private IEnumerable<(IFieldProperty Property, AssociationProperty AssociationProperty)> GetAssociationProperties(IEnumerable classes, string tag) + private IEnumerable<(IProperty Property, AssociationProperty AssociationProperty)> GetAssociationProperties(IEnumerable classes, string tag) { return classes .Distinct() @@ -64,8 +64,8 @@ protected override void HandleFile(string fileType, string fileName, string tag, .Where(p => p is AssociationProperty { Association.IsPersistent: true } || p is AliasProperty { Property: AssociationProperty { Association.IsPersistent: true } }) .Select(p => p switch { - AssociationProperty ap => ((IFieldProperty)p, ap), - AliasProperty { Property: AssociationProperty ap } => ((IFieldProperty)p, ap), + AssociationProperty ap => (p, ap), + AliasProperty { Property: AssociationProperty ap } => (p, ap), _ => (null!, null!) }) .Where(p => p.ap.Type == AssociationType.ManyToOne || p.ap.Type == AssociationType.OneToOne) @@ -92,7 +92,7 @@ private void HandleCommentsFile(string fileName, string tag, string dbContextNam cw.WriteLine(2, $"var {classe.NameCamel} = modelBuilder.Entity<{classe.NamePascal}>();"); cw.WriteLine(2, $"{classe.NameCamel}.ToTable(t => t.HasComment(\"{classe.Comment.Replace("\"", "\\\"")}\"));"); - foreach (var property in classe.Properties.OfType()) + foreach (var property in classe.Properties) { cw.WriteLine(2, $"{classe.NameCamel}.Property(p => p.{property.NamePascal}).HasComment(\"{property.Comment.Replace("\"", "\\\"")}\");"); } @@ -145,7 +145,7 @@ private void HandleMainFile(string fileName, string tag, string dbContextName, s w.WriteLine(1, "{"); var hasPropConfig = false; - foreach (var fp in classes.Distinct().OrderBy(c => c.NamePascal).SelectMany(c => c.Properties.OfType())) + foreach (var fp in classes.Distinct().OrderBy(c => c.NamePascal).SelectMany(c => c.Properties)) { var prop = fp is AliasProperty alp ? alp.Property : fp; var ap = prop as AssociationProperty; diff --git a/TopModel.Generator.Csharp/MapperGenerator.cs b/TopModel.Generator.Csharp/MapperGenerator.cs index 0ed71ea5..95912b7c 100644 --- a/TopModel.Generator.Csharp/MapperGenerator.cs +++ b/TopModel.Generator.Csharp/MapperGenerator.cs @@ -47,11 +47,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla foreach (var property in fromMappers.SelectMany(fm => fm.Mapper.PropertyParams.Select(pp => pp.Property).Concat(toMappers.SelectMany(tm => tm.Mapper.MissingRequiredProperties)))) { usings.AddRange(Config.GetDomainImports(property, tag)); - - if (property is IFieldProperty fp) - { - usings.AddRange(Config.GetValueImports(fp)); - } + usings.AddRange(Config.GetValueImports(property)); switch (property) { @@ -67,6 +63,9 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla case CompositionProperty cp when Classes.Contains(cp.Composition): usings.Add(Config.GetNamespace(cp.Composition, GetBestClassTag(cp.Composition, tag))); break; + case AliasProperty { Property: CompositionProperty cp } when Classes.Contains(cp.Composition): + usings.Add(Config.GetNamespace(cp.Composition, GetBestClassTag(cp.Composition, tag))); + break; } } @@ -176,7 +175,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla var value = $"{param.Name}{(!param.Required && mapping.Key is not CompositionProperty ? "?" : string.Empty)}.{mapping.Value.NamePascal}"; - if (mapping.Key is CompositionProperty cp) + if (mapping.Key is CompositionProperty cp && mapping.Value is not CompositionProperty) { w.Write($"{(!param.Required ? $"{param.Name} is null ? null : " : string.Empty)}new() {{ {cp.CompositionPrimaryKey?.NamePascal} = "); } @@ -186,9 +185,9 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla var targetType = Config.GetType(mapping.Key, Classes, nonNullable: true); var sourceType = Config.GetType(mapping.Value, Classes, nonNullable: true); - if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType((IFieldProperty)mapping.Key).EndsWith(targetType)) + if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Key).EndsWith(targetType)) { - value = $"<{Config.GetEnumType((IFieldProperty)mapping.Key)}>({value}"; + value = $"<{Config.GetEnumType(mapping.Key)}>({value}"; if (!requiredNonNullable || !mapping.Key.Required && !mapping.Value.Required) { @@ -199,7 +198,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla value = $"Enum.Parse{value})"; } } - else if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType((IFieldProperty)mapping.Value).EndsWith(sourceType)) + else if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Value).EndsWith(sourceType)) { if (!requiredNonNullable || !mapping.Key.Required && !mapping.Value.Required) { @@ -218,7 +217,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla else if (isValueType && requiredNonNullable && mapping.Key.Required && !param.Required) { var type = Config.GetType(mapping.Value, Classes, nonNullable: true); - var enumType = Config.GetEnumType((IFieldProperty)mapping.Value); + var enumType = Config.GetEnumType(mapping.Value); var cast = enumType.Contains($".{type}") ? enumType : type; value = $"({cast}){value}"; @@ -228,12 +227,12 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla value += ".Value"; } - value = Config.GetConvertedValue(value, mapping.Value.Domain, (mapping.Key as IFieldProperty)?.Domain, isValueType && (!requiredNonNullable || !mapping.Value.Required)); + value = Config.GetConvertedValue(value, mapping.Value.Domain, mapping.Key.Domain, isValueType && (!requiredNonNullable || !mapping.Value.Required)); } w.Write(value); - if (mapping.Key is CompositionProperty) + if (mapping.Key is CompositionProperty && mapping.Value is not CompositionProperty) { w.Write(" }"); } @@ -371,7 +370,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla var sourceType = Config.GetType(mapping.Key, Classes, nonNullable: true); var targetType = Config.GetType(mapping.Value, Classes, nonNullable: true); - if (mapping.Key is IFieldProperty keyFp && !sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(keyFp).EndsWith(sourceType)) + if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Key).EndsWith(sourceType)) { if (!rrnSource || !mapping.Key.Required && !mapping.Value.Required) { @@ -382,9 +381,9 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla value = $"Enum.GetName({value})"; } } - else if (mapping.Value is IFieldProperty valueFp && !sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(valueFp).EndsWith(targetType)) + else if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Value).EndsWith(targetType)) { - value = $"<{Config.GetEnumType(valueFp)}>({value}"; + value = $"<{Config.GetEnumType(mapping.Value)}>({value}"; if (!rrnSource || !mapping.Key.Required && !mapping.Value.Required) { @@ -396,7 +395,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla } } - value = Config.GetConvertedValue(value, (mapping.Key as IFieldProperty)?.Domain, mapping.Value.Domain, isValueType && (!rrnSource || !mapping.Key.Required)); + value = Config.GetConvertedValue(value, mapping.Key.Domain, mapping.Value.Domain, isValueType && (!rrnSource || !mapping.Key.Required)); if (mapper.Class.Abstract) { @@ -489,7 +488,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla var sourceType = Config.GetType(mapping.Key, Classes, nonNullable: true); var targetType = Config.GetType(mapping.Value, Classes, nonNullable: true); - if (mapping.Key is IFieldProperty keyFp && !sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(keyFp).EndsWith(sourceType)) + if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Key).EndsWith(sourceType)) { if (!rrnSource || !mapping.Key.Required && !mapping.Value.Required) { @@ -500,9 +499,9 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla value = $"Enum.GetName({value})"; } } - else if (mapping.Value is IFieldProperty valueFp && !sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(valueFp).EndsWith(targetType)) + else if (!sourceType.EndsWith(targetType) && !targetType.EndsWith(sourceType) && Config.GetEnumType(mapping.Value).EndsWith(targetType)) { - value = $"<{Config.GetEnumType(valueFp)}>({value}"; + value = $"<{Config.GetEnumType(mapping.Value)}>({value}"; if (!rrnSource || !mapping.Key.Required && !mapping.Value.Required) { @@ -514,7 +513,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla } } - value = Config.GetConvertedValue(value, (mapping.Key as IFieldProperty)?.Domain, mapping.Value.Domain, isValueType && (!rrnSource || !mapping.Key.Required)); + value = Config.GetConvertedValue(value, mapping.Key.Domain, mapping.Value.Domain, isValueType && (!rrnSource || !mapping.Key.Required)); w.WriteLine(2, $"dest.{mapping.Value.NamePascal} = {value};"); } diff --git a/TopModel.Generator.Javascript/AngularApiClientGenerator.cs b/TopModel.Generator.Javascript/AngularApiClientGenerator.cs index de395bf8..1455acfa 100644 --- a/TopModel.Generator.Javascript/AngularApiClientGenerator.cs +++ b/TopModel.Generator.Javascript/AngularApiClientGenerator.cs @@ -166,7 +166,7 @@ private void WriteEndpoint(Endpoint endpoint, FileWriter fw) foreach (var param in endpoint.Params.Where(p => !p.IsRouteParam() && !p.IsQueryParam())) { - if (param is IFieldProperty) + if (param is not CompositionProperty) { fw.Write($@" {param.GetParamName()}"); } diff --git a/TopModel.Generator.Javascript/JavascriptApiClientGenerator.cs b/TopModel.Generator.Javascript/JavascriptApiClientGenerator.cs index f5d3236a..4b0197a2 100644 --- a/TopModel.Generator.Javascript/JavascriptApiClientGenerator.cs +++ b/TopModel.Generator.Javascript/JavascriptApiClientGenerator.cs @@ -95,7 +95,7 @@ protected override void HandleFile(string filePath, string fileName, string tag, foreach (var param in endpoint.Params.Where(p => !p.IsRouteParam() && !p.IsQueryParam())) { - if (param is IFieldProperty) + if (param is not CompositionProperty) { fw.Write(3, $@"{param.GetParamName()}"); } @@ -156,7 +156,7 @@ protected override void HandleFile(string filePath, string fileName, string tag, fw.WriteLine("}"); } - if (endpoints.Any(endpoint => endpoint.Params.Any(p => p is IFieldProperty fp && Config.GetType(fp).Contains("File")))) + if (endpoints.Any(endpoint => endpoint.Params.Any(p => p is not CompositionProperty && Config.GetType(p).Contains("File")))) { fw.WriteLine(@" function fillFormData(data: any, formData: FormData, prefix = """") { diff --git a/TopModel.Generator.Javascript/JavascriptConfig.cs b/TopModel.Generator.Javascript/JavascriptConfig.cs index 8526689c..148c6fd4 100644 --- a/TopModel.Generator.Javascript/JavascriptConfig.cs +++ b/TopModel.Generator.Javascript/JavascriptConfig.cs @@ -128,12 +128,12 @@ public string GetCommentResourcesFilePath(Namespace ns, string tag, string lang) { return endpoints.SelectMany(e => e.ClassDependencies) .Select(dep => ( - Import: dep is { Source: IFieldProperty fp } + Import: dep is { Source: IProperty fp and not CompositionProperty } ? GetEnumType(fp) : dep.Classe.NamePascal, Path: GetImportPathForClass(dep, dep.Classe.Tags.Contains(tag) ? tag : dep.Classe.Tags.Intersect(Tags).FirstOrDefault() ?? tag, tag, availableClasses)!)) .Concat(endpoints.SelectMany(d => d.Properties).SelectMany(dep => GetDomainImportPaths(fileName, dep, tag))) - .Concat(endpoints.SelectMany(d => d.Params).OfType().Where(p => p.IsQueryParam()).SelectMany(dep => GetValueImportPaths(fileName, dep))) + .Concat(endpoints.SelectMany(d => d.Params).Where(p => p.IsQueryParam()).SelectMany(dep => GetValueImportPaths(fileName, dep))) .Where(i => i.Path != null) .GroupAndSort(); } @@ -150,7 +150,7 @@ public string GetEndpointsFileName(ModelFile file, string tag) public string? GetImportPathForClass(ClassDependency dep, string targetTag, string sourceTag, IEnumerable availableClasses) { string target; - if (dep.Source is IFieldProperty) + if (dep.Source is IProperty and not CompositionProperty) { if (dep.Classe.EnumKey != null && availableClasses.Contains(dep.Classe)) { @@ -223,7 +223,7 @@ public string GetResourcesFilePath(Namespace ns, string tag, string lang) .Replace("\\", "/"); } - public IEnumerable<(string Import, string Path)> GetValueImportPaths(string fileName, IFieldProperty prop, string? value = null) + public IEnumerable<(string Import, string Path)> GetValueImportPaths(string fileName, IProperty prop, string? value = null) { return GetValueImports(prop, value) .Select(import => (Import: import.Split("/").Last(), Path: GetRelativePath(import[..import.LastIndexOf('/')], fileName))); diff --git a/TopModel.Generator.Javascript/JavascriptResourceGenerator.cs b/TopModel.Generator.Javascript/JavascriptResourceGenerator.cs index c76aa11c..60eeb749 100644 --- a/TopModel.Generator.Javascript/JavascriptResourceGenerator.cs +++ b/TopModel.Generator.Javascript/JavascriptResourceGenerator.cs @@ -24,7 +24,7 @@ public JavascriptResourceGenerator(ILogger logger, public override string Name => "JSResourceGen"; - protected override string? GetCommentResourceFilePath(IFieldProperty property, string tag, string lang) + protected override string? GetCommentResourceFilePath(IProperty property, string tag, string lang) { if (!Config.GenerateComments) { @@ -44,12 +44,12 @@ public JavascriptResourceGenerator(ILogger logger, return Config.GetMainResourceFilePath(tag, lang); } - protected override string GetResourceFilePath(IFieldProperty property, string tag, string lang) + protected override string GetResourceFilePath(IProperty property, string tag, string lang) { return Config.GetResourcesFilePath(property.Parent.Namespace, tag, lang); } - protected override void HandleCommentResourceFile(string filePath, string lang, IEnumerable properties) + protected override void HandleCommentResourceFile(string filePath, string lang, IEnumerable properties) { using var fw = new FileWriter(filePath, _logger, encoderShouldEmitUTF8Identifier: false) { EnableHeader = Config.ResourceMode == ResourceMode.JS }; @@ -97,7 +97,7 @@ protected override void HandleMainResourceFile(string mainFilePath, IEnumerable< } } - protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) + protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) { using var fw = new FileWriter(filePath, _logger, encoderShouldEmitUTF8Identifier: false) { EnableHeader = Config.ResourceMode == ResourceMode.JS }; @@ -129,7 +129,7 @@ private string Quote(string name) return Config.ResourceMode == ResourceMode.JS ? name : $@"""{name}"""; } - private void WriteClasseNode(FileWriter fw, IGrouping container, bool isComment, bool isLast, string lang, int indentLevel) + private void WriteClasseNode(FileWriter fw, IGrouping container, bool isComment, bool isLast, string lang, int indentLevel) { fw.WriteLine(indentLevel, $"{Quote(container.Key.NameCamel)}: {{"); @@ -171,7 +171,7 @@ private void WriteClasseNode(FileWriter fw, IGrouping properties, bool isComment, int level) + private void WriteSubModule(FileWriter fw, string lang, IEnumerable properties, bool isComment, int level) { var classes = properties.GroupBy(prop => prop.Parent); var modules = classes diff --git a/TopModel.Generator.Javascript/NuxtApiClientGenerator.cs b/TopModel.Generator.Javascript/NuxtApiClientGenerator.cs index dea5a69b..ab46a171 100644 --- a/TopModel.Generator.Javascript/NuxtApiClientGenerator.cs +++ b/TopModel.Generator.Javascript/NuxtApiClientGenerator.cs @@ -81,7 +81,7 @@ protected override void HandleFile(string filePath, string fileName, string tag, foreach (var param in endpoint.Params.Where(p => !p.IsRouteParam() && !p.IsQueryParam())) { - if (param is IFieldProperty) + if (param is not CompositionProperty) { fw.Write($@" {param.GetParamName()}"); } diff --git a/TopModel.Generator.Javascript/TypescriptDefinitionGenerator.cs b/TopModel.Generator.Javascript/TypescriptDefinitionGenerator.cs index 0514bc8a..32b9e5e0 100644 --- a/TopModel.Generator.Javascript/TypescriptDefinitionGenerator.cs +++ b/TopModel.Generator.Javascript/TypescriptDefinitionGenerator.cs @@ -41,22 +41,22 @@ protected override void HandleClass(string fileName, Class classe, string tag) fw.WriteLine($"import {{{string.Join(", ", GetFocusStoresImports(fileName, classe, tag).OrderBy(x => x))}}} from \"{Config.EntityTypesPath}\";"); } - if (classe.Properties.Any(c => c is IFieldProperty or CompositionProperty { Domain: not null } && !Config.IsListComposition(c))) + if (classe.Properties.Any(c => c.Domain is not null && !Config.IsListComposition(c))) { var domainImport = Config.GetRelativePath(Config.ResolveVariables(Config.DomainPath, tag), fileName); - fw.WriteLine($"import {{{string.Join(", ", classe.Properties.Select(p => p is IFieldProperty fp ? fp.Domain : p is CompositionProperty cp && !Config.IsListComposition(cp) ? cp.Domain! : null!).Where(d => d != null).OrderBy(d => d.Name).Select(d => d.Name).Distinct())}}} from \"{domainImport}\";"); + fw.WriteLine($"import {{{string.Join(", ", classe.Properties.Select(p => p is not CompositionProperty ? p.Domain : p is CompositionProperty cp && !Config.IsListComposition(cp) ? cp.Domain! : null!).Where(d => d != null).OrderBy(d => d.Name).Select(d => d.Name).Distinct())}}} from \"{domainImport}\";"); } var imports = classe.ClassDependencies .Select(dep => ( Import: dep is { Source: CompositionProperty { Domain: not null } cp } && !Config.IsListComposition(cp) ? dep.Classe.NamePascal - : dep is { Source: IFieldProperty fp } + : dep is { Source: IProperty fp and not CompositionProperty } ? Config.GetEnumType(fp) : $"{dep.Classe.NamePascal}Entity, {dep.Classe.NamePascal}{(Config.EntityMode == EntityMode.TYPED ? "EntityType" : string.Empty)}", Path: Config.GetImportPathForClass(dep, dep.Classe.Tags.Contains(tag) ? tag : dep.Classe.Tags.Intersect(Config.Tags).FirstOrDefault() ?? tag, tag, Classes)!)) .Concat(classe.Properties.SelectMany(dep => Config.GetDomainImportPaths(fileName, dep, tag))) - .Concat(classe.Properties.OfType().SelectMany(dep => Config.GetValueImportPaths(fileName, dep))) + .Concat(classe.Properties.SelectMany(dep => Config.GetValueImportPaths(fileName, dep))) .Where(p => p.Path != null && p.Path != Config.EntityTypesPath) .GroupAndSort(); @@ -184,13 +184,13 @@ protected override void HandleClass(string fileName, Class classe, string tag) fw.Write("\r\n"); - if (property is IFieldProperty field) + if (property is not CompositionProperty) { - fw.WriteLine($" name: \"{field.NameCamel}\","); - fw.WriteLine($" domain: {field.Domain.Name},"); - fw.WriteLine($" isRequired: {(field.Required && !((field.PrimaryKey || field is AliasProperty { AliasedPrimaryKey: true }) && field.Domain.AutoGeneratedValue)).ToString().ToFirstLower()},"); + fw.WriteLine($" name: \"{property.NameCamel}\","); + fw.WriteLine($" domain: {property.Domain.Name},"); + fw.WriteLine($" isRequired: {(property.Required && !((property.PrimaryKey || property is AliasProperty { AliasedPrimaryKey: true }) && property.Domain.AutoGeneratedValue)).ToString().ToFirstLower()},"); - var defaultValue = Config.GetValue(field, Classes); + var defaultValue = Config.GetValue(property, Classes); if (defaultValue != "undefined") { fw.WriteLine($" defaultValue: {defaultValue},"); @@ -198,22 +198,22 @@ protected override void HandleClass(string fileName, Class classe, string tag) if (Config.TranslateProperties == true) { - fw.WriteLine($" label: \"{field.ResourceKey}\"{(Config.GenerateComments ? "," : string.Empty)}"); + fw.WriteLine($" label: \"{property.ResourceKey}\"{(Config.GenerateComments ? "," : string.Empty)}"); } else { - fw.WriteLine($" label: \"{field.Label}\"{(Config.GenerateComments ? "," : string.Empty)}"); + fw.WriteLine($" label: \"{property.Label}\"{(Config.GenerateComments ? "," : string.Empty)}"); } if (Config.GenerateComments) { if (Config.TranslateProperties == true) { - fw.WriteLine($" comment: \"{field.CommentResourceKey}\""); + fw.WriteLine($" comment: \"{property.CommentResourceKey}\""); } else { - fw.WriteLine($" comment: \"{field.Comment}\""); + fw.WriteLine($" comment: \"{property.Comment}\""); } } } @@ -270,7 +270,7 @@ protected override void HandleClass(string fileName, Class classe, string tag) private IEnumerable GetFocusStoresImports(string fileName, Class classe, string tag) { - if (classe.Properties.Any(p => p is IFieldProperty || p is CompositionProperty { Domain: not null } && !Config.IsListComposition(p))) + if (classe.Properties.Any(p => p.Domain is not null && !Config.IsListComposition(p))) { yield return "FieldEntry2"; } diff --git a/TopModel.Generator.Javascript/TypescriptReferenceGenerator.cs b/TopModel.Generator.Javascript/TypescriptReferenceGenerator.cs index f6b17d36..1ab304a6 100644 --- a/TopModel.Generator.Javascript/TypescriptReferenceGenerator.cs +++ b/TopModel.Generator.Javascript/TypescriptReferenceGenerator.cs @@ -139,7 +139,7 @@ private void GenerateReferenceFile(string fileName, IEnumerable reference fw.Write(" {\r\n"); - foreach (var property in reference.Properties.OfType()) + foreach (var property in reference.Properties) { fw.Write(" "); fw.Write(property.NameCamel); diff --git a/TopModel.Generator.Jpa/ImportsJpaExtensions.cs b/TopModel.Generator.Jpa/ImportsJpaExtensions.cs index 39b52e17..3d7af21c 100644 --- a/TopModel.Generator.Jpa/ImportsJpaExtensions.cs +++ b/TopModel.Generator.Jpa/ImportsJpaExtensions.cs @@ -40,11 +40,33 @@ public static List GetTypeImports(this IProperty p, JpaConfig config, st { CompositionProperty cp => cp.GetTypeImports(config, tag), AssociationProperty ap => ap.GetTypeImports(config, tag), - IFieldProperty fp => fp.GetTypeImports(config, tag), - _ => new List(), + _ => p.GetRegularTypeImports(config, tag) }; } + private static List GetRegularTypeImports(this IProperty rp, JpaConfig config, string tag) + { + var imports = new List(); + + imports.AddRange(config.GetDomainImports(rp, tag)); + + if (rp is AliasProperty apo) + { + imports.AddRange(apo.GetTypeImports(config, tag)); + } + else if (rp is RegularProperty rpr) + { + imports.AddRange(rpr.GetTypeImports(config, tag)); + } + + if (rp.Class != null && config.CanClassUseEnums(rp.Class, prop: rp)) + { + imports.Add($"{config.GetEnumPackageName(rp.Class, tag)}.{config.GetEnumName(rp, rp.Class)}"); + } + + return imports; + } + private static List GetTypeImports(this AssociationProperty ap, JpaConfig config, string tag) { var imports = new List(); @@ -84,29 +106,6 @@ private static List GetTypeImports(this AliasProperty ap, JpaConfig conf return imports; } - private static List GetTypeImports(this IFieldProperty rp, JpaConfig config, string tag) - { - var imports = new List(); - - imports.AddRange(config.GetDomainImports(rp, tag)); - - if (rp is AliasProperty apo) - { - imports.AddRange(apo.GetTypeImports(config, tag)); - } - else if (rp is RegularProperty rpr) - { - imports.AddRange(rpr.GetTypeImports(config, tag)); - } - - if (rp.Class != null && config.CanClassUseEnums(rp.Class, prop: rp)) - { - imports.Add($"{config.GetEnumPackageName(rp.Class, tag)}.{config.GetEnumName(rp, rp.Class)}"); - } - - return imports; - } - private static List GetTypeImports(this RegularProperty rp, JpaConfig config, string tag) { var imports = new List(); diff --git a/TopModel.Generator.Jpa/JpaConfig.cs b/TopModel.Generator.Jpa/JpaConfig.cs index b12be3ee..18ac4ea4 100644 --- a/TopModel.Generator.Jpa/JpaConfig.cs +++ b/TopModel.Generator.Jpa/JpaConfig.cs @@ -168,7 +168,7 @@ public class JpaConfig : GeneratorConfigBase nameof(DataFlowsPath) }; - public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IFieldProperty? prop = null) + public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IProperty? prop = null) { return !UseJdbc && base.CanClassUseEnums(classe, availableClasses, prop) && !classe.Properties.OfType().Any(a => a.Association != classe && !CanClassUseEnums(a.Association, availableClasses)); @@ -214,7 +214,7 @@ public string GetDataFlowPartialFilePath(DataFlow df, string tag) $"{df.Name.ToPascalCase()}PartialFlow.java"); } - public string GetEnumFileName(IFieldProperty property, Class classe, string tag) + public string GetEnumFileName(IProperty property, Class classe, string tag) { return Path.Combine( OutputDirectory, @@ -222,7 +222,7 @@ public string GetEnumFileName(IFieldProperty property, Class classe, string tag) $"{GetEnumName(property, classe)}.java"); } - public string GetEnumName(IFieldProperty property, Class classe) + public string GetEnumName(IProperty property, Class classe) { return $"{classe.NamePascal}{property.Name.ToPascalCase()}"; } diff --git a/TopModel.Generator.Jpa/JpaEnumGenerator.cs b/TopModel.Generator.Jpa/JpaEnumGenerator.cs index a5a0c378..f1b844fc 100644 --- a/TopModel.Generator.Jpa/JpaEnumGenerator.cs +++ b/TopModel.Generator.Jpa/JpaEnumGenerator.cs @@ -28,7 +28,7 @@ protected bool FilterClass(Class classe) return !classe.Abstract && Config.CanClassUseEnums(classe, Classes.ToList()); } - protected string GetFileName(IFieldProperty property, Class classe, string tag) + protected string GetFileName(IProperty property, Class classe, string tag) { return Config.GetEnumFileName(property, classe, tag); } @@ -55,9 +55,9 @@ protected override void HandleFiles(IEnumerable files) } } - private IEnumerable GetEnumProperties(Class classe) + private IEnumerable GetEnumProperties(Class classe) { - List result = new(); + List result = new(); if (classe.EnumKey != null && Config.CanClassUseEnums(classe, prop: classe.EnumKey) && !(classe.Extends != null && Config.CanClassUseEnums(classe.Extends, Classes, prop: classe.EnumKey))) { result.Add(classe.EnumKey); @@ -68,7 +68,7 @@ private IEnumerable GetEnumProperties(Class classe) return result; } - private void WriteEnum(IFieldProperty property, Class classe, string tag) + private void WriteEnum(IProperty property, Class classe, string tag) { var packageName = Config.GetEnumPackageName(classe, tag); using var fw = new JavaWriter(Config.GetEnumFileName(property, classe, tag), _logger, packageName, null); diff --git a/TopModel.Generator.Jpa/JpaMapperGenerator.cs b/TopModel.Generator.Jpa/JpaMapperGenerator.cs index 5aaa2923..76160123 100644 --- a/TopModel.Generator.Jpa/JpaMapperGenerator.cs +++ b/TopModel.Generator.Jpa/JpaMapperGenerator.cs @@ -84,7 +84,7 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla { var getterPrefix = Config.GetType(propertyTarget!) == "boolean" ? "is" : "get"; var getter = string.Empty; - var converter = Config.GetConverter((propertySource as IFieldProperty)?.Domain, (propertyTarget as IFieldProperty)?.Domain); + var converter = Config.GetConverter(propertySource.Domain, propertyTarget.Domain); if (converter != null && Config.GetImplementation(converter) != null) { var impl = Config.GetImplementation(converter); @@ -99,8 +99,8 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla getter = $"{sourceName}.{getterPrefix}{propertySource.NamePascal.ToFirstUpper()}()"; return (Getter: Config.GetConvertedValue( getter, - (propertySource as IFieldProperty)?.Domain, - (propertyTarget as IFieldProperty)?.Domain), CheckSourceNull: false); + propertySource.Domain, + propertyTarget.Domain), CheckSourceNull: false); } var checkSourceNull = false; @@ -241,8 +241,8 @@ protected override void HandleFile(string fileName, string tag, IList<(Class Cla return (Getter: Config.GetConvertedValue( getter, - (propertySource as IFieldProperty)?.Domain, - (propertyTarget as IFieldProperty)?.Domain), CheckSourceNull: checkSourceNull); + propertySource.Domain, + propertyTarget.Domain), CheckSourceNull: checkSourceNull); } private void WriteFromMapper(Class classe, FromMapper mapper, JavaWriter fw, string tag) diff --git a/TopModel.Generator.Jpa/JpaModelConstructorGenerator.cs b/TopModel.Generator.Jpa/JpaModelConstructorGenerator.cs index 3a4556fa..834b0f22 100644 --- a/TopModel.Generator.Jpa/JpaModelConstructorGenerator.cs +++ b/TopModel.Generator.Jpa/JpaModelConstructorGenerator.cs @@ -43,8 +43,7 @@ public void WriteEnumConstructor(JavaWriter fw, Class classe, List availa { var code = refValue.Value[codeProperty]; fw.WriteLine(2, $@"case {code} :"); - foreach (var prop in classe.GetProperties(availableClasses).OfType() - .Where(p => p != codeProperty)) + foreach (var prop in classe.GetProperties(availableClasses).Where(p => p != codeProperty)) { var isString = _config.GetType(prop) == "String"; var value = refValue.Value.ContainsKey(prop) ? refValue.Value[prop] : "null"; diff --git a/TopModel.Generator.Jpa/JpaModelPropertyGenerator.cs b/TopModel.Generator.Jpa/JpaModelPropertyGenerator.cs index d4d7fde4..4e71b5bc 100644 --- a/TopModel.Generator.Jpa/JpaModelPropertyGenerator.cs +++ b/TopModel.Generator.Jpa/JpaModelPropertyGenerator.cs @@ -144,8 +144,8 @@ public void WriteProperty(JavaWriter fw, Class classe, IProperty property, strin case AliasProperty alp: WriteAliasProperty(fw, classe, alp, tag); break; - case IFieldProperty fp: - WriteIFieldProperty(fw, classe, fp, tag); + default: + WriteIFieldProperty(fw, classe, property, tag); break; } } @@ -180,7 +180,7 @@ private static void WriteValidationAnnotations(JavaWriter fw, string javaOrJakar fw.AddImport($"{javaOrJakarta}.validation.constraints.NotNull"); } - private bool ShouldWriteColumnAnnotation(Class classe, IFieldProperty property) + private bool ShouldWriteColumnAnnotation(Class classe, IProperty property) { return (classe.IsPersistent || _config.UseJdbc) && !_config.GetImplementation(property.Domain)!.Annotations .Where(i => @@ -309,7 +309,7 @@ private void WriteAssociationProperty(JavaWriter fw, Class classe, AssociationPr } fw.AddImport("org.springframework.data.relational.core.mapping.Column"); - fw.WriteLine(1, $@"@Column(""{((IFieldProperty)property).SqlName.ToLower()}"")"); + fw.WriteLine(1, $@"@Column(""{((IProperty)property).SqlName.ToLower()}"")"); fw.WriteLine(1, $"private {_config.GetType(property)} {property.NameCamel};"); } } @@ -346,7 +346,6 @@ private void WriteColumnAnnotation(JavaWriter fw, IProperty property, int indent column = @$"@Column(name = ""{property.SqlName}"", nullable = {(!property.Required).ToString().ToFirstLower()}"; if (property.Domain != null) { - if (property.Domain.Length != null) { if (_config.GetImplementation(property.Domain)?.Type?.ToUpper() == "STRING") @@ -384,7 +383,7 @@ private void WriteColumnAnnotation(JavaWriter fw, IProperty property, int indent fw.WriteLine(indentLevel, column); } - private void WriteDomainAnnotations(JavaWriter fw, IFieldProperty property, string tag, int indentLevel) + private void WriteDomainAnnotations(JavaWriter fw, IProperty property, string tag, int indentLevel) { foreach (var annotation in _config.GetDomainAnnotations(property, tag)) { @@ -392,7 +391,7 @@ private void WriteDomainAnnotations(JavaWriter fw, IFieldProperty property, stri } } - private void WriteIFieldProperty(JavaWriter fw, Class classe, IFieldProperty property, string tag) + private void WriteIFieldProperty(JavaWriter fw, Class classe, IProperty property, string tag) { var javaOrJakarta = _config.PersistenceMode.ToString().ToLower(); @@ -429,7 +428,7 @@ private void WriteIFieldProperty(JavaWriter fw, Class classe, IFieldProperty pro fw.WriteLine(1, $"private {_config.GetType(property, useClassForAssociation: useClassForAssociation)} {(isAssociationNotPersistent ? property.NameCamel : property.NameByClassCamel)}{suffix};"); } - private void WriteIdAnnotation(JavaWriter fw, Class classe, IFieldProperty property) + private void WriteIdAnnotation(JavaWriter fw, Class classe, IProperty property) { var javaOrJakarta = _config.PersistenceMode.ToString().ToLower(); if (!_config.UseJdbc) @@ -452,7 +451,7 @@ private void WriteIdAnnotation(JavaWriter fw, Class classe, IFieldProperty prope private void WriteManyToManyAnnotations(JavaWriter fw, Class classe, AssociationProperty property, int indentLevel) { var role = property.Role is not null ? "_" + property.Role.ToConstantCase() : string.Empty; - var fk = ((IFieldProperty)property).SqlName; + var fk = ((IProperty)property).SqlName; var pk = classe.PrimaryKey.Single().SqlName + role; var javaOrJakarta = _config.PersistenceMode.ToString().ToLower(); if (!_config.CanClassUseEnums(property.Association)) @@ -476,7 +475,7 @@ private void WriteManyToManyAnnotations(JavaWriter fw, Class classe, Association private void WriteManyToOneAnnotations(JavaWriter fw, AssociationProperty property, int indentLevel) { - var fk = ((IFieldProperty)property).SqlName; + var fk = ((IProperty)property).SqlName; var apk = property.Property.SqlName; var javaOrJakarta = _config.PersistenceMode.ToString().ToLower(); fw.WriteLine(indentLevel, @$"@{property.Type}(fetch = FetchType.LAZY, optional = {(property.Required ? "false" : "true")}, targetEntity = {property.Association.NamePascal}.class)"); @@ -507,7 +506,7 @@ private void WriteOneToManyAnnotations(JavaWriter fw, Class classe, AssociationP private void WriteOneToOneAnnotations(JavaWriter fw, AssociationProperty property, int indentLevel) { - var fk = ((IFieldProperty)property).SqlName; + var fk = ((IProperty)property).SqlName; var apk = property.Property.SqlName; var javaOrJakarta = _config.PersistenceMode.ToString().ToLower(); fw.AddImport($"{javaOrJakarta}.persistence.CascadeType"); diff --git a/TopModel.Generator.Jpa/JpaResourceGenerator.cs b/TopModel.Generator.Jpa/JpaResourceGenerator.cs index 1ef33517..5db6dbc5 100644 --- a/TopModel.Generator.Jpa/JpaResourceGenerator.cs +++ b/TopModel.Generator.Jpa/JpaResourceGenerator.cs @@ -23,7 +23,7 @@ public JpaResourceGenerator(ILogger logger, TranslationSto public override string Name => "JpaResourceGen"; - protected override string? GetResourceFilePath(IFieldProperty property, string tag, string lang) + protected override string? GetResourceFilePath(IProperty property, string tag, string lang) { var p = property.ResourceProperty; if (p.Label != null || (p.Class?.Values.Any() ?? false) && p.Class?.DefaultProperty != null) @@ -37,7 +37,7 @@ public JpaResourceGenerator(ILogger logger, TranslationSto return null; } - protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) + protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) { var encoding = Encoding.Latin1; if (Config.ResourcesEncoding is not null) @@ -63,7 +63,7 @@ protected override void HandleResourceFile(string filePath, string lang, IEnumer /// /// Flux de sortie. /// Classe. - private void WriteClasse(FileWriter fw, IGrouping container, string lang) + private void WriteClasse(FileWriter fw, IGrouping container, string lang) { if (Config.TranslateProperties == true) { diff --git a/TopModel.Generator.Jpa/SpringClientApiGenerator.cs b/TopModel.Generator.Jpa/SpringClientApiGenerator.cs index 24f7b5fe..3d8712c9 100644 --- a/TopModel.Generator.Jpa/SpringClientApiGenerator.cs +++ b/TopModel.Generator.Jpa/SpringClientApiGenerator.cs @@ -105,15 +105,15 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) { var accept = string.Empty; - if (endpoint.Returns != null && endpoint.Returns is IFieldProperty fp && fp.Domain.MediaType != null) + if (endpoint.Returns != null && endpoint.Returns.Domain?.MediaType != null) { - accept = @$", accept = {{ ""{fp.Domain.MediaType}"" }}"; + accept = @$", accept = {{ ""{endpoint.Returns.Domain.MediaType}"" }}"; } var contentType = string.Empty; - if (endpoint.Params.Any(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null)) + if (endpoint.Params.Any(p => p.Domain?.MediaType != null)) { - contentType = @$", contentType = {string.Join(", ", endpoint.Params.Where(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null).Select(p => $@"""{((IFieldProperty)p).Domain.MediaType}""")).First()} "; + contentType = @$", contentType = {string.Join(", ", endpoint.Params.Where(p => p.Domain?.MediaType != null).Select(p => $@"""{p.Domain.MediaType}""")).First()} "; } foreach (var annotation in Config.GetDecoratorAnnotations(endpoint, tag)) @@ -138,7 +138,7 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) foreach (var param in endpoint.GetQueryParams()) { var ann = string.Empty; - ann += @$"@RequestParam(value = ""{param.GetParamName()}"", required = {(param is not IFieldProperty fp || fp.Required).ToString().ToFirstLower()}) "; + ann += @$"@RequestParam(value = ""{param.GetParamName()}"", required = {param.Required.ToString().ToFirstLower()}) "; fw.AddImport("org.springframework.web.bind.annotation.RequestParam"); fw.AddImports(Config.GetDomainImports(param, tag)); var decoratorAnnotations = string.Join(' ', Config.GetDomainAnnotations(param, tag).Select(a => a.StartsWith("@") ? a : "@" + a)); @@ -160,7 +160,7 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) } else { - ann += @$"@RequestPart(value = ""{param.GetParamName()}"", required = {(param is not IFieldProperty fp || fp.Required).ToString().ToFirstLower()}) "; + ann += @$"@RequestPart(value = ""{param.GetParamName()}"", required = {param.Required.ToString().ToFirstLower()}) "; fw.AddImport("org.springframework.web.bind.annotation.RequestPart"); methodParams.Add($"{ann}{Config.GetType(param)} {param.GetParamName()}"); } diff --git a/TopModel.Generator.Jpa/SpringDataFlowGenerator.cs b/TopModel.Generator.Jpa/SpringDataFlowGenerator.cs index f1553ed4..c27a9b20 100644 --- a/TopModel.Generator.Jpa/SpringDataFlowGenerator.cs +++ b/TopModel.Generator.Jpa/SpringDataFlowGenerator.cs @@ -503,7 +503,7 @@ private void WriteWriterMapper(JavaWriter fw, DataFlow dataFlow, string tag) mapper = null; } - foreach (var property in dataFlow.Class.ExtendedProperties.OfType() + foreach (var property in dataFlow.Class.ExtendedProperties .Where(p => !(p is AssociationProperty ap && (ap.Type == AssociationType.OneToMany || ap.Type == AssociationType.OneToMany))) .Where(p => mapper == null || mapper.ClassParams.SelectMany(pa => pa.Mappings).Select(mapping => mapping.Key).Contains(p))) { diff --git a/TopModel.Generator.Jpa/SpringRestTemplateApiGenerator.cs b/TopModel.Generator.Jpa/SpringRestTemplateApiGenerator.cs index 233df35e..ce3896c4 100644 --- a/TopModel.Generator.Jpa/SpringRestTemplateApiGenerator.cs +++ b/TopModel.Generator.Jpa/SpringRestTemplateApiGenerator.cs @@ -255,8 +255,7 @@ private void WriteUriBuilderMethod(JavaWriter fw, Endpoint endpoint) foreach (IProperty p in endpoint.GetQueryParams()) { var indentLevel = 2; - var isRequired = p is IFieldProperty fp && fp.Required; - if (!isRequired) + if (!p.Required) { fw.WriteLine(2, @$"if ({p.GetParamName()} != null) {{"); indentLevel++; @@ -272,7 +271,7 @@ private void WriteUriBuilderMethod(JavaWriter fw, Endpoint endpoint) fw.WriteLine(indentLevel, @$"uriBuilder.queryParam(""{p.GetParamName()}"", {p.GetParamName()});"); } - if (!isRequired) + if (!p.Required) { fw.WriteLine(2, @$"}}"); fw.WriteLine(); diff --git a/TopModel.Generator.Jpa/SpringServerApiGenerator.cs b/TopModel.Generator.Jpa/SpringServerApiGenerator.cs index 24704328..4e8116a1 100644 --- a/TopModel.Generator.Jpa/SpringServerApiGenerator.cs +++ b/TopModel.Generator.Jpa/SpringServerApiGenerator.cs @@ -105,15 +105,15 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) { var produces = string.Empty; - if (endpoint.Returns != null && endpoint.Returns is IFieldProperty fp && fp.Domain.MediaType != null) + if (endpoint.Returns != null && endpoint.Returns.Domain?.MediaType != null) { - produces = @$", produces = {{ ""{fp.Domain.MediaType}"" }}"; + produces = @$", produces = {{ ""{endpoint.Returns.Domain.MediaType}"" }}"; } var consumes = string.Empty; - if (endpoint.Params.Any(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null)) + if (endpoint.Params.Any(p => p.Domain?.MediaType != null)) { - consumes = @$", consumes = {{ {string.Join(", ", endpoint.Params.Where(p => p is IFieldProperty fdp && fdp.Domain.MediaType != null).Select(p => $@"""{((IFieldProperty)p).Domain.MediaType}"""))} }}"; + consumes = @$", consumes = {{ {string.Join(", ", endpoint.Params.Where(p => p.Domain.MediaType != null).Select(p => $@"""{p.Domain.MediaType}"""))} }}"; } foreach (var annotation in Config.GetDecoratorAnnotations(endpoint, tag)) @@ -138,7 +138,7 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) foreach (var param in endpoint.GetQueryParams()) { var ann = string.Empty; - ann += @$"@RequestParam(value = ""{param.GetParamName()}"", required = {(param is not IFieldProperty fp || fp.Required).ToString().ToFirstLower()}) "; + ann += @$"@RequestParam(value = ""{param.GetParamName()}"", required = {param.Required.ToString().ToFirstLower()}) "; fw.AddImport("org.springframework.web.bind.annotation.RequestParam"); fw.AddImports(Config.GetDomainImports(param, tag)); var decoratorAnnotations = string.Join(' ', Config.GetDomainAnnotations(param, tag).Select(a => a.StartsWith("@") ? a : "@" + a)); @@ -157,7 +157,7 @@ private void WriteEndpoint(JavaWriter fw, Endpoint endpoint, string tag) } else { - ann += @$"@RequestPart(value = ""{param.GetParamName()}"", required = {(param is not IFieldProperty fp || fp.Required).ToString().ToFirstLower()}) "; + ann += @$"@RequestPart(value = ""{param.GetParamName()}"", required = {param.Required.ToString().ToFirstLower()}) "; fw.AddImport("org.springframework.web.bind.annotation.RequestPart"); } diff --git a/TopModel.Generator.Php/PhpConfig.cs b/TopModel.Generator.Php/PhpConfig.cs index 5ae362bb..984c07bb 100644 --- a/TopModel.Generator.Php/PhpConfig.cs +++ b/TopModel.Generator.Php/PhpConfig.cs @@ -39,7 +39,7 @@ public class PhpConfig : GeneratorConfigBase nameof(DtosPath), }; - public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IFieldProperty? prop = null) + public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IProperty? prop = null) { return false; } diff --git a/TopModel.Generator.Php/PhpModelGenerator.cs b/TopModel.Generator.Php/PhpModelGenerator.cs index 02bc437a..427743b1 100644 --- a/TopModel.Generator.Php/PhpModelGenerator.cs +++ b/TopModel.Generator.Php/PhpModelGenerator.cs @@ -130,8 +130,7 @@ private void WriteGetters(PhpWriter fw, Class classe) } var getterPrefix = Config.GetType(property, Classes, classe.IsPersistent) == "boolean" ? "is" : "get"; - var required = property is IFieldProperty rp && rp.Required || false; - fw.WriteLine(1, @$"public function {property.NameByClassPascal.WithPrefix(getterPrefix)}(): {Config.GetType(property, Classes, classe.IsPersistent)}{(required ? string.Empty : "|null")}"); + fw.WriteLine(1, @$"public function {property.NameByClassPascal.WithPrefix(getterPrefix)}(): {Config.GetType(property, Classes, classe.IsPersistent)}{(property.Required ? string.Empty : "|null")}"); fw.WriteLine(1, "{"); fw.WriteLine(2, @$"return $this->{property.NameByClassCamel};"); fw.WriteLine(1, "}"); diff --git a/TopModel.Generator.Php/PhpModelPropertyGenerator.cs b/TopModel.Generator.Php/PhpModelPropertyGenerator.cs index fcf49470..6282a62b 100644 --- a/TopModel.Generator.Php/PhpModelPropertyGenerator.cs +++ b/TopModel.Generator.Php/PhpModelPropertyGenerator.cs @@ -48,8 +48,8 @@ public void WriteProperty(PhpWriter fw, Class classe, IProperty property, string case AssociationProperty { Association.IsPersistent: true } ap: WriteProperty(fw, classe, ap, tag); break; - case IFieldProperty fp: - WriteProperty(fw, classe, fp, tag); + default: + WriteRegularProperty(fw, classe, property, tag); break; } } @@ -71,7 +71,7 @@ private static void WriteManyToMany(PhpWriter fw, Class classe, AssociationPrope private static void WriteManyToOne(PhpWriter fw, AssociationProperty property) { - var fk = ((IFieldProperty)property).SqlName; + var fk = ((IProperty)property).SqlName; var apk = property.Property.SqlName; fw.AddImport(@$"Doctrine\ORM\Mapping\ManyToOne"); fw.AddImport(@$"Doctrine\ORM\Mapping\JoinColumn"); @@ -87,7 +87,7 @@ private static void WriteOneToMany(PhpWriter fw, AssociationProperty property) private static void WriteOneToOne(PhpWriter fw, AssociationProperty property) { - var fk = ((IFieldProperty)property).SqlName; + var fk = ((IProperty)property).SqlName; var apk = property.Property.SqlName; fw.AddImport(@$"Doctrine\ORM\Mapping\OneToOne"); fw.AddImport(@$"Doctrine\ORM\Mapping\JoinColumn"); @@ -124,7 +124,7 @@ private void WriteProperty(PhpWriter fw, Class classe, AssociationProperty prope fw.WriteLine(1, $"private {_config.GetType(property, _classes, classe.IsPersistent)} ${property.NameByClassCamel};"); } - private void WriteProperty(PhpWriter fw, Class classe, IFieldProperty property, string tag) + private void WriteRegularProperty(PhpWriter fw, Class classe, IProperty property, string tag) { if (classe.IsPersistent) { diff --git a/TopModel.Generator.Sql/Procedural/AbstractSchemaGenerator.cs b/TopModel.Generator.Sql/Procedural/AbstractSchemaGenerator.cs index ef43543e..3fea0875 100644 --- a/TopModel.Generator.Sql/Procedural/AbstractSchemaGenerator.cs +++ b/TopModel.Generator.Sql/Procedural/AbstractSchemaGenerator.cs @@ -229,7 +229,7 @@ protected static string CheckIdentifierLength(string identifier) { var nameValueDict = new Dictionary(); var definition = initItem.Value; - foreach (var property in modelClass.Properties.OfType()) + foreach (var property in modelClass.Properties) { if (!property.PrimaryKey || !property.Domain.AutoGeneratedValue) { @@ -288,7 +288,7 @@ private void GenerateConstraintForeignKey(AssociationProperty property, SqlFileW /// Propriété destination de la contrainte. /// Association destination de la clef étrangère. /// Flux d'écriture. - private void GenerateConstraintForeignKey(IFieldProperty propertySource, IFieldProperty propertyTarget, Class association, SqlFileWriter writer) + private void GenerateConstraintForeignKey(IProperty propertySource, IProperty propertyTarget, Class association, SqlFileWriter writer) { var tableName = propertySource.Class.SqlName; var propertyName = propertySource.SqlName; @@ -312,7 +312,7 @@ private void GenerateConstraintForeignKey(IFieldProperty propertySource, IFieldP /// /// Propriété cible de l'index. /// Flux d'écriture. - private void GenerateIndexForeignKey(IFieldProperty property, SqlFileWriter writer) + private void GenerateIndexForeignKey(IProperty property, SqlFileWriter writer) { var tableName = Quote(property.Class.SqlName); var propertyName = property.SqlName; @@ -461,14 +461,14 @@ private void WriteResourceTableDeclaration(SqlFileWriter writer) private void WriteResources(SqlFileWriter writer, Class modelClass) { var hasLocale = _translationStore.Translations.Keys.Count > 1 || _translationStore.Translations.Keys.Any(a => a != string.Empty); - if (_config.TranslateProperties == true && modelClass.Properties.OfType().Where(p => p.Label != null).Count() > 0 && modelClass.ModelFile != null) + if (_config.TranslateProperties == true && modelClass.Properties.Where(p => p.Label != null).Count() > 0 && modelClass.ModelFile != null) { writer.WriteLine(); writer.WriteLine("/**\t\tInitialisation des traductions des propriétés de la table " + modelClass.SqlName + "\t\t**/"); foreach (var lang in _translationStore.Translations.Keys) { - foreach (var property in modelClass.Properties.OfType().Where(p => p.Label != null)) + foreach (var property in modelClass.Properties.Where(p => p.Label != null)) { writer.WriteLine($@"INSERT INTO {_config.ResourcesTableName}(RESOURCE_KEY{(hasLocale ? ", LOCALE" : string.Empty)}, LABEL) VALUES({SingleQuote(property.ResourceKey)}{(string.IsNullOrEmpty(lang) ? string.Empty : @$", {SingleQuote(lang)}")}, {SingleQuote(_translationStore.GetTranslation(property, lang))});"); } @@ -573,7 +573,7 @@ private IEnumerable WriteTableDeclaration(Class classe, Sql foreach (var property in properties) { - var persistentType = property is IFieldProperty ? _config.GetType(property, availableClasses) : JsonType; + var persistentType = property is not CompositionProperty ? _config.GetType(property, availableClasses) : JsonType; if (persistentType.ToLower().Equals("varchar") && property.Domain.Length != null) { @@ -673,7 +673,7 @@ private IEnumerable WriteTableDeclaration(Class classe, Sql private void WriteUniqueKeys(Class classe, SqlFileWriter? writerUk) { foreach (var uk in classe.UniqueKeys - .Concat(classe.Properties.OfType().Where(ap => ap.Type == AssociationType.OneToOne).Select(ap => new List { ap }))) + .Concat(classe.Properties.OfType().Where(ap => ap.Type == AssociationType.OneToOne).Select(ap => new List { ap }))) { writerUk?.WriteLine($"alter table {classe.SqlName} add constraint {Quote($"UK_{classe.SqlName}_{string.Join("_", uk.Select(p => p.SqlName))}")} unique ({string.Join(", ", uk.Select(p => Quote(p.SqlName)))}){BatchSeparator}"); writerUk?.WriteLine(); diff --git a/TopModel.Generator.Sql/SqlConfig.cs b/TopModel.Generator.Sql/SqlConfig.cs index 03c20b7d..d7b1d114 100644 --- a/TopModel.Generator.Sql/SqlConfig.cs +++ b/TopModel.Generator.Sql/SqlConfig.cs @@ -34,12 +34,12 @@ public class SqlConfig : GeneratorConfigBase protected override bool UseNamedEnums => false; - public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IFieldProperty? prop = null) + public override bool CanClassUseEnums(Class classe, IEnumerable? availableClasses = null, IProperty? prop = null) { return false; } - public override bool ShouldQuoteValue(IFieldProperty prop) + public override bool ShouldQuoteValue(IProperty prop) { var type = GetType(prop); return (type ?? string.Empty).Contains("varchar") diff --git a/TopModel.Generator.Sql/Ssdt/Scripter/InitReferenceListScripter.cs b/TopModel.Generator.Sql/Ssdt/Scripter/InitReferenceListScripter.cs index 04b4e73e..4fac2e01 100644 --- a/TopModel.Generator.Sql/Ssdt/Scripter/InitReferenceListScripter.cs +++ b/TopModel.Generator.Sql/Ssdt/Scripter/InitReferenceListScripter.cs @@ -87,7 +87,7 @@ private string GetInsertLine(Class modelClass, ClassValue initItem, IEnumerable< // Remplissage d'un dictionnaire nom de colonne => valeur. var definition = initItem.Value; var nameValueDict = new Dictionary(); - foreach (var property in modelClass.Properties.OfType()) + foreach (var property in modelClass.Properties) { if (!property.PrimaryKey || !property.Domain.AutoGeneratedValue) { diff --git a/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableScripter.cs b/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableScripter.cs index a33b8408..e7cb212d 100644 --- a/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableScripter.cs +++ b/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableScripter.cs @@ -146,7 +146,7 @@ private void GenerateIndexForeignKey(TextWriter writer, string tableName, IList< /// Propriété. private void WriteColumn(StringBuilder sb, IProperty property, IEnumerable availableClasses) { - var persistentType = property is IFieldProperty + var persistentType = property is not CompositionProperty ? _config.GetType(property, availableClasses) : _config.TargetDBMS == TargetDBMS.Postgre ? "jsonb" : "json"; @@ -387,7 +387,7 @@ private void WritePkLine(StringBuilder sb, Class classe, List propert private IList WriteUniqueConstraints(Class classe) { return classe.UniqueKeys - .Concat(classe.Properties.OfType().Where(ap => ap.Type == AssociationType.OneToOne).Select(ap => new List { ap })) + .Concat(classe.Properties.OfType().Where(ap => ap.Type == AssociationType.OneToOne).Select(ap => new List { ap })) .Select(uk => _config.TargetDBMS == TargetDBMS.Sqlserver ? $"constraint [UK_{classe.SqlName}_{string.Join("_", uk.Select(p => p.SqlName))}] unique nonclustered ({string.Join(", ", uk.Select(p => $"[{p.SqlName}] ASC"))})" : $"constraint UK_{classe.SqlName}_{string.Join("_", uk.Select(p => p.SqlName))} unique ({string.Join(", ", uk.Select(p => $"{p.SqlName}"))})") diff --git a/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableTypeScripter.cs b/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableTypeScripter.cs index 738127f6..5a6a9f23 100644 --- a/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableTypeScripter.cs +++ b/TopModel.Generator.Sql/Ssdt/Scripter/SqlTableTypeScripter.cs @@ -110,7 +110,7 @@ private static void WriteInsertKeyLine(StringBuilder sb, Class classe) /// /// Flux. /// Propriété. - private void WriteColumn(StringBuilder sb, IFieldProperty property) + private void WriteColumn(StringBuilder sb, IProperty property) { var persistentType = _config.GetType(property); sb.Append('[').Append(property.SqlName).Append("] ").Append(persistentType).Append(" null"); @@ -128,7 +128,7 @@ private void WriteInsideInstructions(TextWriter writer, Class table) var sb = new StringBuilder(); // Colonnes - foreach (var property in table.Properties.OfType()) + foreach (var property in table.Properties) { if ((!property.PrimaryKey || _config.ShouldQuoteValue(property)) && property.Name != ScriptUtils.InsertKeyName) { diff --git a/TopModel.Generator.Translation/TranslationOutGenerator.cs b/TopModel.Generator.Translation/TranslationOutGenerator.cs index dc9e2901..e76fe4d7 100644 --- a/TopModel.Generator.Translation/TranslationOutGenerator.cs +++ b/TopModel.Generator.Translation/TranslationOutGenerator.cs @@ -26,7 +26,7 @@ public TranslationOutGenerator(ILogger logger, ModelCon protected override bool NoLanguage => true; - protected override string? GetResourceFilePath(IFieldProperty property, string tag, string lang) + protected override string? GetResourceFilePath(IProperty property, string tag, string lang) { if (lang == _modelConfig.I18n.DefaultLang) { @@ -49,7 +49,7 @@ public TranslationOutGenerator(ILogger logger, ModelCon return null; } - protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) + protected override void HandleResourceFile(string filePath, string lang, IEnumerable properties) { using var fw = new FileWriter(filePath, _logger) { EnableHeader = false }; var containers = properties.GroupBy(prop => prop.Parent); @@ -66,7 +66,7 @@ private bool ExistsInStore(string lang, string key) && langDict.ContainsKey(key); } - private void WriteClasse(FileWriter fw, IGrouping container, string lang) + private void WriteClasse(FileWriter fw, IGrouping container, string lang) { foreach (var property in container) { diff --git a/TopModel.LanguageServer/CompletionHandler.cs b/TopModel.LanguageServer/CompletionHandler.cs index b7177f27..5a1193e8 100644 --- a/TopModel.LanguageServer/CompletionHandler.cs +++ b/TopModel.LanguageServer/CompletionHandler.cs @@ -284,7 +284,7 @@ private CompletionList CompleteProperty(CompletionParams request, string[] text, var referencedClasses = _modelStore.GetReferencedClasses(file); if (referencedClasses.TryGetValue(className, out var aliasedClass)) { - return CompleteProperty(request, aliasedClass, true, false); + return CompleteProperty(request, aliasedClass, false); } } @@ -298,7 +298,6 @@ private CompletionList CompleteProperty(CompletionParams request, string[] text, var classe = file.Classes.Find(c => c.Name == className); if (classe != null) { - var includeCompositions = false; var includeExtends = false; var selfClassropertyKeyWords = new List() @@ -308,14 +307,7 @@ private CompletionList CompleteProperty(CompletionParams request, string[] text, var isValues = false; var isMappings = false; - if (selfClassropertyKeyWords.Contains(currentKey.Key)) - { - if (currentKey.Key == "target") - { - includeCompositions = true; - } - } - else + if (!selfClassropertyKeyWords.Contains(currentKey.Key)) { var parentKey = currentKey; while (parentKey.Key != "class" && parentKey.Key != "mappings" && parentKey.Key != "values") @@ -351,7 +343,7 @@ private CompletionList CompleteProperty(CompletionParams request, string[] text, if (searchText != null && (isValues || isMappings || selfClassropertyKeyWords.Contains(currentKey.Key))) { - return CompleteProperty(request, classe, includeCompositions, includeExtends); + return CompleteProperty(request, classe, includeExtends); } } } @@ -359,14 +351,11 @@ private CompletionList CompleteProperty(CompletionParams request, string[] text, return new CompletionList(); } - private CompletionList CompleteProperty(CompletionParams request, Class classe, bool includeCompositions, bool includeExtends) + private CompletionList CompleteProperty(CompletionParams request, Class classe, bool includeExtends) { var properties = includeExtends ? classe.ExtendedProperties : classe.Properties; var searchText = GetSearchText(request); - return new CompletionList( - (includeCompositions - ? properties - : properties.Where(p => p is IFieldProperty)) + return new CompletionList(properties .Where(f => f.Name.ShouldMatch(searchText)) .Select(f => new CompletionItem { diff --git a/TopModel.UI/Graphing/Label.cs b/TopModel.UI/Graphing/Label.cs index a0c73a3c..f8ff923e 100644 --- a/TopModel.UI/Graphing/Label.cs +++ b/TopModel.UI/Graphing/Label.cs @@ -16,7 +16,7 @@ public Label(Class classe) AddRow($"{classe}"); AddRow(); - foreach (var prop in classe.Properties.OfType()) + foreach (var prop in classe.Properties) { if (prop is AssociationProperty) { diff --git a/samples/generators/angular/src/appgenerated/resources/securite.json b/samples/generators/angular/src/appgenerated/resources/securite.json index a3afc767..2a2bad56 100644 --- a/samples/generators/angular/src/appgenerated/resources/securite.json +++ b/samples/generators/angular/src/appgenerated/resources/securite.json @@ -19,6 +19,9 @@ "profilItem": { "nombreUtilisateurs": "Nombre d'utilisateurs affectés" }, + "profilRead": { + "utilisateurs": "Utilisateurs" + }, "typeDroit": { "code": "Type de droit", "libelle": "Libelle", diff --git a/samples/generators/focus/src/locale/securite.ts b/samples/generators/focus/src/locale/securite.ts index 7dc4cb1d..94489818 100644 --- a/samples/generators/focus/src/locale/securite.ts +++ b/samples/generators/focus/src/locale/securite.ts @@ -17,6 +17,9 @@ export const securite = { profilItem: { nombreUtilisateurs: "Nombre d'utilisateurs affectés" }, + profilRead: { + utilisateurs: "Utilisateurs" + }, typeDroit: { code: "Type de droit", libelle: "Libelle" diff --git a/samples/generators/jpa/src/main/resources/i18n/model/securite.properties b/samples/generators/jpa/src/main/resources/i18n/model/securite.properties index a058c51e..ebc803ce 100644 --- a/samples/generators/jpa/src/main/resources/i18n/model/securite.properties +++ b/samples/generators/jpa/src/main/resources/i18n/model/securite.properties @@ -8,6 +8,7 @@ securite.profil.profil.id=Id technique du profil securite.profil.profil.libelle=Libellé du profil securite.profil.profil.droits=Droits securite.profil.profilItem.nombreUtilisateurs=Nombre d'utilisateurs affectés +securite.profil.profilRead.utilisateurs=Utilisateurs securite.profil.typeDroit.code=Type de droit securite.profil.typeDroit.values.Read=Lecture securite.profil.typeDroit.values.Write=Ecriture diff --git a/samples/generators/php/src/Model/Securite/Profil/ProfilRead.php b/samples/generators/php/src/Model/Securite/Profil/ProfilRead.php index a55bb124..9df4fe02 100644 --- a/samples/generators/php/src/Model/Securite/Profil/ProfilRead.php +++ b/samples/generators/php/src/Model/Securite/Profil/ProfilRead.php @@ -60,7 +60,7 @@ public function getDateModification(): Date|null return $this->dateModification; } - public function getUtilisateurs(): Collection|null + public function getUtilisateurs(): Collection { return $this->utilisateurs; } diff --git a/samples/generators/translation/i18n/de_DE/out/securite_de_DE.properties b/samples/generators/translation/i18n/de_DE/out/securite_de_DE.properties index e6403a11..75b5467c 100644 --- a/samples/generators/translation/i18n/de_DE/out/securite_de_DE.properties +++ b/samples/generators/translation/i18n/de_DE/out/securite_de_DE.properties @@ -8,6 +8,7 @@ securite.profil.profil.id=Id technique du profil securite.profil.profil.libelle=Libellé du profil securite.profil.profil.droits=Droits securite.profil.profilItem.nombreUtilisateurs=Nombre d'utilisateurs affectés +securite.profil.profilRead.utilisateurs=Utilisateurs securite.profil.typeDroit.code=Type de droit securite.profil.typeDroit.values.Read=Lecture securite.profil.typeDroit.values.Write=Ecriture diff --git a/samples/generators/translation/i18n/en_US/out/securite_en_US.properties b/samples/generators/translation/i18n/en_US/out/securite_en_US.properties index e6403a11..75b5467c 100644 --- a/samples/generators/translation/i18n/en_US/out/securite_en_US.properties +++ b/samples/generators/translation/i18n/en_US/out/securite_en_US.properties @@ -8,6 +8,7 @@ securite.profil.profil.id=Id technique du profil securite.profil.profil.libelle=Libellé du profil securite.profil.profil.droits=Droits securite.profil.profilItem.nombreUtilisateurs=Nombre d'utilisateurs affectés +securite.profil.profilRead.utilisateurs=Utilisateurs securite.profil.typeDroit.code=Type de droit securite.profil.typeDroit.values.Read=Lecture securite.profil.typeDroit.values.Write=Ecriture