| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="SlugifyTransform.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Globalization; |
| | | 9 | | using System.Text; |
| | | 10 | | using MyNet.Text.Normalization; |
| | | 11 | | |
| | | 12 | | namespace MyNet.Text.Slugification; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Converts text to a URL-friendly slug. |
| | | 16 | | /// </summary> |
| | | 17 | | public sealed class SlugifyTransform(TextSlugifierOptions options) : ITextSlugifierTransform |
| | | 18 | | { |
| | 3 | 19 | | private static readonly DiacriticsRemovalTransform DiacriticsRemoval = new(); |
| | | 20 | | |
| | | 21 | | /// <inheritdoc/> |
| | | 22 | | public string Apply(string input, CultureInfo culture) |
| | | 23 | | { |
| | 15 | 24 | | ArgumentNullException.ThrowIfNull(input); |
| | 15 | 25 | | ArgumentNullException.ThrowIfNull(culture); |
| | | 26 | | |
| | 15 | 27 | | if (string.IsNullOrWhiteSpace(input)) |
| | 0 | 28 | | return string.Empty; |
| | | 29 | | |
| | 15 | 30 | | var value = options.RemoveDiacritics ? DiacriticsRemoval.Apply(input, culture) : input; |
| | 15 | 31 | | var sb = new StringBuilder(value.Length); |
| | 15 | 32 | | var wroteSeparator = false; |
| | | 33 | | |
| | 486 | 34 | | foreach (var ch in value) |
| | | 35 | | { |
| | 228 | 36 | | if (char.IsLetterOrDigit(ch)) |
| | | 37 | | { |
| | 195 | 38 | | sb.Append(ch); |
| | 195 | 39 | | wroteSeparator = false; |
| | 195 | 40 | | continue; |
| | | 41 | | } |
| | | 42 | | |
| | 33 | 43 | | if (char.IsWhiteSpace(ch) || ch == '_' || ch == '-' || ch == '.' || ch == '/') |
| | | 44 | | { |
| | 33 | 45 | | if (sb.Length > 0 && !wroteSeparator) |
| | | 46 | | { |
| | 27 | 47 | | sb.Append(options.Separator); |
| | 27 | 48 | | wroteSeparator = true; |
| | | 49 | | } |
| | | 50 | | } |
| | | 51 | | } |
| | | 52 | | |
| | 15 | 53 | | var slug = sb.ToString().Trim(options.Separator); |
| | 15 | 54 | | return options.Lowercase ? slug.ToLower(culture) : slug; |
| | | 55 | | } |
| | | 56 | | } |
| | | 57 | | |