From d1a6afe9e9782026943bb21f98a316550385b769 Mon Sep 17 00:00:00 2001 From: Jake Hotson Date: Fri, 27 Sep 2019 19:23:53 +0100 Subject: [PATCH] [FEATURE] Add HtmlPruner::removeRedundantClassesAfterCssInlined Also added section for `HtmlPruner` to the README. Closes #380. --- CHANGELOG.md | 3 + README.md | 37 +++- src/Emogrifier/HtmlProcessor/HtmlPruner.php | 27 +++ .../HtmlProcessor/HtmlPrunerTest.php | 177 ++++++++++++++++++ 4 files changed, 242 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ec3d099..e6b89dea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## x.y.z ### Added +- Add `HtmlPruner::removeRedundantClassesAfterCssInlined` + ([#380](https://github.com/MyIntervals/emogrifier/issues/380), + [#724](https://github.com/MyIntervals/emogrifier/pull/724)) - Check on Travis that PHP-CS-Fixer will not change anything [#727](https://github.com/MyIntervals/emogrifier/pull/727)) - Support `:not(…)` as an entire selector diff --git a/README.md b/README.md index 53b3f859..76ad05c0 100644 --- a/README.md +++ b/README.md @@ -106,8 +106,10 @@ use Pelago\Emogrifier\HtmlProcessor\HtmlPruner; … -$domDocument = CssInliner::fromHtml($html)->inlineCss($css)->getDomDocument(); -HtmlPruner::fromDomDocument($domDocument)->removeElementsWithDisplayNone(); +$cssInliner = CssInliner::fromHtml($html)->inlineCss($css); +$domDocument = $cssInliner->getDomDocument(); +HtmlPruner::fromDomDocument($domDocument)->removeElementsWithDisplayNone() + ->removeRedundantClassesAfterCssInlined($cssInliner); $finalHtml = CssToAttributeConverter::fromDomDocument($domDocument) ->convertCssToVisualAttributes()->render(); ``` @@ -156,6 +158,37 @@ $visualHtml = CssToAttributeConverter::fromDomDocument($domDocument) ->convertCssToVisualAttributes()->render(); ``` +### Removing redundant content and attributes from the HTML + +The `HtmlPruner` class can reduce the size of the HTML by removing elements with +a `display: none` style declaration, and/or removing classes from `class` +attributes that are not required. + +It can be used like this: + +```php +use Pelago\Emogrifier\HtmlProcessor\HtmlPruner; + +… + +$prunedHtml = HtmlPruner::fromHtml($html)->removeElementsWithDisplayNone() + ->removeRedundantClasses($classesToKeep)->render(); +``` + +The `removeRedundantClasses` method accepts a whitelist of names of classes that +should be retained. If this is a post-processing step after inlining CSS, you +can alternatively use `removeRedundantClassesAfterCssInlined`, passing it the +`CssInliner` instance that has inlined the CSS (and having the `HtmlPruner` work +on the `DOMDocument`). This will use information from the `CssInliner` to +determine which classes are still required (namely, those used in uninlinable +rules that have been copied to a `