Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

NopCssMinifier.cs

using Nop.Core.Infrastructure;
using Nop.Services.Logging;
using NUglify;
using NUglify.Css;
using WebOptimizer;

namespace Nop.Web.Framework.WebOptimizer.Processors;

/// 
/// Represents a class of processor that handle style assets
/// 
/// Implementation has taken from WebOptimizer to add logging
public partial class NopCssMinifier : Processor
{
    #region Methods

    /// 
    /// Executes the processor on the specified configuration.
    /// 
    /// The context used to perform processing to WebOptimizer.IAsset instances
    public override async Task ExecuteAsync(IAssetContext context)
    {
        var content = new Dictionary();

        foreach (var key in context.Content.Keys)
        {
            if (key.EndsWith(".min.css", StringComparison.InvariantCultureIgnoreCase))
            {
                content[key] = context.Content[key];
                continue;
            }

            var input = context.Content[key].AsString();
            var result = Uglify.Css(input, new CssSettings());

            var minified = result.Code;

            if (result.HasErrors)
            {
                await EngineContext.Current.Resolve()
                    .WarningAsync($"Stylesheet minification: {key}", new(string.Join(Environment.NewLine, result.Errors)));
            }

            content[key] = minified.AsByteArray();
        }

        context.Content = content;

        return;
    }

    #endregion

}