Skip to content

Commit 14989d6

Browse files
authored
Merge pull request #635 from GravityPDF/feature/536-stylesheet-tokenizer
Parse stylesheets with a tokenizer, so a brace, semicolon or comment marker in a string no longer breaks the rules around it
2 parents 296be03 + 58294d8 commit 14989d6

20 files changed

Lines changed: 1364 additions & 446 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,11 @@ Bugfixes
168168
* The rule after an `@supports`, `@layer`, `@keyframes`, `@container` or other block at-rule was lost, and so were the rules inside `@supports` and `@layer`. The rule after `@charset`, `@namespace` or `@import` was lost too. `@supports` and `@layer` blocks are now unwrapped as `@media` blocks are, except `@supports not`, and other at-rules are removed whole. [#524] [#566]
169169
* `@media` was matched by looking for the word `print`, so `@media not print` applied, `orientation` was ignored and `min-width` never matched. Media queries are now evaluated for the print medium against the page current when the stylesheet is read: media types with `not` and `only`; `and`, `or` and `not` conditions; and `width`, `height` and `orientation`, with `min-`/`max-` prefixes and range syntax such as `(width >= 600px)`. An A4 page is about 794px wide, so `@media (min-width: 768px)` rules now apply to it. [#552] [#575]
170170
* `@import` ignored its media list, and did not load a URL that does not end in `.css`, such as a Google Fonts stylesheet. [#552] [#575]
171+
* A brace, semicolon or comment marker inside a quoted string, an unquoted `url()` or an escape broke the stylesheet around it. `q { quotes: "}" }` lost the rule after it, `font-family: 'a;color:red'` set the colour, a `/*` in one string and a `*/` in a later one removed every rule between them, and `@import url(…?family=Inter:wght@300;400)` lost the rule after it. A rule or at-rule nested in a block, as CSS nesting writes them, lost the rest of the block and the rule after it. Stylesheets are now split by a tokenizer that reads strings, `url()`, escapes and comments as CSS does, in either `cssMode`. A rule or at-rule nested in a block is left out, and the declarations after it apply. [#536] [#635]
172+
* A string left open ends at the line break, as in CSS. A block or comment left open ends with its `<style>` or stylesheet file instead of running into the next one.
173+
* A byte order mark at the start of a stylesheet, as `WriteHTML(file_get_contents('style.css'), HTMLParserMode::HEADER_CSS)` passes one on, no longer spoils the first rule.
174+
* An `@import` is loaded only from the stylesheet's own rules, not from a comment, a string or a block.
175+
* A `style` attribute is split the same way, so `style="font-family: 'a;b', serif; color: red"` applies both, and a value may run over several lines.
171176
* `td:nth-child()` and `th:nth-child()` counted grid columns, so a `colspan` or `rowspan` before a cell made the rule miss it and reach the cell after. They now count the cells of the row. `:first-child` on a `tr`, `td` or `th` now works, as `:nth-child(1)`. [#528] [#572]
172177
* Some colour values were read wrongly. [#552] [#570]
173178
* `#rgba` was read from the wrong digits: `#f008` drew `rgb(240, 8, 0)`. `#rrggbbaa` dropped its alpha. Both are now read with their alpha.
@@ -789,6 +794,7 @@ These changes do not change output.
789794
[#528]: https://github.com/GravityPDF/mpdf/issues/528
790795
[#533]: https://github.com/GravityPDF/mpdf/issues/533
791796
[#535]: https://github.com/GravityPDF/mpdf/issues/535
797+
[#536]: https://github.com/GravityPDF/mpdf/issues/536
792798
[#537]: https://github.com/GravityPDF/mpdf/issues/537
793799
[#538]: https://github.com/GravityPDF/mpdf/issues/538
794800
[#549]: https://github.com/GravityPDF/mpdf/pull/549
@@ -836,4 +842,5 @@ These changes do not change output.
836842
[#631]: https://github.com/GravityPDF/mpdf/pull/631
837843
[#632]: https://github.com/GravityPDF/mpdf/issues/632
838844
[#633]: https://github.com/GravityPDF/mpdf/pull/633
845+
[#635]: https://github.com/GravityPDF/mpdf/pull/635
839846
[#634]: https://github.com/GravityPDF/mpdf/pull/634

‎src/Css/AtRuleProcessor.php‎

Lines changed: 0 additions & 217 deletions
This file was deleted.

‎src/Css/CommentParser.php‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ public function removeHtmlComments($html)
2121
}
2222

2323
/**
24-
* Remove HTML and CSS comments from style blocks.
24+
* Remove the HTML comment markers from style blocks.
2525
*
26-
* Removes both HTML comments (<!-- -->) and CSS comments from
27-
* <style> tag contents while preserving the structure.
26+
* Replaces each <!-- and --> in <style> tag contents with a space, so removeHtmlComments() does not take the
27+
* stylesheet for a comment. CSS comments are left for StylesheetTokenizer::removeComments(), which knows a comment
28+
* marker inside a string is not one.
2829
*
2930
* @param string $html HTML content with style tags
3031
* @return string HTML with cleaned style blocks
@@ -37,8 +38,7 @@ public function removeCommentsFromStyleBlocks($html)
3738
}
3839

3940
foreach ($m[1] as $style) {
40-
$sub = str_replace(['<!--', '-->'], ' ', $style);
41-
$sub = '>' . preg_replace('|/\*.*?\*/|s', ' ', $sub) . '</style>';
41+
$sub = '>' . str_replace(['<!--', '-->'], ' ', $style) . '</style>';
4242
$html = str_replace('>' . $style . '</style>', $sub, $html);
4343
}
4444

‎src/Css/CssLoader.php‎

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,18 @@ class CssLoader
3232
*/
3333
private $mediaQueryProcessor;
3434

35+
/**
36+
* @var StylesheetTokenizer
37+
*/
38+
private $tokenizer;
39+
3540
public function __construct(Mpdf $mpdf, AssetFetcher $assetFetcher, Cache $cache, MediaQueryProcessor $mediaQueryProcessor)
3641
{
3742
$this->mpdf = $mpdf;
3843
$this->assetFetcher = $assetFetcher;
3944
$this->cache = $cache;
4045
$this->mediaQueryProcessor = $mediaQueryProcessor;
46+
$this->tokenizer = new StylesheetTokenizer();
4147
}
4248

4349
/**
@@ -93,29 +99,40 @@ public function extractExternalStylesheetUrls($html)
9399
}
94100

95101
preg_match_all('/<style.*?>(.*?)<\/style>/si', $html, $styles);
102+
foreach ($styles[1] as $css) {
103+
$cssUrls = array_merge($cssUrls, $this->extractImportUrls($css));
104+
}
96105

97-
return array_merge($cssUrls, $this->extractImportUrls(implode(' ', $styles[1])));
106+
return $cssUrls;
98107
}
99108

100109
/**
101110
* The URLs the @import rules in $css load, less those whose media query list does not match
102111
*
103-
* A layer() before the media query list is ignored. A supports() condition is taken to pass, as the rules in an
104-
* @supports block are unwrapped, so one that starts with not fails.
112+
* Only an @import among the stylesheet's own rules is read, not one in a comment, a string or a block. A layer()
113+
* before the media query list is ignored. A supports() condition is taken to pass, as the rules in an @supports
114+
* block are unwrapped, so one that starts with not fails.
105115
*
106116
* @param string $css
107117
* @return string[]
108118
*/
109119
private function extractImportUrls($css)
110120
{
121+
if (stripos($css, '@import') === false) {
122+
return [];
123+
}
124+
111125
$url = '(?|url\(\s*"([^"]*)"\s*\)|url\(\s*\'([^\']*)\'\s*\)|url\(\s*([^\s"\')]*)\s*\)|"([^"]*)"|\'([^\']*)\')';
112126
$layer = '(?:\s*layer(?:\([^)]*\))?)?';
113127
$supports = '(?:\s*supports\(\s*(not\b)?(?:[^()]|\([^()]*\))*\))?';
114-
preg_match_all('/@import\s*' . $url . $layer . $supports . '([^;{}]*)/i', $css, $imports, PREG_SET_ORDER);
128+
$pattern = '/^' . $url . $layer . $supports . '(.*)$/is';
115129

116130
$urls = [];
117-
foreach ($imports as $import) {
118-
if ($import[1] !== '' && $import[2] === '' && $this->mediaQueryProcessor->matches($import[3])) {
131+
foreach ($this->tokenizer->rules($this->tokenizer->removeComments($css)) as $rule) {
132+
if ($rule[0] === 'import' && $rule[2] === null
133+
&& preg_match($pattern, $rule[1], $import)
134+
&& $import[1] !== '' && $import[2] === '' && $this->mediaQueryProcessor->matches($import[3])
135+
) {
119136
$urls[] = $import[1];
120137
}
121138
}
@@ -135,18 +152,14 @@ private function extractImportUrls($css)
135152
*/
136153
public function processExternalCssImports($stylesheetCss, $path, &$externalCss, &$externalCssCount)
137154
{
138-
$css = '';
139-
140155
$cssBasePath = preg_replace('/\/[^\/]*$/', '', $path) . '/';
141156
foreach ($this->extractImportUrls($stylesheetCss) as $cxtembedded) {
142157
// path is relative to original stylesheet!!
143158
$externalCss[] = Path::relativeToAbsolutePath($cxtembedded, $cssBasePath);
144159
$externalCssCount++;
145160
}
146161

147-
$css .= ' ' . $this->resolveBackgroundUrls($stylesheetCss, $cssBasePath);
148-
149-
return $css;
162+
return $this->resolveBackgroundUrls($stylesheetCss, $cssBasePath);
150163
}
151164

152165
/**

0 commit comments

Comments
 (0)