Jelajahi Sumber

Make factory method self-contained in another handler type

Tigran 4 tahun lalu
induk
melakukan
e09fc8d8e5

+ 27 - 2
MafiaTelegramBot/Commands/CallbackQueries/CallbackQueryHandler.cs

@@ -1,12 +1,17 @@
 #nullable enable
+using System;
 using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
 
 namespace MafiaTelegramBot.Commands.CallbackQueries
 {
     public class CallbackQueryHandler : UpdateHandler
     {
-        protected override List<UpdateHandler> List => new()
+        private static IEnumerable<UpdateHandler> List => new List<UpdateHandler>
         {
             // Переносим обработку сообщений в другой класс, если игрок находится в комнате
             new UserInGameCallbackQueryHandler(null),
@@ -43,7 +48,27 @@ namespace MafiaTelegramBot.Commands.CallbackQueries
             new SwitchTimerCallbackQueryHandler(null),
             new UnblockUserCallbackQueryHandler(null),
         };
-
+        
+        public static async Task<UpdateHandler> Factory(User user, string message)
+        {
+            // Объект пользователя
+            var player = await UserDao.GetPlayerById(user.Id) ?? await UserDao.AddNew(user);
+            
+            // Если игрок заблокирован, то нафиг его
+            if (player.Info.IsBlocked) return new CallbackQueryHandler(player);
+            
+            // Устанавливаем игроку время активности на текущее
+            player.SetActive();
+            
+            // Возвращаем объект, если есть подходящая команда
+            foreach (var item in List.Where(item => item.IsMatches(message)))
+                if (Activator.CreateInstance(item.GetType(), player) is CallbackQueryHandler handler)
+                    if(handler.IsMatches(message)) return handler;
+            
+            // Ничего не делаем, если код дошел до сюда
+            return new CommandNotFound(player, message);
+        }
+        
         public CallbackQueryHandler(Player player) : base(player) { }
     }
 }

+ 25 - 2
MafiaTelegramBot/Commands/ChannelPost/ChannelPost.cs

@@ -1,8 +1,11 @@
 #nullable enable
+using System;
 using System.Collections.Generic;
+using System.Linq;
 using System.Threading.Tasks;
 using System.Timers;
 using MafiaTelegramBot.Controllers;
+using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
 using Telegram.Bot.Types;
 
@@ -10,7 +13,7 @@ namespace MafiaTelegramBot.Commands.ChannelPost
 {
     public class ChannelPost : UpdateHandler
     {
-        protected override List<UpdateHandler> List => new()
+        private static IEnumerable<UpdateHandler> List => new List<UpdateHandler>
         {
             new GiveawayChannelPost(null),
         };
@@ -29,7 +32,27 @@ namespace MafiaTelegramBot.Commands.ChannelPost
             timer.Start();
             return error;
         }
+        
+        public static async Task<UpdateHandler> Factory(User user, string message)
+        {
+            // Объект пользователя
+            var player = await UserDao.GetPlayerById(user.Id) ?? await UserDao.AddNew(user);
+            
+            // Если игрок заблокирован, то нафиг его
+            if (player.Info.IsBlocked) return new ChannelPost(player);
+            
+            // Устанавливаем игроку время активности на текущее
+            player.SetActive();
+            
+            // Возвращаем объект, если есть подходящая команда
+            foreach (var item in List.Where(item => item.IsMatches(message)))
+                if (Activator.CreateInstance(item.GetType(), player) is ChannelPost handler)
+                    if(handler.IsMatches(message)) return handler;
+            
+            // Ничего не делаем, если код дошел до сюда
+            return new ChannelPost(player);
+        }
 
-        public ChannelPost(Player player) : base(player) { }
+        protected ChannelPost(Player player) : base(player) { }
     }
 }

+ 27 - 2
MafiaTelegramBot/Commands/Messages/MessageHandler.cs

@@ -1,11 +1,16 @@
+using System;
 using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using MafiaTelegramBot.DataBase.EntityDao;
 using MafiaTelegramBot.Game;
+using Telegram.Bot.Types;
 
 namespace MafiaTelegramBot.Commands.Messages
 {
     public class MessageHandler : UpdateHandler
     {
-        protected override List<UpdateHandler> List => new()
+        private static IEnumerable<UpdateHandler> List => new List<UpdateHandler>
         {
             // Переносим обработку сообщений в другой класс, если игрок находится в комнате
             new UserInGameMessageHandler(null),
@@ -31,7 +36,27 @@ namespace MafiaTelegramBot.Commands.Messages
             new StartMessageHandler(null),
             new StartGameMessageHandler(null),
         };
+        
+        public static async Task<UpdateHandler> Factory(User user, string message)
+        {
+            // Объект пользователя
+            var player = await UserDao.GetPlayerById(user.Id) ?? await UserDao.AddNew(user);
+            
+            // Если игрок заблокирован, то нафиг его
+            if (player.Info.IsBlocked) return new MessageHandler(player);
+            
+            // Устанавливаем игроку время активности на текущее
+            player.SetActive();
+            
+            // Возвращаем объект, если есть подходящая команда
+            foreach (var item in List.Where(item => item.IsMatches(message)))
+                if (Activator.CreateInstance(item.GetType(), player) is MessageHandler handler)
+                    if(handler.IsMatches(message)) return handler;
+            
+            // Возвращаем команда не найдена, если код дошел до сюда
+            return new CommandNotFound(player, message);
+        }
 
-        public MessageHandler(Player player) : base(player) { }
+        protected MessageHandler(Player player) : base(player) { }
     }
 }

+ 0 - 25
MafiaTelegramBot/Commands/UpdateHandler.cs

@@ -10,8 +10,6 @@ namespace MafiaTelegramBot.Commands
     public class UpdateHandler
     {
         protected virtual string Command => "";
-
-        protected virtual List<UpdateHandler> List { get; } = new();
         
         protected Player User { get; }
         
@@ -19,29 +17,6 @@ namespace MafiaTelegramBot.Commands
 
         public virtual bool IsMatches(string command) { return command.Contains(Command); }
 
-        public static async Task<UpdateHandler> Factory(User user, string message, UpdateHandler caller)
-        {
-            // Объект пользователя
-            var player = await UserDao.GetPlayerById(user.Id) ?? await UserDao.AddNew(user);
-            
-            // Если игрок заблокирован, то нафиг его
-            if (player.Info.IsBlocked) return new UpdateHandler(player);
-            
-            // Устанавливаем игроку время активности на текущее
-            player.SetActive();
-
-            var list = caller.List;
-            
-            // Возвращаем объект, если есть подходящая команда
-            foreach (var item in list)
-                if(item.IsMatches(message))
-                    if (Activator.CreateInstance(item.GetType(), player) is UpdateHandler handler)
-                        if(handler.IsMatches(message)) return handler;
-            
-            // Возвращаем команда не найдена, если код дошел до сюда
-            return new CommandNotFound(player, message);
-        }
-
         protected UpdateHandler(Player player) { User = player; }
         
         public UpdateHandler() { }

+ 3 - 3
MafiaTelegramBot/Controllers/MessageController.cs

@@ -40,11 +40,11 @@ namespace MafiaTelegramBot.Controllers
                 var handler = update.Type switch
                 {
                     UpdateType.Message =>
-                        await UpdateHandler.Factory(update.Message.From, update.Message.Text, new MessageHandler(null)),
+                        await MessageHandler.Factory(update.Message.From, update.Message.Text),
                     UpdateType.CallbackQuery =>
-                        await UpdateHandler.Factory(update.CallbackQuery.From, update.CallbackQuery.Data, new CallbackQueryHandler(null)),
+                        await CallbackQueryHandler.Factory(update.CallbackQuery.From, update.CallbackQuery.Data),
                     UpdateType.ChannelPost =>
-                        await UpdateHandler.Factory(ChatToUser(update.ChannelPost.Chat), update.ChannelPost.Text, new ChannelPost(null)),
+                        await ChannelPost.Factory(ChatToUser(update.ChannelPost.Chat), update.ChannelPost.Text),
                     UpdateType.MyChatMember => await MyChatMemberHandler.Factory(ChatToUser(update.MyChatMember.Chat)),
                     _ => await UnknownUpdateHandlerAsync(update)
                 };