コード例 #1
0
ファイル: TextFormatter.cs プロジェクト: kaleyroy/Cirqus
        public void Format(string template, object @event)
        {
            template = template ?? @event.GetType().Name;

            foreach (var match in new Regex(@"\{[^\}]\}+").Matches(template).OfType <Match>())
            {
            }

            var extras = new Dictionary <string, object>();
            var unused = new Dictionary <string, string>();

            var metaProperty = @event.GetType().GetProperty("Meta", typeof(Metadata));

            if (metaProperty != null)
            {
                var metadata = (Metadata)metaProperty.GetValue(@event);
                if (metadata.ContainsKey(DomainEvent.MetadataKeys.AggregateRootId))
                {
                    extras.Add("Id", metadata[DomainEvent.MetadataKeys.AggregateRootId]);
                }
            }

            var result = template;

            foreach (var property in extras
                     .Select(property => new { Name = property.Key, property.Value })
                     .Concat(@event.GetType()
                             .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(x => x.Name != "Meta")
                             .Select(property => new { property.Name, Value = property.GetValue(@event) })))
            {
                var placeholder = "{" + property.Name + "}";
                var value       = property.Value != null?property.Value.ToString() : "null";

                if (result.Contains(placeholder))
                {
                    result = result.Replace(placeholder, value);
                }
                else
                {
                    unused.Add(property.Name, value);
                }
            }

            formatter.Write(result);

            if (!unused.Any())
            {
                return;
            }

            formatter.NewLine();
            formatter.Indent();
            foreach (KeyValuePair <string, string> pair in unused)
            {
                formatter.Write(pair.Key + ": " + pair.Value);
            }
            formatter.Unindent();
        }