This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-nitride-cil/src/MfGames.Nitride.Slugs/SimpleSlugConverter.cs

88 lines
2.5 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Slugify;
namespace MfGames.Nitride.Slugs;
/// <summary>
/// A default implementation of ISlugProvider.
/// </summary>
public class SimpleSlugConverter : ISlugConverter, IEnumerable<string>
{
private readonly List<(string, string, StringComparison)> replacements;
public SimpleSlugConverter()
{
this.replacements = new List<(string, string, StringComparison)>();
}
public SimpleSlugConverter(
IDictionary<string, string> replacements,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
: this()
{
foreach (KeyValuePair<string, string> pair in replacements)
{
this.Add(pair.Key, pair.Value, comparison);
}
}
/// <summary>
/// Adds a replacement for the resulting slug. This is applied before the final
/// conversion
/// into a slug but after any other added replacements.
/// </summary>
/// <param name="search">The text to search for.</param>
/// <param name="replace">The replacement string.</param>
/// <param name="comparison">
/// The comparison to use, defaults to invariant ignore
/// case.
/// </param>
public void Add(
string search,
string replace,
StringComparison comparison = StringComparison.InvariantCultureIgnoreCase)
{
this.replacements.Add((search, replace, comparison));
}
/// <inheritdoc />
public IEnumerator<string> GetEnumerator()
{
return this.replacements.Select(x => x.Item1)
.GetEnumerator();
}
/// <inheritdoc />
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;
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}