2010-01-15 23:44:22 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text.RegularExpressions;
|
2010-01-20 01:19:16 +00:00
|
|
|
|
using Orchard.Core.Common.Models;
|
2010-01-15 23:44:22 +00:00
|
|
|
|
|
|
|
|
|
namespace Orchard.Core.Common.Services {
|
|
|
|
|
public class RoutableService : IRoutableService {
|
2010-01-20 01:19:16 +00:00
|
|
|
|
public void FillSlug<TModel>(TModel model) where TModel : RoutableAspect {
|
|
|
|
|
if (!string.IsNullOrEmpty(model.Slug) || string.IsNullOrEmpty(model.Title))
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
var slug = model.Title;
|
|
|
|
|
var dissallowed = new Regex(@"[/:?#\[\]@!$&'()*+,;=\s]+");
|
|
|
|
|
|
|
|
|
|
slug = dissallowed.Replace(slug, "-");
|
|
|
|
|
slug = slug.Trim('-');
|
|
|
|
|
|
|
|
|
|
if (slug.Length > 1000)
|
|
|
|
|
slug = slug.Substring(0, 1000);
|
|
|
|
|
|
|
|
|
|
model.Slug = slug;
|
2010-01-15 23:44:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
2010-01-20 01:19:16 +00:00
|
|
|
|
public void FillSlug<TModel>(TModel model, Func<string, string> generateSlug) where TModel : RoutableAspect {
|
|
|
|
|
if (!string.IsNullOrEmpty(model.Slug) || string.IsNullOrEmpty(model.Title))
|
|
|
|
|
return;
|
|
|
|
|
|
|
|
|
|
model.Slug = generateSlug(model.Title);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2010-01-15 23:44:22 +00:00
|
|
|
|
public string GenerateUniqueSlug(string slugCandidate, IEnumerable<string> existingSlugs) {
|
|
|
|
|
int? version = existingSlugs
|
|
|
|
|
.Select(s => {
|
|
|
|
|
int v;
|
|
|
|
|
string[] slugParts = s.Split(new[] { slugCandidate }, StringSplitOptions.RemoveEmptyEntries);
|
|
|
|
|
if (slugParts.Length == 0) {
|
2010-01-20 01:19:16 +00:00
|
|
|
|
return 2;
|
2010-01-15 23:44:22 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return int.TryParse(slugParts[0].TrimStart('-'), out v)
|
|
|
|
|
? (int?) ++v
|
|
|
|
|
: null;
|
|
|
|
|
})
|
|
|
|
|
.OrderBy(i => i)
|
|
|
|
|
.LastOrDefault();
|
|
|
|
|
|
|
|
|
|
return version != null
|
|
|
|
|
? string.Format("{0}-{1}", slugCandidate, version)
|
|
|
|
|
: slugCandidate;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|