PostResult.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. var type = fragment.GetType();
  43. if (!fragments.TryGetValue(type, out var fragmentsList))
  44. {
  45. fragmentsList = new List<IPostableFragment<TPostable>>();
  46. fragments[type] = fragmentsList;
  47. }
  48. fragment.Post();
  49. fragment.PostedStatus = status;
  50. fragmentsList.Add(fragment);
  51. }
  52. public void AddFragment(IPostableFragment<TPostable> fragment)
  53. {
  54. var type = fragment.GetType();
  55. if (!fragments.TryGetValue(type, out var fragmentsList))
  56. {
  57. fragmentsList = new List<IPostableFragment<TPostable>>();
  58. fragments[type] = fragmentsList;
  59. }
  60. if(fragment is IPostable postableFragment)
  61. {
  62. postableFragment.Post();
  63. }
  64. fragmentsList.Add(fragment);
  65. }
  66. }
  67. }