public static MethodBuilder AddMethod(this ClassBuilder builder, string name) { MethodBuilder methodBuilder = MethodBuilder.New().SetName(name); builder.AddMethod(methodBuilder); return(methodBuilder); }
private static MethodBuilder BuildEqualsMethod( string typeName, IReadOnlyList <PropertyDescriptor> properties) { const string other = nameof(other); ConditionBuilder equalCondition = ConditionBuilder .New() .SetReturn() .SetDetermineStatement(); if (properties.Count == 0) { equalCondition.And("true"); } else { foreach (PropertyDescriptor property in properties) { equalCondition.And(ConditionBuilder .New() .Set(BuildPropertyComparison(property.Type, property.Name))); } } return(MethodBuilder .New() .SetName(nameof(IEquatable <object> .Equals)) .SetPublic() .SetInheritance(Inheritance.Virtual) .SetReturnType(TypeNames.Boolean) .AddParameter(other, x => x.SetType(typeName.MakeNullable())) .AddCode(CodeBlockBuilder .New() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("null") .AddArgument(other)) .AddCode("return false;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("this") .AddArgument(other)) .AddCode("return true;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition($"{other}.GetType() != GetType()") .AddCode("return false;")) .AddEmptyLine() .AddCode(equalCondition))); }
private void AddDeserializeMethod( ClassBuilder classBuilder, ResultParserDeserializerMethodDescriptor methodDescriptor, string indent) { ImmutableQueue <ResultTypeComponentDescriptor> runtimeTypeComponents = ImmutableQueue.CreateRange <ResultTypeComponentDescriptor>( methodDescriptor.RuntimeTypeComponents); classBuilder.AddMethod( MethodBuilder.New() .SetAccessModifier(AccessModifier.Private) .SetInheritance(Inheritance.Override) .SetReturnType( $"{methodDescriptor.RuntimeType}?", IsNullable(methodDescriptor.RuntimeTypeComponents)) .SetReturnType( $"{methodDescriptor.RuntimeType}", !IsNullable(methodDescriptor.RuntimeTypeComponents)) .SetName(methodDescriptor.Name) .AddParameter(ParameterBuilder.New() .SetType(Types.JsonElement) .SetName("obj")) .AddParameter(ParameterBuilder.New() .SetType("string") .SetName("field")) .AddCode(CreateDeserializeMethodBody( methodDescriptor, runtimeTypeComponents, indent))); }
private void AddBuildMethod( InterfaceTypeDescriptor resultNamedType, ClassBuilder classBuilder) { var responseParameterName = "response"; var buildMethod = MethodBuilder .New() .SetAccessModifier(AccessModifier.Public) .SetName("Build") .SetReturnType( TypeReferenceBuilder.New() .SetName(TypeNames.IOperationResult) .AddGeneric(resultNamedType.RuntimeType.Name)) .AddParameter( ParameterBuilder.New() .SetType( TypeReferenceBuilder.New() .SetName(TypeNames.Response) .AddGeneric(TypeNames.JsonDocument) .SetName(TypeNames.Response)) .SetName(responseParameterName)); var concreteResultType = CreateResultInfoName(resultNamedType.ImplementedBy.First().RuntimeType.Name); buildMethod.AddCode( AssignmentBuilder.New() .SetLefthandSide( $"({resultNamedType.RuntimeType.Name} Result, {concreteResultType} " + "Info)? data") .SetRighthandSide("null")); buildMethod.AddEmptyLine(); buildMethod.AddCode( IfBuilder.New() .SetCondition( ConditionBuilder.New() .Set("response.Body is not null") .And("response.Body.RootElement.TryGetProperty(\"data\"," + $" out {TypeNames.JsonElement} obj)")) .AddCode("data = BuildData(obj);")); buildMethod.AddEmptyLine(); buildMethod.AddCode( MethodCallBuilder.New() .SetPrefix("return new ") .SetMethodName( TypeNames.OperationResult.WithGeneric(resultNamedType.RuntimeType.Name)) .AddArgument("data?.Result") .AddArgument("data?.Info") .AddArgument(_resultDataFactoryFieldName) .AddArgument("null")); classBuilder.AddMethod(buildMethod); }
protected override void Generate( CodeWriter writer, EntityIdFactoryDescriptor descriptor, out string fileName) { fileName = descriptor.Name; var factory = ClassBuilder .New() .SetStatic() .SetAccessModifier(AccessModifier.Public) .SetName(fileName); var obj = ParameterBuilder .New() .SetName("obj") .SetType(TypeNames.JsonElement); var type = ParameterBuilder .New() .SetName("type") .SetType(TypeNames.String); var createEntityId = MethodBuilder .New() .SetStatic() .SetAccessModifier(AccessModifier.Public) .SetName("CreateEntityId") .SetReturnType(TypeNames.EntityId) .AddParameter(obj) .AddCode(CreateEntityIdBody(descriptor)); factory.AddMethod(createEntityId); foreach (var entity in descriptor.Entities) { var createSpecificEntityId = MethodBuilder .New() .SetStatic() .SetAccessModifier(AccessModifier.Private) .SetName($"Create{entity.Name}EntityId") .SetReturnType(TypeNames.EntityId) .AddParameter(obj) .AddParameter(type) .AddCode(CreateSpecificEntityIdBody(entity)); factory.AddMethod(createSpecificEntityId); } CodeFileBuilder .New() .SetNamespace(descriptor.Namespace) .AddType(factory) .Build(writer); }
public static ClassBuilder AddMethod( this ClassBuilder builder, string name, Action <MethodBuilder> configure) { MethodBuilder methodBuilder = MethodBuilder.New().SetName(name); configure(methodBuilder); builder.AddMethod(methodBuilder); return(builder); }
private static void AddToStringMethod( ClassBuilder classBuilder, string originalDocument) { classBuilder .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetInheritance(Inheritance.Override) .SetReturnType("string") .SetName("ToString") .AddCode(CreateToStringBody(originalDocument))); }
public static MethodBuilder AddMethod(this ClassBuilder builder, string?name = null) { MethodBuilder methodBuilder = MethodBuilder.New(); if (name is not null) { methodBuilder.SetName(name); } builder.AddMethod(methodBuilder); return(methodBuilder); }
private void AddInitializeMethod( IReadOnlyList <ValueSerializerDescriptor> serializerDescriptors, ClassBuilder builder) { builder .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetName("Initialize") .AddParameter(ParameterBuilder.New() .SetType(Types.IValueSerializerCollection) .SetName("serializerResolver")) .AddCode(CreateInitializeBody(serializerDescriptors, CodeWriter.Indent))); }
private void AddDeserializeMethod(ClassBuilder builder) { builder .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType("object?", NullableRefTypes) .SetReturnType("object", !NullableRefTypes) .SetName("Deserialize") .AddParameter(ParameterBuilder.New() .SetType("object?", NullableRefTypes) .SetType("object", !NullableRefTypes) .SetName("serialized")) .AddCode(CreateDeserializeBody(CodeWriter.Indent))); }
private static void AddGetVariableValues( ClassBuilder classBuilder, IReadOnlyList <OperationArgumentDescriptor> arguments, string indent) { MethodBuilder methodBuilder = MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType( "global::System.Collections.Generic.IReadOnlyList<" + "global::StrawberryShake.VariableValue>") .SetName("GetVariableValues") .AddCode(CreateGetVariableValuesBody(arguments, indent)); classBuilder.AddMethod(methodBuilder); }
private static MethodBuilder BuildGetHashCodeMethod( IReadOnlyList <PropertyDescriptor> properties) { const string obj = nameof(obj); return(MethodBuilder .New() .SetName(nameof(GetHashCode)) .SetPublic() .SetOverride() .SetReturnType(TypeNames.Int32) .AddCode(HashCodeBuilder .New() .AddProperties(properties))); }
public async Task CreateMethod() { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await MethodBuilder.New() .SetName("GetAbc") .AddCode(CodeLineBuilder.New().SetLine("return;")) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot(); }
private void AddSerializeMethod( InputModelSerializerDescriptor descriptor, ClassBuilder builder) { builder .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType("object?", NullableRefTypes) .SetReturnType("object", !NullableRefTypes) .SetName("Serialize") .AddParameter(ParameterBuilder.New() .SetType("object?", NullableRefTypes) .SetType("object", !NullableRefTypes) .SetName("value")) .AddCode(CreateSerializeBody(descriptor, CodeWriter.Indent))); }
public async Task CreateMethod_With_Two_Parameter() { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await MethodBuilder.New() .SetName("GetAbc") .AddCode(CodeLineBuilder.New().SetLine("return;")) .AddParameter(ParameterBuilder.New().SetName("abc").SetType("String")) .AddParameter(ParameterBuilder.New().SetName("def").SetType("String").SetDefault()) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot(); }
public async Task CreateExtensionMethod() { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await MethodBuilder.New() .SetName("GetAbc") .SetStatic() .AddParameter(ParameterBuilder.New().SetName("abc").SetType("this String")) .AddCode(CodeLineBuilder.New().SetLine("return;")) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot(); }
public async Task CreateMethod_With_AccessModifier(AccessModifier accessModifier) { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await MethodBuilder.New() .SetName("GetAbc") .SetAccessModifier(accessModifier) .AddCode(CodeLineBuilder.New().SetLine("return;")) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot( new SnapshotNameExtension( accessModifier.ToString())); }
private static void AddAddClientMethod( ClassBuilder builder, DependencyInjectionDescriptor descriptor, string indent) { builder.AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetStatic() .SetReturnType( "global::StrawberryShake.Configuration.IOperationClientBuilder") .SetName($"Add{descriptor.ClientName}") .AddParameter(ParameterBuilder.New() .SetType( "this global::Microsoft.Extensions.DependencyInjection." + "IServiceCollection") .SetName("serviceCollection")) .AddCode(CreateAddClientBody(descriptor, indent))); }
private void AddTypeSerializerMethods( IReadOnlyList <InputTypeSerializerMethodDescriptor> descriptors, ClassBuilder builder) { foreach (InputTypeSerializerMethodDescriptor descriptor in descriptors) { builder .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Private) .SetName(descriptor.Name) .SetReturnType("object?", NullableRefTypes) .SetReturnType("object", !NullableRefTypes) .AddParameter(ParameterBuilder.New() .SetName("value") .SetType("object?", NullableRefTypes) .SetType("object", !NullableRefTypes)) .AddCode(CreateTypeSerializeBody(descriptor, CodeWriter.Indent))); } }
private void AddParseMethod( ClassBuilder classBuilder, ResultParserMethodDescriptor methodDescriptor, string indent) { classBuilder.AddMethod( MethodBuilder.New() .SetAccessModifier(AccessModifier.Private) .SetInheritance(Inheritance.Override) .SetReturnType( $"{methodDescriptor.ResultType}?", IsNullable(methodDescriptor.ResultType.Components)) .SetReturnType( $"{methodDescriptor.ResultType}", !IsNullable(methodDescriptor.ResultType.Components)) .SetName(methodDescriptor.Name) .AddParameter(ParameterBuilder.New() .SetType(Types.JsonElement) .SetName("parent")) .AddCode(CreateParseMethodBody(methodDescriptor, indent))); }
private void AddDeserializeMethod( ITypeDescriptor typeReference, ClassBuilder classBuilder, HashSet <string> processed) { string methodName = DeserializerMethodNameFromTypeName(typeReference); if (processed.Add(methodName)) { var returnType = typeReference.ToEntityIdBuilder(); var methodBuilder = MethodBuilder.New() .SetAccessModifier(AccessModifier.Private) .SetName(methodName) .SetReturnType(returnType) .AddParameter( ParameterBuilder.New() .SetType(_jsonElementParamName) .SetName(_objParamName)); if (typeReference.IsEntityType() || typeReference.ContainsEntity()) { methodBuilder.AddParameter( ParameterBuilder.New() .SetType($"{TypeNames.ISet}<{TypeNames.EntityId}>") .SetName(_entityIdsParam)); } methodBuilder.AddCode( EnsureProperNullability(isNonNullType: typeReference.IsNonNullableType())); classBuilder.AddMethod(methodBuilder); AddDeserializeMethodBody( classBuilder, methodBuilder, typeReference, processed); } }
private static MethodBuilder BuildObjectEqualsMethod(string typeName) { const string obj = nameof(obj); return(MethodBuilder .New() .SetName(nameof(IEquatable <object> .Equals)) .SetPublic() .SetOverride() .SetReturnType(TypeNames.Boolean) .AddParameter(obj, x => x.SetType(TypeNames.Object.MakeNullable())) .AddCode(CodeBlockBuilder .New() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("null") .AddArgument(obj)) .AddCode("return false;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition(MethodCallBuilder .Inline() .SetMethodName(nameof(ReferenceEquals)) .AddArgument("this") .AddArgument(obj)) .AddCode("return true;")) .AddEmptyLine() .AddCode(IfBuilder .New() .SetCondition($"{obj}.GetType() != GetType()") .AddCode("return false;")) .AddEmptyLine() .AddLine($"return Equals(({typeName}){obj});"))); }
public async Task Class_With_Field_Constructor_Property_Method() { // arrange var sb = new StringBuilder(); var writer = new CodeWriter(sb); // act await ClassBuilder.New() .SetName("MyClass") .AddImplements("SomeOtherType") .SetAbstract() .AddField(FieldBuilder.New() .SetName("_foo") .SetType("Bar") .SetReadOnly()) .AddProperty( PropertyBuilder.New() .SetName("Foo") .SetType("Bar") .SetBackingField("_foo")) .AddConstructor(ConstructorBuilder.New() .SetAccessModifier(AccessModifier.Protected) .AddParameter(ParameterBuilder.New() .SetName("foo") .SetType("Bar") .SetDefault()) .AddCode("_foo = foo;")) .AddMethod(MethodBuilder.New() .SetName("GetFooAsync") .SetReturnType("ValueTask<Bar>") .AddCode("return new ValueTask<Bar>(_foo);")) .BuildAsync(writer); // assert sb.ToString().MatchSnapshot(); }
protected override void Generate( CodeWriter writer, OperationDescriptor descriptor, out string fileName) { var(classBuilder, constructorBuilder) = CreateClassBuilder(); fileName = CreateDocumentTypeName(descriptor.Name); classBuilder .AddImplements(TypeNames.IDocument) .SetName(fileName); constructorBuilder.SetAccessModifier(AccessModifier.Private); classBuilder.AddField( FieldBuilder.New() .SetStatic() .SetConst() .SetType(TypeNames.String) .SetName("_bodyString") .SetValue($"@\"{descriptor.BodyString}\"", true)); classBuilder.AddField( FieldBuilder.New() .SetStatic() .SetReadOnly() .SetType("byte[]") .SetName("_body") .SetValue($"{TypeNames.EncodingUtf8}.GetBytes(_bodyString)")); string operationKind; switch (descriptor) { case MutationOperationDescriptor mutationOperationDescriptor: operationKind = "Mutation"; break; case QueryOperationDescriptor queryOperationDescriptor: operationKind = "Query"; break; case SubscriptionOperationDescriptor subscriptionOperationDescriptor: operationKind = "Subscription"; break; default: throw new ArgumentOutOfRangeException(nameof(descriptor)); } classBuilder.AddProperty( PropertyBuilder.New() .SetStatic() .SetType(fileName) .SetName("Instance") .SetValue($"new {fileName}()")); classBuilder.AddProperty( PropertyBuilder.New() .SetType(TypeNames.OperationKind) .SetName("Kind").AsLambda($"{TypeNames.OperationKind}.{operationKind}")); classBuilder.AddProperty( PropertyBuilder.New() .SetType($"{TypeNames.IReadOnlySpan}<byte>") .SetName("Body").AsLambda("_body")); classBuilder.AddMethod( MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType("override string") .SetName("ToString") .AddCode("return _bodyString;")); CodeFileBuilder .New() .SetNamespace(descriptor.Namespace) .AddType(classBuilder) .Build(writer); }
private void AddBuildDataMethod( NamedTypeDescriptor resultNamedType, ClassBuilder classBuilder) { var objParameter = "obj"; var buildDataMethod = MethodBuilder.New() .SetAccessModifier(AccessModifier.Private) .SetName("BuildData") .SetReturnType( $"({resultNamedType.Name}, " + $"{ResultInfoNameFromTypeName(resultNamedType.ImplementedBy[0].Name)})") .AddParameter( ParameterBuilder.New() .SetType(TypeNames.JsonElement) .SetName(objParameter)); var sessionName = "session"; buildDataMethod.AddCode( CodeLineBuilder.New() .SetLine( CodeBlockBuilder.New() .AddCode( $"using {TypeNames.IEntityUpdateSession} {sessionName} = ") .AddCode(_entityStoreFieldName + ".BeginUpdate();"))); var entityIdsName = "entityIds"; buildDataMethod.AddCode( CodeLineBuilder.New() .SetLine( $"var {entityIdsName} = new {TypeNames.HashSet}<{TypeNames.EntityId}>();")); buildDataMethod.AddEmptyLine(); foreach (PropertyDescriptor property in resultNamedType.Properties.Where(prop => prop.Type.IsEntityType())) { buildDataMethod.AddCode( AssignmentBuilder.New() .SetLefthandSide(CodeBlockBuilder.New() .AddCode(property.Type.ToEntityIdBuilder()) .AddCode($"{property.Name.WithLowerFirstChar()}Id")) .SetRighthandSide(BuildUpdateMethodCall(property, ""))); } var resultInfoConstructor = MethodCallBuilder.New() .SetMethodName( $"new {ResultInfoNameFromTypeName(resultNamedType.ImplementedBy[0].Name)}") .SetDetermineStatement(false); foreach (PropertyDescriptor property in resultNamedType.Properties) { if (property.Type.IsEntityType()) { resultInfoConstructor.AddArgument($"{property.Name.WithLowerFirstChar()}Id"); } else { resultInfoConstructor.AddArgument(BuildUpdateMethodCall(property, "")); } } resultInfoConstructor.AddArgument(entityIdsName); resultInfoConstructor.AddArgument( $"{sessionName}.{TypeNames.IEntityUpdateSession_Version}"); buildDataMethod.AddEmptyLine(); var resultInfoName = "resultInfo"; buildDataMethod.AddCode( AssignmentBuilder.New() .SetLefthandSide($"var {resultInfoName}") .SetRighthandSide(resultInfoConstructor)); buildDataMethod.AddEmptyLine(); buildDataMethod.AddCode( $"return ({_resultDataFactoryFieldName}" + $".Create({resultInfoName}), {resultInfoName});"); classBuilder.AddMethod(buildDataMethod); }
protected override Task WriteAsync( CodeWriter writer, EnumValueSerializerDescriptor descriptor) { if (writer is null) { throw new ArgumentNullException(nameof(writer)); } if (descriptor is null) { throw new ArgumentNullException(nameof(descriptor)); } return(ClassBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetSealed() .SetName(descriptor.Name) .AddImplements("global::StrawberryShake.IValueSerializer") .AddProperty(PropertyBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetType("string") .SetName("Name") .SetGetter(CodeLineBuilder.New() .SetLine($"return \"{descriptor.EnumGraphQLTypeName}\";"))) .AddProperty(PropertyBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetType("global::StrawberryShake.ValueKind") .SetName("Kind") .SetGetter(CodeLineBuilder.New() .SetLine($"return global::StrawberryShake.ValueKind.Enum;"))) .AddProperty(PropertyBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetType("global::System.Type") .SetName("ClrType") .SetGetter(CodeLineBuilder.New() .SetLine($"return typeof({descriptor.EnumTypeName});"))) .AddProperty(PropertyBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetType("global::System.Type") .SetName("SerializationType") .SetGetter(CodeLineBuilder.New() .SetLine($"return typeof(string);"))) .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType("object?", NullableRefTypes) .SetReturnType("object", !NullableRefTypes) .SetName("Serialize") .AddParameter(ParameterBuilder.New() .SetType("object?", NullableRefTypes) .SetType("object", !NullableRefTypes) .SetName("value")) .AddCode(CreateSerializerMethodBody(descriptor, CodeWriter.Indent))) .AddMethod(MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetReturnType("object?", NullableRefTypes) .SetReturnType("object", !NullableRefTypes) .SetName("Deserialize") .AddParameter(ParameterBuilder.New() .SetType("object?", NullableRefTypes) .SetType("object", !NullableRefTypes) .SetName("serialized")) .AddCode(CreateDeserializerMethodBody(descriptor, CodeWriter.Indent))) .BuildAsync(writer)); }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName) { var(classBuilder, constructorBuilder) = CreateClassBuilder(false); NamedTypeDescriptor descriptor = (NamedTypeDescriptor)typeDescriptor.NamedType(); // Setup class fileName = descriptor.ExtractMapperName(); classBuilder .AddImplements( TypeNames.IEntityMapper .WithGeneric(descriptor.ExtractTypeName(), descriptor.Name)) .SetName(fileName); constructorBuilder.SetTypeName(descriptor.Name); if (descriptor.ContainsEntity()) { AddConstructorAssignedField( TypeNames.IEntityStore, StoreFieldName, classBuilder, constructorBuilder); } // Define map method MethodBuilder mapMethod = MethodBuilder.New() .SetName(_mapMethodName) .SetAccessModifier(AccessModifier.Public) .SetReturnType(descriptor.Name) .AddParameter( ParameterBuilder.New() .SetType( descriptor.Kind == TypeKind.EntityType ? EntityTypeNameFromGraphQLTypeName(descriptor.GraphQLTypeName) : descriptor.Name) .SetName(_entityParamName)); var constructorCall = MethodCallBuilder .New() .SetMethodName($"return new {descriptor.Name}"); if (typeDescriptor is NamedTypeDescriptor namedTypeDescriptor) { foreach (PropertyDescriptor property in namedTypeDescriptor.Properties) { constructorCall.AddArgument(BuildMapMethodCall(_entityParamName, property)); } } mapMethod.AddCode(constructorCall); if (constructorBuilder.HasParameters()) { classBuilder.AddConstructor(constructorBuilder); } classBuilder.AddMethod(mapMethod); var processed = new HashSet <string>(); AddRequiredMapMethods( _entityParamName, descriptor, classBuilder, constructorBuilder, processed); CodeFileBuilder .New() .SetNamespace(descriptor.Namespace) .AddType(classBuilder) .Build(writer); }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName) { ComplexTypeDescriptor descriptor = typeDescriptor as ComplexTypeDescriptor ?? throw new InvalidOperationException( "A result data factory can only be generated for complex types"); var(classBuilder, constructorBuilder) = CreateClassBuilder(); fileName = CreateResultFactoryName(descriptor.RuntimeType.Name); classBuilder .SetName(fileName) .AddImplements( // TODO: This should be descriptor.RuntimeType! $"{TypeNames.IOperationResultDataFactory}<{descriptor.RuntimeType.Name}>"); constructorBuilder .SetTypeName(descriptor.Name) .SetAccessModifier(AccessModifier.Public); AddConstructorAssignedField( TypeNames.IEntityStore, StoreParamName, classBuilder, constructorBuilder); var createMethod = MethodBuilder.New() .SetAccessModifier(AccessModifier.Public) .SetName("Create") .SetReturnType(descriptor.RuntimeType.Name) .AddParameter("dataInfo", b => b.SetType(TypeNames.IOperationResultDataInfo)); var returnStatement = MethodCallBuilder.New() .SetPrefix("return new ") .SetMethodName(descriptor.RuntimeType.Name); var ifHasCorrectType = IfBuilder.New() .SetCondition( $"dataInfo is {CreateResultInfoName(descriptor.RuntimeType.Name)} info"); foreach (PropertyDescriptor property in descriptor.Properties) { returnStatement.AddArgument( BuildMapMethodCall( "info", property)); } ifHasCorrectType.AddCode(returnStatement); createMethod.AddCode(ifHasCorrectType); createMethod.AddEmptyLine(); createMethod.AddCode( $"throw new {TypeNames.ArgumentException}(\"" + $"{CreateResultInfoName(descriptor.RuntimeType.Name)} expected.\");"); classBuilder.AddMethod(createMethod); var processed = new HashSet <string>(); AddRequiredMapMethods( "info", descriptor, classBuilder, constructorBuilder, processed, true); CodeFileBuilder .New() .SetNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal) .AddType(classBuilder) .Build(writer); }
protected override void Generate( CodeWriter writer, ITypeDescriptor typeDescriptor, out string fileName) { var(classBuilder, constructorBuilder) = CreateClassBuilder(false); ComplexTypeDescriptor descriptor = typeDescriptor as ComplexTypeDescriptor ?? throw new InvalidOperationException( "A result entity mapper can only be generated for complex types"); // Setup class fileName = descriptor.ExtractMapperName(); classBuilder .AddImplements( TypeNames.IEntityMapper .WithGeneric(descriptor.ExtractTypeName(), descriptor.RuntimeType.Name)) .SetName(fileName); constructorBuilder.SetTypeName(descriptor.Name); if (descriptor.ContainsEntity()) { AddConstructorAssignedField( TypeNames.IEntityStore, StoreFieldName, classBuilder, constructorBuilder); } // Define map method MethodBuilder mapMethod = MethodBuilder.New() .SetName(_mapMethodName) .SetAccessModifier(AccessModifier.Public) .SetReturnType(descriptor.RuntimeType.Name) .AddParameter( ParameterBuilder.New() .SetType( descriptor.Kind == TypeKind.EntityType ? CreateEntityTypeName(descriptor.Name) : descriptor.Name) .SetName(_entityParamName)); var constructorCall = MethodCallBuilder .New() .SetMethodName($"return new {descriptor.RuntimeType.Name}"); if (typeDescriptor is ComplexTypeDescriptor complexTypeDescriptor) { foreach (PropertyDescriptor property in complexTypeDescriptor.Properties) { constructorCall.AddArgument(BuildMapMethodCall(_entityParamName, property)); } } mapMethod.AddCode(constructorCall); if (constructorBuilder.HasParameters()) { classBuilder.AddConstructor(constructorBuilder); } classBuilder.AddMethod(mapMethod); AddRequiredMapMethods( _entityParamName, descriptor, classBuilder, constructorBuilder, new HashSet <string>()); CodeFileBuilder .New() .SetNamespace(descriptor.RuntimeType.NamespaceWithoutGlobal) .AddType(classBuilder) .Build(writer); }