using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Slugify;
namespace Nitride.Slugs;
///
/// A default implementation of ISlugProvider.
///
public class SimpleSlugConverter : ISlugConverter, IEnumerable
{
private readonly List<(string, string, StringComparison)> replacements;
public SimpleSlugConverter()
{
this.replacements = new List<(string, string, StringComparison)>();
}
public SimpleSlugConverter(
IDictionary replacements,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
: this()
{
foreach (KeyValuePair pair in replacements)
{
this.Add(pair.Key, pair.Value, comparison);
}
}
///
/// Adds a replacement for the resulting slug. This is applied before the final
/// conversion
/// into a slug but after any other added replacements.
///
/// The text to search for.
/// The replacement string.
///
/// The comparison to use, defaults to invariant ignore
/// case.
///
public void Add(
string search,
string replace,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
{
this.replacements.Add((search, replace, comparison));
}
///
public IEnumerator GetEnumerator()
{
return this.replacements.Select(x => x.Item1)
.GetEnumerator();
}
///
public virtual string ToSlug(string input)
{
// If we have null or whitespace, we have a problem.
if (string.IsNullOrWhiteSpace(input))
{
throw new ArgumentException("Cannot have a blank or null input", nameof(input));
}
// We need to do the replacements before we slugify.
// Perform any additional replacements.
foreach ((string search, string replace, StringComparison comparison) in this.replacements)
{
input = input.Replace(search, replace, comparison);
}
// Create a slug.
var helper = new SlugHelper();
string output = helper.GenerateSlug(input);
return output;
}
///
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}