PIbd-22-Ismailov_SUBD/BlogDataModels/BusinessLogic/UserLogic.cs

117 lines
3.3 KiB
C#
Raw Normal View History

2023-09-06 22:02:39 +04:00
using BlogContracts.BindingModels;
using BlogContracts.BusinessLogicContracts;
using BlogContracts.SearchModels;
using BlogContracts.StoragesContracts;
using BlogContracts.ViewModels;
2023-09-06 20:52:08 +04:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2023-09-06 22:02:39 +04:00
namespace BlogBusinessLogic
2023-09-06 20:52:08 +04:00
{
public class UserLogic : IUserLogic
{
private readonly IUserStorage _userStorage;
public UserLogic(IUserStorage userStorage)
{
_userStorage = userStorage;
}
public bool Create(UserBindingModel model)
{
CheckModel(model);
if (_userStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(UserBindingModel model)
{
CheckModel(model, false);
if (_userStorage.Delete(model) == null)
{
return false;
}
return true;
}
public UserViewModel? ReadElement(UserSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _userStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<UserViewModel>? ReadList(UserSearchModel? model)
{
var list = model == null ? _userStorage.GetFullList() : _userStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(UserBindingModel model)
{
CheckModel(model);
if (_userStorage.Update(model) == null)
{
return false;
}
return true;
}
public void UserInsertList(int num, List<RoleViewModel> roles)
{
_userStorage.UserInsertList(num, roles);
}
private void CheckModel(UserBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Username))
{
throw new ArgumentNullException("Нет имени пользователя", nameof(model.Username));
}
if (string.IsNullOrEmpty(model.Email))
{
throw new ArgumentNullException("Нет почты", nameof(model.Email));
}
if (string.IsNullOrEmpty(model.Password))
{
throw new ArgumentNullException("Нет пароля", nameof(model.Password));
}
var element = _userStorage.GetElement(new UserSearchModel
{
Username = model.Username,
Email = model.Email,
}
);
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Пользователь с такими данными уже есть");
}
}
}
}