public class RulesCustomerRepository : ICustomerRepository
{
private readonly ICustomerRepository _customerRepository;
public RulesCustomerRepository(ICustomerRepository customerRepository)
{
if (customerRepository == null)
throw new ArgumentNullException(nameof(customerRepository));
_customerRepository = customerRepository;
}
public void Create(Customer customer)
{
if (customer == null)
throw new ArgumentNullException(nameof(customer));
if (Find(c => c.Name.Value.Equals(customer.Name.Value)).Any())
throw new Exception("A customer with this name already exists");
if (!customer.EmailAddress.IsEmpty() && Find(c => c.EmailAddress.Value.Equals(customer.EmailAddress.Value)).Any())
throw new Exception("A customer with this Email Address already exists");
_customerRepository.Create(customer);
}
public Customer Find(int id)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
return _customerRepository.Find(id);
}
public IEnumerable<Customer> Find(Func<Customer, bool> predicate)
{
if (predicate == null)
throw new ArgumentNullException(nameof(predicate));
return _customerRepository.Find(predicate);
}
public void Update(Customer customer)
{
if (customer == null)
throw new ArgumentNullException(nameof(customer));
if (Find(c => c.Name.Value.Equals(customer.Name.Value) && c.Id.Value != customer.Id.Value).Any())
throw new Exception("A customer with this name already exists");
if (!customer.EmailAddress.IsEmpty() && Find(c => c.EmailAddress.Value.Equals(customer.EmailAddress.Value) && c.Id.Value != customer.Id.Value).Any())
throw new Exception("A customer with this Email Address already exist");
_customerRepository.Update(customer);
}
public void Delete(Id id)
{
if (id <= 0)
throw new ArgumentOutOfRangeException(nameof(id));
_customerRepository.Delete(id);
}
}