Skip to content

Commit

Permalink
Fix html tags matching and replacing
Browse files Browse the repository at this point in the history
- Void tags are parsed differently of common tags
- Improves replacing attributes of tags
  • Loading branch information
lucasMesquitaBorges committed Mar 25, 2021
1 parent 5c807f0 commit cc188ed
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 8 deletions.
26 changes: 26 additions & 0 deletions src/Entities/HtmlSpecs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

namespace RenatoMarinho\LaravelPageSpeed\Entities;

class HtmlSpecs
{
public static function voidElements(): array
{
return [
'area',
'base',
'br',
'col',
'embed',
'hr',
'img',
'input',
'link',
'meta',
'param',
'source',
'track',
'wbr',
];
}
}
32 changes: 24 additions & 8 deletions src/Middleware/PageSpeed.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace RenatoMarinho\LaravelPageSpeed\Middleware;

use Closure;
use RenatoMarinho\LaravelPageSpeed\Entities\HtmlSpecs;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

Expand Down Expand Up @@ -109,10 +110,26 @@ protected function shouldProcessPageSpeed($request, $response)
*/
protected function matchAllHtmlTag(array $tags, string $buffer): array
{
$tags = '('.implode('|', $tags).')';
$voidTags = array_intersect($tags, HtmlSpecs::voidElements());
$normalTags = array_diff($tags, $voidTags);

preg_match_all("/\<\s*{$tags}[^>]*\>((.|\n)*?)\<\s*\/\s*{$tags}\>/", $buffer, $matches);
return $matches;
return array_merge(
$this->matchTags($voidTags, '/\<\s*(%tags)[^>]*\>/', $buffer),
$this->matchTags($normalTags, '/\<\s*(%tags)[^>]*\>((.|\n)*?)\<\s*\/\s*(%tags)\>/', $buffer)
);
}

protected function matchTags(array $tags, string $pattern, string $buffer): array
{
if (empty($tags)) {
return [];
}

$normalizedPattern = str_replace('%tags', implode('|', $tags), $pattern);

preg_match_all($normalizedPattern, $buffer, $matches);

return $matches[0];
}

/**
Expand All @@ -127,12 +144,11 @@ protected function matchAllHtmlTag(array $tags, string $buffer): array
*/
protected function replaceInsideHtmlTags(array $tags, string $regex, string $replace, string $buffer): string
{
foreach ($this->matchAllHtmlTag($tags, $buffer)[0] as $tagMatched) {
preg_match_all($regex, $tagMatched, $tagContentsMatchedToReplace);
foreach ($this->matchAllHtmlTag($tags, $buffer) as $tagMatched) {
preg_match_all($regex, $tagMatched, $contentsMatched);

foreach ($tagContentsMatchedToReplace[0] as $tagContentReplace) {
$buffer = str_replace($tagContentReplace, $replace, $buffer);
}
$tagAfterReplace = str_replace($contentsMatched[0], $replace, $tagMatched);
$buffer = str_replace($tagMatched, $tagAfterReplace, $buffer);
}

return $buffer;
Expand Down

0 comments on commit cc188ed

Please sign in to comment.