PHPackages                             tobento/service-minify - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. tobento/service-minify

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

tobento/service-minify
======================

A lightweight and extensible PHP service for minifying CSS, JavaScript, and HTML.

2.0(2mo ago)042MITPHPPHP &gt;=8.4

Since Feb 25Pushed 2mo agoCompare

[ Source](https://github.com/tobento-ch/service-minify)[ Packagist](https://packagist.org/packages/tobento/service-minify)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-service-minify/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (2)

Minify Service
==============

[](#minify-service)

The **Minify Service** provides a flexible and extensible way to minify [CSS](#css-minifier), [HTML](#html-minifier), and [JavaScript](#javascript-minifier) content.
It is built around small, composable [Modifiers](#available-modifiers) that can be combined to create highly optimized minifiers tailored to your needs.

The service is designed to be framework-agnostic and works seamlessly in any PHP application.

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Highlights
----------

[](#highlights)

- Framework-agnostic, works with any project
- Decoupled design for maximum flexibility

Table of Contents
-----------------

[](#table-of-contents)

- [Getting started](#getting-started)
    - [Requirements](#requirements)
    - [Highlights](#highlights)
- [Documentation](#documentation)
    - [Basic Usage](#basic-usage)
    - [Available Minifiers](#available-minifiers)
        - [CSS Minifier](#css-minifier)
        - [HTML Minifier](#html-minifier)
        - [JavaScript Minifier](#javascript-minifier)
        - [Null Minifier](#null-minifier)
    - [Available Modifiers](#available-modifiers)
        - [CSS Modifiers](#css-modifiers)
            - [Charsets CSS Modifier](#charsets-css-modifier)
            - [Colors CSS Modifier](#colors-css-modifier)
            - [Comments CSS Modifier](#comments-css-modifier)
            - [Font Weights CSS Modifier](#font-weights-css-modifier)
            - [Leading Zero CSS Modifier](#leading-zero-css-modifier)
            - [Quotes CSS Modifier](#quotes-css-modifier)
            - [Semicolons CSS Modifier](#semicolons-css-modifier)
            - [Whitespaces CSS Modifier](#whitespaces-css-modifier)
            - [Zero Units CSS Modifier](#zero-units-css-modifier)
            - [Zero Values CSS Modifier](#zero-values-css-modifier)
        - [HTML Modifiers](#html-modifiers)
            - [Attributes HTML Modifier](#charsets-html-modifier)
            - [Comments HTML Modifier](#comments-html-modifier)
            - [Doctype HTML Modifier](#doctype-html-modifier)
            - [Whitespaces HTML Modifier](#whitespaces-html-modifier)
        - [JavaScript Modifiers](#javascript-modifiers)
            - [Comments JS Modifier](#comments-js-modifier)
            - [Whitespaces JS Modifier](#whitespaces-js-modifier)
        - [Generic Modifiers](#generic-modifiers)
            - [Callable Modifier](#callable-modifier)
        - [Custom Modifier](#custom-modifier)
    - [Factories](#factories)
        - [CSS Minifier Factory](#css-minifier-factory)
        - [HTML Minifier Factory](#html-minifier-factory)
        - [JavaScript Minifier Factory](#javascript-minifier-factory)
        - [Null Minifier Factory](#null-minifier-factory)
    - [Minifiers](#minifiers)
- [Credits](#credits)

---

Getting started
===============

[](#getting-started)

Add the latest version of the minify project running this command.

```
composer require tobento/service-minify

```

Requirements
------------

[](#requirements-1)

- PHP 8.4 or above

Documentation
=============

[](#documentation)

Basic Usage
-----------

[](#basic-usage)

The recommended way to create a minifier is by using one of the built-in [factories](#factories).
[Factories](#factories) provide sensible defaults and allow you to easily enable or disable specific [modifiers](#available-modifiers).

```
use Tobento\Service\Minify\Factory\CssMinifierFactory;

// Create a CSS minifier with all default modifiers
$minifier = new CssMinifierFactory()->createMinifier();

$minified = $minifier->minify($css);
```

You may customize the minifier by adding or removing modifiers:

```
use Tobento\Service\Minify\Factory\CssMinifierFactory;

$factory = new CssMinifierFactory()
    // exclude built-in modifiers by key
    ->except('comments')

    // or use only the specified built‑in modifiers
    ->only('leading-zero')

    // append a custom modifier instance
    ->addModifier(new MyCustomModifier())

    // or prepend one to run it before all others
    ->prependModifier(new MyCustomModifier());

$minifier = $factory->createMinifier();
```

If you prefer full manual control, you may still create a minifier directly by passing a Modifiers collection:

```
use Tobento\Service\Minify\Minifier;
use Tobento\Service\Minify\Modifier;

$minifier = new Minifier\Css(
    new Modifier\Modifiers(
        new Modifier\Css\Comments(),
        new Modifier\Css\Colors(),
        new Modifier\Css\Whitespaces(),
    )
);

$minified = $minifier->minify($css);
```

Each [minifier](#available-minifiers) accepts a [modifiers](#available-modifiers) collection, giving you full control over the minification pipeline.
If you need a minifier that performs no changes, you may use the [Null Minifier](#null-minifier).

Available Minifiers
-------------------

[](#available-minifiers)

### CSS Minifier

[](#css-minifier)

The CSS minifier applies a sequence of CSS-specific modifiers to optimize and compress stylesheet content.

```
use Tobento\Service\Minify\CssMinifierInterface;
use Tobento\Service\Minify\Minifier;
use Tobento\Service\Minify\MinifierInterface;
use Tobento\Service\Minify\Modifier;

$minifier = new Minifier\Css(
    new Modifier\Modifiers(
        new Modifier\Css\Charsets(),      // handles @charset; typically placed early
        new Modifier\Css\Comments(),      // remove comments early
        new Modifier\Css\Colors(),        // normalize color values
        new Modifier\Css\FontWeights(),   // normalize named weights
        new Modifier\Css\Quotes(),        // remove unnecessary quotes
        new Modifier\Css\Semicolons(),    // remove trailing semicolons
        new Modifier\Css\LeadingZero(),   // 0.5 → .5
        new Modifier\Css\ZeroUnits(),     // 0px → 0
        new Modifier\Css\ZeroValues(),    // .0 → 0
        new Modifier\Css\Whitespaces(),   // final cleanup
    )
);

var_dump($minifier instanceof CssMinifierInterface);
// bool(true)

var_dump($minifier instanceof MinifierInterface);
// bool(true)

// Minifying CSS
$minified = $minifier->minify($css);
```

A full list of available modifiers can be found under the [CSS Modifiers](#css-modifiers) section.

### HTML Minifier

[](#html-minifier)

The HTML minifier applies a sequence of HTML-specific modifiers to reduce markup size while preserving the original structure and meaning.

```
use Tobento\Service\Minify\HtmlMinifierInterface;
use Tobento\Service\Minify\Minifier;
use Tobento\Service\Minify\MinifierInterface;
use Tobento\Service\Minify\Modifier;

$minifier = new Minifier\Html(
    new Modifier\Modifiers(
        new Modifier\Html\Attributes(),     // normalize and trim attributes
        new Modifier\Html\Comments(),       // remove HTML comments
        new Modifier\Html\Doctype(),        // normalize doctype
        new Modifier\Html\OptionalTags(),   // remove optional closing tags
        new Modifier\Html\Whitespaces(),    // collapse and trim whitespace
    )
);

var_dump($minifier instanceof HtmlMinifierInterface);
// bool(true)

var_dump($minifier instanceof MinifierInterface);
// bool(true)

// Minifying HTML
$minified = $minifier->minify($html);
```

A full list of available modifiers can be found under the [HTML Modifiers](#html-modifiers) section.

### JavaScript Minifier

[](#javascript-minifier)

The JavaScript minifier applies JavaScript-specific modifiers to reduce script size while preserving behavior and execution semantics.

```
use Tobento\Service\Minify\JavaScriptMinifierInterface;
use Tobento\Service\Minify\Minifier;
use Tobento\Service\Minify\MinifierInterface;
use Tobento\Service\Minify\Modifier;

$minifier = new Minifier\JavaScript(
    new Modifier\Modifiers(
        new Modifier\JavaScript\Comments(),     // remove comments
        new Modifier\JavaScript\Semicolons(),   // remove unnecessary semicolons
        new Modifier\JavaScript\Whitespaces(),  // collapse and trim whitespace
    )
);

var_dump($minifier instanceof JavaScriptMinifierInterface);
// bool(true)

var_dump($minifier instanceof MinifierInterface);
// bool(true)

// Minifying JavaScript
$minified = $minifier->minify($js);
```

A full list of available modifiers can be found under the [JavaScript Modifiers](#javascript-modifiers) section.

### Null Minifier

[](#null-minifier)

The Null Minifier performs no transformations and returns the content exactly as provided.
It is useful when minification should be disabled without changing application logic.

```
use Tobento\Service\Minify\Minifier;
use Tobento\Service\Minify\MinifierInterface;

$minifier = new Minifier\NullMinifier();

var_dump($minifier instanceof MinifierInterface);
// bool(true)

// No changes are applied
$minified = $minifier->minify($content);

var_dump($minified === $content);
// bool(true)
```

This minifier is ideal for development environments or scenarios where minification must be conditionally bypassed.

Available Modifiers
-------------------

[](#available-modifiers)

### CSS Modifiers

[](#css-modifiers)

#### Charsets CSS Modifier

[](#charsets-css-modifier)

The **Charsets** modifier normalizes and optimizes `@charset` declarations. It ensures that only a single, valid charset appears at the top of the stylesheet and removes any redundant or misplaced declarations.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Charsets();

$css = '@charset "UTF-8"; body { color: red; }';

$modified = $modifier->modify($css);
// '@charset "utf-8"; body { color: red; }'
```

This modifier is typically run early to ensure the `@charset` declaration is handled before other transformations, although it can safely run in any position since it normalizes and relocates the charset automatically.

#### Colors CSS Modifier

[](#colors-css-modifier)

The **Colors** modifier normalizes color values by converting named colors and long-form hex codes into their shortest valid representations. This helps reduce stylesheet size while preserving exact visual output.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Colors();

$css = 'body { color: #ff0000; background: red; }';

$modified = $modifier->modify($css);
// 'body { color: #f00; background: red; }'
```

This modifier focuses purely on color normalization and can be placed anywhere in the modifier sequence.

#### Comments CSS Modifier

[](#comments-css-modifier)

The **Comments** modifier removes CSS comments `(/* ... */)` that are safe to eliminate, helping reduce stylesheet size without affecting rendering or behavior.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Comments();

$css = '/* header */ body { color: red; } /* footer */';

$modified = $modifier->modify($css);
// 'body { color: red; }'
```

This modifier focuses solely on stripping comments and can be placed early in the modifier sequence to simplify later processing.

#### Font Weights CSS Modifier

[](#font-weights-css-modifier)

The **FontWeights** modifier normalizes named font-weight keywords (such as bold or normal) into their numeric equivalents. This reduces size and ensures consistent representation across the stylesheet.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\FontWeights();

$css = 'h1 { font-weight: bold; } p { font-weight: normal; }';

$modified = $modifier->modify($css);
// 'h1 { font-weight: 700; } p { font-weight: 400; }'
```

This modifier focuses solely on converting named weights to numeric values and can be placed anywhere in the modifier sequence.

#### Leading Zero CSS Modifier

[](#leading-zero-css-modifier)

The **LeadingZero** modifier removes unnecessary leading zeros from decimal values, reducing size without affecting meaning. For example, 0.5 becomes .5

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\LeadingZero();

$css = '.foo { opacity: 0.5; margin-left: 0.25em; }';

$modified = $modifier->modify($css);
// '.foo { opacity: .5; margin-left: .25em; }'
```

This modifier focuses solely on trimming leading zeros and can be placed anywhere in the modifier sequence.

#### Quotes CSS Modifier

[](#quotes-css-modifier)

The **Quotes** modifier removes unnecessary quotation marks in CSS attribute selectors, reducing size while preserving correct selector behavior.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Quotes();

$css = 'input[type="text"] { color: red; }';

$modified = $modifier->modify($css);
// 'input[type=text] { color: red; }'
```

This modifier affects only attribute selectors (e.g., `[type="text"] to [type=text])` and leaves all other quoted values such as strings or font-family names untouched.

#### Semicolons CSS Modifier

[](#semicolons-css-modifier)

The **Semicolons** modifier normalizes redundant semicolons in CSS declarations by replacing multiple consecutive semicolons with a single one. This helps clean up malformed or overly verbose CSS without altering valid syntax.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Semicolons();

$css = ".foo { color: red;; margin: 0;; }";

$modified = $modifier->modify($css);
// '.foo { color: red; margin: 0; }'
```

This modifier affects only consecutive semicolons (e.g., `;;` into `;`) and leaves valid single semicolons untouched. It does not add missing semicolons or modify spacing beyond the redundant sequences it removes.

#### Whitespaces CSS Modifier

[](#whitespaces-css-modifier)

The **Whitespaces** modifier removes unnecessary whitespace from CSS, reducing file size while preserving valid syntax. It collapses redundant spaces, tabs, and line breaks, and tightens common CSS patterns without altering semantics.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\Whitespaces();

$css = "
.foo {
    color: red;
    margin: 0;
}
";

$modified = $modifier->modify($css);
// '.foo{color:red;margin:0;}'
```

This modifier focuses on structural whitespace cleanup - such as removing extra spaces around braces, colons, semicolons, and between rules - while leaving meaningful whitespace (e.g., inside strings) untouched.

#### Zero Units CSS Modifier

[](#zero-units-css-modifier)

The **ZeroUnits** modifier removes unnecessary units from zero‑values in CSS declarations.
Values like `0px`, `0em`, or `0%` are normalized to plain `0`, reducing size while keeping the CSS valid.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\ZeroUnits();

$css = ".foo { margin: 0px; padding: 0em 10px; }";

$modified = $modifier->modify($css);
// '.foo { margin: 0; padding: 0 10px; }'
```

This modifier affects only values where the numeric part is exactly zero.
Non-zero values (e.g., `0.5px`, `10px`) remain unchanged.

#### Zero Values CSS Modifier

[](#zero-values-css-modifier)

The **ZeroValues** modifier normalizes zero-like numeric values to a plain `0`. It converts variants such as `0.0`, `.0`, `0.`, or `00` into a consistent `0`, helping clean up malformed or inconsistent CSS values.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Css\ZeroValues();

$css = ".foo { margin: 0.0; padding: 00; line-height: .0; }";

$modified = $modifier->modify($css);
// '.foo { margin: 0; padding: 0; line-height: 0; }'
```

This modifier affects only values that are effectively zero.
Non-zero values such as `0.5` or `0.75` remain unchanged - those are handled by the [Leading Zero](#leading-zero-css-modifier) modifier instead.

### HTML Modifiers

[](#html-modifiers)

#### Attributes HTML Modifier

[](#attributes-html-modifier)

The **Attributes** modifier removes redundant or unnecessary HTML attributes and normalizes certain boolean attributes.
It cleans up markup by stripping empty attributes, removing obsolete `type` declarations, and simplifying boolean attributes without altering the meaning of the HTML.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Html\Attributes();

$html = '';

$modified = $modifier->modify($html);
// ''
```

This modifier performs the following cleanups:

- Removes empty attributes such as `class=""`, `id=""`, or `style=""`.
- Removes obsolete script and style types (`type="text/javascript"` and `type="text/css"`).
- Normalizes boolean attributes by converting patterns like `disabled="disabled"` to `disabled`.

It does not modify attribute values, reorder attributes, or alter any other HTML semantics.

#### Comments HTML Modifier

[](#comments-html-modifier)

The **Comments** modifier removes standard HTML comments while preserving conditional comments used by older versions of Internet Explorer.
This helps reduce markup size without affecting compatibility-related comment blocks.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Html\Comments();

$html = '';

$modified = $modifier->modify($html);
// ''
```

This modifier removes:

- Regular HTML comments such as ``

It preserves:

- Conditional comments like ``

Only non-conditional comments are stripped. All other HTML content remains untouched.

#### Doctype HTML Modifier

[](#doctype-html-modifier)

The **Doctype** modifier normalizes any existing HTML doctype declaration to the minimal HTML5 form.
This ensures consistent output and removes legacy or verbose doctypes without affecting the rest of the document.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Html\Doctype();

$html = '';

$modified = $modifier->modify($html);
// ''
```

This modifier performs a single transformation:

- Replaces any doctype declaration with the minimal HTML5 doctype: ``

It does not modify any other part of the HTML document.

#### Whitespaces HTML Modifier

[](#whitespaces-html-modifier)

The **Whitespaces** modifier collapses redundant whitespace in HTML and removes unnecessary gaps between tags.
It reduces file size while keeping the document's structure and semantics intact.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\Html\Whitespaces();

$html = "   Hello       World ";

$modified = $modifier->modify($html);
// ' Hello  World '
```

This modifier performs the following cleanups:

- Collapses multiple consecutive whitespace characters into a single space.
- Removes whitespace between HTML tags (`> modify($js);
// "var x = 1;\nvar url = 'http://example.com';"
```

This modifier performs the following cleanups:

- Removes full-line single-line comments (lines that contain only `//` comments, optionally preceded by whitespace)
- Removes multi-line comments (`/* ... */`)
- Trims leading and trailing whitespace from the final output

It does not remove inline `//` comments and does not attempt to parse JavaScript syntax.
This ensures that URLs, strings, template literals, and regular expressions remain intact.

#### Whitespaces JS Modifier

[](#whitespaces-js-modifier)

The **Whitespaces** modifier normalizes and collapses unnecessary whitespace in JavaScript code.
It reduces file size by simplifying spacing and line breaks while preserving the overall structure of the code.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\JavaScript\Whitespaces();

$js = "var   x =  1;\n\n    console.log(x);";

$modified = $modifier->modify($js);
// "var x = 1;\nconsole.log(x);"
```

This modifier performs the following cleanups:

- Collapses consecutive spaces and tabs into a single space (excluding line feeds)
- Removes leading and trailing whitespace around line breaks
- Collapses multiple blank lines into a single line break
- Normalizes leftover spacing patterns for a cleaner output

**Important limitations**

- This modifier does not parse JavaScript syntax.
- It may alter whitespace inside:
    - string literals
    - template literals
    - regular expression literals
- It is therefore not safe for arbitrary or third-party JavaScript.
- It is intended for controlled codebases, such as your own project files where whitespace inside literals is not meaningful.

### Generic Modifiers

[](#generic-modifiers)

#### Callable Modifier

[](#callable-modifier)

The **CallableModifier** allows any PHP callable to be used as a minification modifier.
It acts as a lightweight wrapper that forwards the content to the provided callable and returns its result.

```
use Tobento\Service\Minify\Modifier;

$modifier = new Modifier\CallableModifier(function (string $content) {
    return strtoupper($content);
});

echo $modifier->modify('hello');
// 'HELLO'
```

This modifier performs the following behavior:

- Wraps any valid callable so it can be used as a modifier
- Passes the content string to the callable and returns the callable's output
- Ensures the provided value is callable and throws an exception otherwise

This is especially useful when integrating third-party minifiers or external processing functions.
Any existing minification logic can be plugged in directly without creating a dedicated modifier class.

The modifier itself applies no transformations. All behavior is defined by the user-supplied callable.

### Custom Modifier

[](#custom-modifier)

You can create your own modifier by implementing the `ModifierInterface`.
A custom modifier receives the content as a string and must return the modified result.

```
use Tobento\Service\Minify\ModifierInterface;

class MyCustomModifier implements ModifierInterface
{
    public function modify(string $content): string
    {
        // apply any transformation you need
        return str_replace('foo', 'bar', $content);
    }
}
```

Custom modifiers are useful when you need project-specific transformations or want full control over how content is processed.
They integrate seamlessly with the minifier pipeline and can be combined with built-in modifiers.

If you prefer not to create a dedicated class, the [Callable Modifier](#callable-modifier) allows you to wrap any callable and use it as a modifier directly.

Factories
---------

[](#factories)

### CSS Minifier Factory

[](#css-minifier-factory)

The `CssMinifierFactory` creates a [CSS Minifier](#css-minifier) instance composed of one or more CSS modifiers. By default, it includes all built-in [CSS modifiers](#css-modifiers), but the modifier pipeline can be fully customized.

This factory allows you to:

- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order

#### Built-in modifier keys

[](#built-in-modifier-keys)

The factory provides the following modifier keys:

- `charsets`
- `colors`
- `comments`
- `font-weights`
- `leading-zero`
- `quotes`
- `semicolons`
- `whitespaces`
- `zero-units`
- `zero-values`

If no modifiers are specified, **all** of the above are enabled by default.

#### Usage example

[](#usage-example)

```
use Tobento\Service\Minify\CssMinifierInterface;
use Tobento\Service\Minify\Factory\CssMinifierFactory;

// default: all modifiers enabled
$factory = new CssMinifierFactory();
// or with specific modifiers only
// $factory = new CssMinifierFactory(modifiers: ['comments']);

// exclude comments and whitespaces
$factory = $factory->except('comments', 'whitespaces');

// or use only the specified built-in modifiers
$factory = $factory->only('leading-zero');

// append a custom modifier
$factory = $factory->addModifier(new MyCustomCssModifier());

// or prepend one to run it before all others
$factory = $factory->prependModifier(new MyCustomCssModifier());

// create the minifier
$minifier = $factory->createMinifier();

var_dump($minifier instanceof CssMinifierInterface);
// bool(true)

$minified = $minifier->minify($css);
```

#### Customizing the modifier pipeline

[](#customizing-the-modifier-pipeline)

- **`only(...)`**
    Defines *exactly* which built-in modifier keys should be used, replacing the current list.
- **`except(...)`**
    Excludes one or more built-in modifier keys from the current list.
- **`addModifier(ModifierInterface)`**
    Appends a custom modifier instance to the end of the pipeline.
- **`prependModifier(ModifierInterface)`**
    Prepends a custom modifier instance to the beginning of the pipeline.

#### How it works

[](#how-it-works)

When `createMinifier()` is called:

- Each modifier entry is resolved:
    - strings are mapped to built-in modifier classes
    - instances of `ModifierInterface` are used directly
- The resolved modifiers are assembled into a `Modifiers` pipeline
- A [CSS Minifier](#css-minifier) instance is returned

This design keeps the CSS minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.

### HTML Minifier Factory

[](#html-minifier-factory)

The `HtmlMinifierFactory` creates an [HTML Minifier](#html-minifier) instance composed of one or more HTML modifiers. By default, all built‑in [HTML modifiers](#html-modifiers) are enabled, but the modifier pipeline can be fully customized.

This factory allows you to:

- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order

#### Built-in modifier keys

[](#built-in-modifier-keys-1)

The factory provides the following modifier keys:

- `attributes`
- `comments`
- `doctype`
- `whitespaces`

If no modifiers are specified, **all** of the above are enabled by default.

#### Usage example

[](#usage-example-1)

```
use Tobento\Service\Minify\HtmlMinifierInterface;
use Tobento\Service\Minify\Factory\HtmlMinifierFactory;

// default: all modifiers enabled
$factory = new HtmlMinifierFactory();
// or with specific modifiers only
// $factory = new HtmlMinifierFactory(modifiers: ['comments']);

// exclude comments and doctype
$factory = $factory->except('comments', 'doctype');

// or use only the specified built‑in modifiers
$factory = $factory->only('attributes');

// append a custom modifier
$factory = $factory->addModifier(new MyCustomHtmlModifier());

// or prepend one to run it before all others
$factory = $factory->prependModifier(new MyCustomHtmlModifier());

// create the minifier
$minifier = $factory->createMinifier();

var_dump($minifier instanceof HtmlMinifierInterface);
// bool(true)

$minified = $minifier->minify($html);
```

#### Customizing the modifier pipeline

[](#customizing-the-modifier-pipeline-1)

- **`only(...)`**
    Defines *exactly* which built-in modifier keys should be used, replacing the current list.
- **`except(...)`**
    Excludes one or more built-in modifier keys from the current list.
- **`addModifier(ModifierInterface)`**
    Appends a custom modifier instance to the end of the pipeline.
- **`prependModifier(ModifierInterface)`**
    Prepends a custom modifier instance to the beginning of the pipeline.

#### How it works

[](#how-it-works-1)

When `createMinifier()` is called:

- Each modifier entry is resolved:
    - strings are mapped to built-in modifier classes
    - instances of `ModifierInterface` are used directly
- The resolved modifiers are assembled into a `Modifiers` pipeline
- A [HTML Minifier](#html-minifier) instance is returned

This design keeps the HTML minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.

### JavaScript Minifier Factory

[](#javascript-minifier-factory)

The `JavaScriptMinifierFactory` creates a [JavaScript Minifier](#javascript-minifier) instance composed of one or more JavaScript modifiers. By default, all built-in [JavaScript modifiers](#javascript-modifiers) are enabled, but the modifier pipeline can be fully customized.

This factory allows you to:

- select only specific built-in modifiers
- exclude specific built-in modifiers
- append custom modifiers to the end of the pipeline
- prepend custom modifiers to run before all others
- combine built-in and custom modifiers in any order

#### Built-in modifier keys

[](#built-in-modifier-keys-2)

The factory provides the following modifier keys:

- `comments`
- `whitespaces`

If no modifiers are specified, **both** built-in modifiers are enabled by default.

#### Usage example

[](#usage-example-2)

```
use Tobento\Service\Minify\JavaScriptMinifierInterface;
use Tobento\Service\Minify\Factory\JavaScriptMinifierFactory;

// default: all modifiers enabled
$factory = new JavaScriptMinifierFactory();
// or with specific modifiers only
// $factory = new JavaScriptMinifierFactory(modifiers: ['comments']);

// exclude comments
$factory = $factory->except('comments');

// or use only the specified built-in modifiers
$factory = $factory->only('whitespaces');

// append a custom modifier
$factory = $factory->addModifier(new MyCustomJsModifier());

// or prepend one to run it before all others
$factory = $factory->prependModifier(new MyCustomJsModifier());

// create the minifier
$minifier = $factory->createMinifier();

var_dump($minifier instanceof JavaScriptMinifierInterface);
// bool(true)

$minified = $minifier->minify($js);
```

#### Customizing the modifier pipeline

[](#customizing-the-modifier-pipeline-2)

- **`only(...)`**
    Defines *exactly* which built-in modifier keys should be used, replacing the current list.
- **`except(...)`**
    Excludes one or more built-in modifier keys from the current list.
- **`addModifier(ModifierInterface)`**
    Appends a custom modifier instance to the end of the pipeline.
- **`prependModifier(ModifierInterface)`**
    Prepends a custom modifier instance to the beginning of the pipeline.

#### How it works

[](#how-it-works-2)

When `createMinifier()` is called:

- Each modifier entry is resolved:
    - strings are mapped to built-in modifier classes
    - instances of `ModifierInterface` are used directly
- The resolved modifiers are assembled into a `Modifiers` pipeline
- A [JavaScript Minifier](#javascript-minifier) instance is returned

This design keeps the JavaScript minifier flexible, composable, and easy to extend with project-specific or third-party modifiers.

### Null Minifier Factory

[](#null-minifier-factory)

The `NullMinifierFactory` creates a [Null Minifier](#null-minifier) instance.
This minifier performs **no transformations** on the input and simply returns the content unchanged.

This factory is useful when:

- minification should be disabled in certain environments (e.g., development)
- you want to explicitly bypass minification while keeping the same interface
- an asset handler expects a minifier but you do not want any processing applied

#### Usage example

[](#usage-example-3)

```
use Tobento\Service\Minify\Factory\NullMinifierFactory;

$factory = new NullMinifierFactory();

$minifier = $factory->createMinifier();

$original = $minifier->minify($content); // unchanged
```

#### How it works

[](#how-it-works-3)

When `createMinifier()` is called:

- A new `NullMinifier` instance is returned
- The minifier simply returns the input content without modification

This design provides a simple, predictable way to disable minification while maintaining compatibility with the minifier pipeline and the asset handler system.

Minifiers
---------

[](#minifiers)

The `Minifiers` class acts as a registry and resolver for all available minifiers. It allows you to register minifiers by name and retrieve them on demand.
A minifier may be:

- a `MinifierInterface` instance
- a `MinifierFactoryInterface` instance (lazy-loaded)
- a callable returning a `MinifierInterface` (lazy-loaded)

If a requested minifier is not found, a fallback minifier is created using the configured fallback factory (default: `NullMinifierFactory`).

### Minifiers Registry

[](#minifiers-registry)

You may register any number of named minifiers:

```
use Tobento\Service\Minify\MinifierInterface;
use Tobento\Service\Minify\Minifiers;
use Tobento\Service\Minify\MinifiersInterface;
use Tobento\Service\Minify\Factory;

$minifiers = new Minifiers(
    minifiers: [
        'css' => new Factory\CssMinifierFactory(),
        'html' => new Factory\HtmlMinifierFactory(),
        'js' => fn() => new Factory\JavaScriptMinifierFactory()->createMinifier(),
    ],

    // Used as fallback if a named minifier is missing
    // minifierFactory: new Factory\NullMinifierFactory(), // default
);

var_dump($minifiers instanceof MinifiersInterface);
// bool(true)

// Add minifiers in all supported ways:
// 1. Direct instance
$minifiers->add('direct', new Factory\CssMinifierFactory()->createMinifier());

// 2. Factory (lazy-loaded)
$minifiers->add('factory', new Factory\CssMinifierFactory());

// 3. Callable (lazy-loaded)
$minifiers->add(
    name: 'callable',
    minifier: fn(): MinifierInterface => new Factory\HtmlMinifierFactory()->createMinifier(),
);

// Check if a minifier exists
$minifiers->has('css'); // true or false

// Retrieve a minifier
$cssMinifier = $minifiers->get('css');

// List all registered minifier names:
$minifiers->names(); // ['css', 'html', 'js']
```

Credits
=======

[](#credits)

- [Tobias Strub](https://www.tobento.ch)
- [All Contributors](../../contributors)

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance85

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

75d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/055d6a1b5c2384bb179c75ab0b55914231d898fdc4dffeb30770f81200e52206?d=identicon)[TOBENTOch](/maintainers/TOBENTOch)

---

Top Contributors

[![tobento-ch](https://avatars.githubusercontent.com/u/16684832?v=4)](https://github.com/tobento-ch "tobento-ch (1 commits)")

---

Tags

phpjavascriptcsscompressionhtmlminifyminifieroptimizertobento

###  Code Quality

TestsPHPUnit

Static AnalysisPsalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tobento-service-minify/health.svg)

```
[![Health](https://phpackages.com/badges/tobento-service-minify/health.svg)](https://phpackages.com/packages/tobento-service-minify)
```

###  Alternatives

[matthiasmullie/minify

CSS &amp; JavaScript minifier, in PHP. Removes whitespace, strips comments, combines files (incl. @import statements and small assets in CSS files), and optimizes/shortens a few common programming patterns.

2.0k30.5M336](/packages/matthiasmullie-minify)[nlac/nlsclientscript

Yii ClientScript extension for prevent reloading javascript and merging/minfying resources

208.2k](/packages/nlac-nlsclientscript)[hexydec/htmldoc

A token based HTML document parser and minifier. Minify HTML documents including inline CSS, Javascript, and SVG's on the fly. Extract document text, attributes, and fragments. Full test suite.

2610.3k3](/packages/hexydec-htmldoc)[bissolli/php-css-js-minifier

A PHP Class to merge and minify CSS and JavaScript files.

102.8k4](/packages/bissolli-php-css-js-minifier)[trentrichardson/cakephp-shrink

Compiles, combines, and minifies javascript, coffee, less, scss, and css

1619.3k](/packages/trentrichardson-cakephp-shrink)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
