Exemplo n.º 1
0
        private static IDictionary <int, MessageValidationRule> GetRules(Func <string, string>?modifier = null)
        {
            var rulesText = ReadSection(0).Select(modifier ?? (s => s))
                            .ToArray();

            return(MessageValidationRule.ReadRules(rulesText));
        }
        private ValidateResult[] Validate(MessageValidationRule rule, string message, int position)
        {
            if (position >= message.Length)
            {
                return(Array.Empty <ValidateResult>());
            }

            if (rule is MatchMessageValidationRule matchRule)
            {
                var isValid = matchRule.Value == message[position];
                return(isValid
                           ? new[] { new ValidateResult(true, 1) }
                           : Array.Empty <ValidateResult>());
            }

            if (rule is CompositeMessageValidationRule compositeRule)
            {
                var allValidChildResults = new List <ValidateResult>();

                foreach (var ruleSet in compositeRule.ChildRuleSets)
                {
                    var previous = new List <ValidateResult> {
                        new ValidateResult(true, 0)
                    };
                    foreach (var childRule in ruleSet)
                    {
                        previous = previous.SelectMany(
                            p => Validate(childRule, message, position + p.Consumed)
                            .Where(r => r.IsValid)
                            .Select(r => new ValidateResult(true, r.Consumed + p.Consumed)))
                                   .ToList();
                    }

                    allValidChildResults.AddRange(previous);
                }

                return(allValidChildResults.ToArray());
            }

            throw new ArgumentException($"Unrecognised rule type: {rule.GetType().Name}");
        }