79 lines
2.2 KiB
C#
79 lines
2.2 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Slugify;
|
|
|
|
namespace Nitride.Slugs
|
|
{
|
|
/// <summary>
|
|
/// A default implementation of ISlugProvider.
|
|
/// </summary>
|
|
public class SimpleSlugProvider : ISlugProvider, IEnumerable<string>
|
|
{
|
|
private readonly List<(string, string)> replacements;
|
|
|
|
public SimpleSlugProvider()
|
|
{
|
|
this.replacements = new List<(string, string)>();
|
|
}
|
|
|
|
public SimpleSlugProvider(IDictionary<string, string> replacements)
|
|
: this()
|
|
{
|
|
foreach (KeyValuePair<string, string> pair in replacements)
|
|
{
|
|
this.Add(pair.Key, pair.Value);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Adds a replacement for the resulting slug.
|
|
/// </summary>
|
|
/// <param name="search">The text to search for.</param>
|
|
/// <param name="replace">The replacement string.</param>
|
|
public void Add(string search, string replace)
|
|
{
|
|
this.replacements.Add((search, replace));
|
|
}
|
|
|
|
/// <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));
|
|
}
|
|
|
|
// Create a slug..
|
|
var helper = new SlugHelper();
|
|
string output = helper.GenerateSlug(input);
|
|
|
|
// Perform any additional replacements.
|
|
foreach ((string search, string replace) in this.replacements)
|
|
{
|
|
output = output.Replace(search, replace);
|
|
}
|
|
|
|
return output;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
IEnumerator IEnumerable.GetEnumerator()
|
|
{
|
|
return this.GetEnumerator();
|
|
}
|
|
}
|
|
}
|