Skip to content

Commit

Permalink
feat: implement TryGetFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
elementh committed Aug 4, 2021
1 parent 739837a commit 1502532
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
8 changes: 8 additions & 0 deletions src/Thankifi.Common.Filters.Abstractions/IFilterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,14 @@ public interface IFilterService
/// <param name="identifier">The identifier of the <see cref="IFilter"/>.</param>
/// <returns>A instance of the <see cref="IFilter"/></returns>
IFilter? GetFilterOrDefault(string identifier);

/// <summary>
/// Try to get a filter given a identifier.
/// </summary>
/// <param name="identifier">The identifier of the <see cref="IFilter"/>.</param>
/// <param name="filter">A reference to store the <see cref="IFilter"/>.</param>
/// <returns>A instance of the <see cref="IFilter"/></returns>
bool TryGetFilter(string identifier, out IFilter filter);

/// <summary>
/// Applies a filter to a string given a filter identifier and an input string.
Expand Down
18 changes: 13 additions & 5 deletions src/Thankifi.Common.Filters/FilterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,17 +50,25 @@ public IFilter GetFilter(string identifier)
return Filters.FirstOrDefault(f => f.Identifier == identifier);
}

/// <inheritdoc />
public bool TryGetFilter(string identifier, out IFilter filter)
{
filter = Filters.FirstOrDefault(f => f.Identifier == identifier);

return filter is not null;
}

/// <inheritdoc />
public async Task<string> Apply(string identifier, string str, CancellationToken cancellationToken = default)
{
var selectedFilter = Filters.FirstOrDefault(f => f.Identifier == identifier);
var filter = Filters.FirstOrDefault(f => f.Identifier == identifier);

if (selectedFilter is null)
if (filter is null)
{
throw new InvalidFilterException();
}

return await selectedFilter.Apply(str, cancellationToken).ConfigureAwait(false);
return await filter.Apply(str, cancellationToken).ConfigureAwait(false);
}

/// <inheritdoc />
Expand All @@ -81,7 +89,7 @@ public async Task<string> Apply(IEnumerable<string> identifiers, string str, Can
{
foreach (var filter in identifiers)
{
str = await Apply(filter, str, cancellationToken);
str = await Apply(filter, str, cancellationToken).ConfigureAwait(false);
}

return str;
Expand All @@ -92,7 +100,7 @@ public async Task<string> Apply(IEnumerable<string> identifiers, string str, Can
{
foreach (var filter in identifiers)
{
var filtered = await ApplyOrDefault(filter, str, cancellationToken);
var filtered = await ApplyOrDefault(filter, str, cancellationToken).ConfigureAwait(false);

if (filtered is not null)
{
Expand Down

0 comments on commit 1502532

Please sign in to comment.