-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathParameterlessConstructorRule.cs
More file actions
45 lines (38 loc) · 1.31 KB
/
ParameterlessConstructorRule.cs
File metadata and controls
45 lines (38 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace CSharpFunctionalExtensions.HttpResults.Generators.Rules;
internal class ParameterlessConstructorRule : IRule
{
public DiagnosticDescriptor RuleDescriptor { get; } =
new(
"CFEHTTPR004",
"Missing parameterless constructor in IResultErrorMapper",
"Class '{0}' does not have a parameterless constructor",
"Mapping",
DiagnosticSeverity.Error,
true,
customTags: ["CompilationEnd"]
);
public IEnumerable<Diagnostic> Check(List<ClassDeclarationSyntax> mapperClasses)
{
foreach (var mapperClass in mapperClasses)
{
if (!HasParameterlessConstructor(mapperClass))
yield return Diagnostic.Create(
RuleDescriptor,
mapperClass.Identifier.GetLocation(),
mapperClass.Identifier.Text
);
}
}
private static bool HasParameterlessConstructor(ClassDeclarationSyntax classDeclaration)
{
var hasExplicitParameterless = classDeclaration
.Members.OfType<ConstructorDeclarationSyntax>()
.Any(c => c.ParameterList.Parameters.Count == 0);
if (hasExplicitParameterless)
return true;
var hasAnyConstructors = classDeclaration.Members.OfType<ConstructorDeclarationSyntax>().Any();
return !hasAnyConstructors;
}
}