-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathEnsureCommandValidatorsFollowNamingConvention.cs
More file actions
76 lines (62 loc) · 2.8 KB
/
EnsureCommandValidatorsFollowNamingConvention.cs
File metadata and controls
76 lines (62 loc) · 2.8 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
namespace LeanCode.CodeAnalysis.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class EnsureCommandValidatorsFollowNamingConvention : DiagnosticAnalyzer
{
private const string ValidatorTypeName = "FluentValidation.IValidator`1";
private const string CommandTypeName = "LeanCode.Contracts.ICommand";
private const string ExpectedSuffix = "CV";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
DiagnosticsIds.CommandValidatorsShouldFollowNamingConvention,
"Validators should follow naming convention",
"`{0}` does not follow `{1}` naming convention",
"Cqrs",
DiagnosticSeverity.Warning,
true
);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(
GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics
);
context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.ClassDeclaration);
}
private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
var type = (INamedTypeSymbol)context.ContainingSymbol!;
if (TryGetCommandValidator(type, out var commandValidator))
{
var expectedName = GetCommandValidatorExpectedName(commandValidator!);
if (type.Name != expectedName)
{
var diagnostic = Diagnostic.Create(Rule, type.Locations[0], type.Name, expectedName);
context.ReportDiagnostic(diagnostic);
}
}
}
internal static string GetCommandValidatorExpectedName(INamedTypeSymbol commandValidator)
{
return commandValidator.TypeArguments.First().Name + ExpectedSuffix;
}
internal static INamedTypeSymbol? GetImplementedValidator(INamedTypeSymbol type)
{
return type.AllInterfaces.FirstOrDefault(interfaceSymbol =>
interfaceSymbol.GetFullNamespaceName() == ValidatorTypeName
);
}
private static bool TryGetCommandValidator(INamedTypeSymbol type, out INamedTypeSymbol? commandValidator)
{
var validator = GetImplementedValidator(type);
var isCommandValidator = validator
?.TypeArguments.First()
.AllInterfaces.Any(i => i.GetFullNamespaceName() == CommandTypeName);
commandValidator = isCommandValidator == true ? validator : null;
return type.TypeKind != TypeKind.Interface && !type.IsAbstract && commandValidator != null;
}
}