Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
markvaneijk committed May 10, 2024
1 parent e386637 commit 869206c
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 11 deletions.
5 changes: 3 additions & 2 deletions config/minify-html.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

return [
'transformers' => [
RemoveComments::class,
RemoveWhitespace::class,
\Vormkracht10\MinifyHtml\Transformers\RemoveComments::class,
\Vormkracht10\MinifyHtml\Transformers\RemoveWhitespace::class,
\Vormkracht10\MinifyHtml\Transformers\TrimScripts::class,
],
];
16 changes: 7 additions & 9 deletions src/Middleware/MinifyHtml.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,30 @@ public function handle($request, $next)

$response = $next($request);

foreach (config('minify-html.transformers') as $x => $transformer) {
$response = (new $transformer)->transform($response);
$content = $response->getContent();

foreach (config('minify-html.transformers', []) as $x => $transformer) {
$content = (new $transformer)->transform($content);
}

return $response;
return $response->setContent($content);
}

public function shouldMinifyHtml(Request $request)
{
if (! config('minify-html.enabled')) {
return false;
}

if (! in_array($request->method(), ['GET', 'HEAD'])) {
return false;
}

if ($request->isJson() || $request->isXml()) {
if ($request->isJson()) {
return false;
}

if (! str_contains($request->header('Accept'), 'html')) {
return false;
}

if ($request->ajax()) {
if ($request->isPrecognitive() || $request->isXmlHttpRequest()) {
return false;
}

Expand Down
2 changes: 2 additions & 0 deletions src/Transformers/RemoveComments.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

namespace Vormkracht10\MinifyHtml\Transformers;

class RemoveComments
{
public function transform(string $html): string
Expand Down
2 changes: 2 additions & 0 deletions src/Transformers/RemoveWhitespace.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

namespace Vormkracht10\MinifyHtml\Transformers;

class RemoveWhitespace
{
protected array $hiddenElements = [];
Expand Down
19 changes: 19 additions & 0 deletions src/Transformers/TrimScripts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Vormkracht10\MinifyHtml\Transformers;

class TrimScripts
{
public function transform(string $html): string
{
if (preg_match_all('~<script[^>]*>(.*)</script>~Uuis', $html, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$replace = trim(preg_replace('~^\p{Z}+|\p{Z}+$|^\s+~m', '', $match[1]));

$html = str_replace($match[1], $replace, $html);
}
}

return $html;
}
}

0 comments on commit 869206c

Please sign in to comment.