PostResult.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace InABox.Core
  6. {
  7. public interface IPostResult<TPostable>
  8. where TPostable : IPostable
  9. {
  10. /// <summary>
  11. /// All successful or failed <typeparamref name="TPostable"/>s.
  12. /// </summary>
  13. public IEnumerable<TPostable> PostedEntities { get; }
  14. public IEnumerable<TPostable> SuccessfulEntities => PostedEntities.Where(x => x.PostedStatus == PostedStatus.Posted);
  15. public IEnumerable<TPostable> FailedEntities => PostedEntities.Where(x => x.PostedStatus == PostedStatus.PostFailed);
  16. public IEnumerable<KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>> Fragments { get; }
  17. }
  18. public class PostResult<TPostable> : IPostResult<TPostable>
  19. where TPostable : IPostable
  20. {
  21. private List<TPostable> posts = new List<TPostable>();
  22. private Dictionary<Type, List<IPostableFragment<TPostable>>> fragments = new Dictionary<Type, List<IPostableFragment<TPostable>>>();
  23. /// <summary>
  24. /// All successful or failed <typeparamref name="TPostable"/>s.
  25. /// </summary>
  26. public IEnumerable<TPostable> PostedEntities => posts;
  27. public IEnumerable<KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>> Fragments =>
  28. fragments.Select(x => new KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>(x.Key, x.Value));
  29. public void AddSuccess(TPostable post)
  30. {
  31. post.Post();
  32. posts.Add(post);
  33. }
  34. public void AddFailed(TPostable post, string note)
  35. {
  36. post.FailPost(note);
  37. posts.Add(post);
  38. }
  39. public void AddFragment<TPostableFragment>(TPostableFragment fragment, PostedStatus status)
  40. where TPostableFragment : IPostableFragment<TPostable>, IPostable
  41. {
  42. fragment.Post();
  43. fragment.PostedStatus = status;
  44. }
  45. public void AddFragment(IPostableFragment<TPostable> fragment)
  46. {
  47. var type = fragment.GetType();
  48. if (!fragments.TryGetValue(type, out var fragmentsList))
  49. {
  50. fragmentsList = new List<IPostableFragment<TPostable>>();
  51. fragments[type] = fragmentsList;
  52. }
  53. if(fragment is IPostable postableFragment)
  54. {
  55. postableFragment.Post();
  56. }
  57. fragmentsList.Add(fragment);
  58. }
  59. }
  60. }