Skip to content

Commit 63bcecc

Browse files
jakejackson1claude
andcommitted
Match selectors that write an id with classes, such as p#i.c
`p#i.c`, `p.c#i`, `#i.c` and `p.a.b#i` never matched: the `.` and `#` shapes took anything after the dot or hash, so `p.c#i` was stored as class `C#I` and `p#i.c` as id `I.C`, names no element has. A part made of an optional tag and any mix of classes and one id is now parsed into one key, the tag, then the id, then the classes sorted, so `p.c#i` and `p#i.c` are both `P>>ID>>I>>CLASS>>C`. Those keys are looked up after `tag#id`, for each combination of the element's classes `#id.class` then `tag#id.class`, in the simple groups, in descendant rules and when an ancestor's rules are lifted. Class and id names are limited to name characters, so a part such as `.a:hover` or `#i::before` fails to parse and the selector is dropped, as other selectors mPDF cannot match are. Closes #527 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 09e26ea commit 63bcecc

8 files changed

Lines changed: 390 additions & 15 deletions

‎CHANGELOG-GRAVITYPDF.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ New features
9191
* Text beside a float, and the blocks around it, keep to the page area of each page the float runs over. [#549]
9292
* A block with a set width keeps its place in each page area: a centred block stays centred, and a block pushed right by `margin-left: auto` or set right to left stays against the right margin. [#550] [#551] [#553]
9393

94+
### CSS
95+
96+
* **An id written with classes.** Selectors such as `p#note.warning`, `p.warning#note`, `#note.warning` and `p.a.b#note` match, on their own and as parts of descendant rules, in any order of id and classes. They are applied after `p#note`. A selector with a class or id followed by something mPDF cannot match, such as `.a:hover` or `#note::before`, is dropped like any other selector mPDF cannot match. [#527] [#568]
97+
9498
Performance
9599
-----------
96100

@@ -720,6 +724,7 @@ These changes do not change output.
720724
[#549]: https://github.com/GravityPDF/mpdf/pull/549
721725
[#561]: https://github.com/GravityPDF/mpdf/pull/561
722726
[#525]: https://github.com/GravityPDF/mpdf/issues/525
727+
[#527]: https://github.com/GravityPDF/mpdf/issues/527
723728
[#549]: https://github.com/GravityPDF/mpdf/pull/549
724729
[#552]: https://github.com/GravityPDF/mpdf/issues/552
725730
[#560]: https://github.com/GravityPDF/mpdf/pull/560
@@ -735,3 +740,4 @@ These changes do not change output.
735740
[#564]: https://github.com/GravityPDF/mpdf/pull/564
736741
[#563]: https://github.com/GravityPDF/mpdf/pull/563
737742
[#565]: https://github.com/GravityPDF/mpdf/pull/565
743+
[#568]: https://github.com/GravityPDF/mpdf/pull/568

‎src/Css/CssMerger.php‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,21 @@ protected function mergeTagSpecificSelectors($tag, $attr, $classes, $languageCod
679679
$this->mergeBorderProperties($zp);
680680
}
681681
}
682+
683+
// STYLESHEET ID WITH CLASSES e.g. #smallone.note{} p#smallone.note{}
684+
foreach ($this->idClassKeys($tag, $attr['ID'], $classes) as $key) {
685+
if (empty($this->cssManager->CSS[$key])) {
686+
continue;
687+
}
688+
689+
$zp = $this->cssManager->CSS[$key];
690+
if ($tag === 'TD' || $tag === 'TH') {
691+
$this->setDominanceFromProperties($zp, 9);
692+
}
693+
694+
$this->cssProperties = array_merge($this->cssProperties, $zp);
695+
$this->mergeBorderProperties($zp);
696+
}
682697
}
683698

684699
/**
@@ -787,6 +802,11 @@ protected function mergeTableDescendantSelectors($tag, $attr, $classes, $languag
787802
}
788803

789804
$this->setMergedCss($node[$tag . '>>ID>>' . $attr['ID']], false, 9);
805+
foreach ($this->idClassKeys($tag, $attr['ID'], $classes) as $key) {
806+
if (isset($node[$key])) {
807+
$this->setMergedCss($node[$key], false, 9);
808+
}
809+
}
790810

791811
if ($this->sideEffects) {
792812
$this->cssManager->tablecascadeCSS[$this->cssManager->tbCSSlvl - 1] = $node;
@@ -827,6 +847,11 @@ protected function mergeDescendantCss($cascadeCSS, $tag, $attr, $classes, $langu
827847
}
828848

829849
$this->setMergedCss($cascadeCSS[$tag . '>>ID>>' . $attr['ID']]);
850+
foreach ($this->idClassKeys($tag, $attr['ID'], $classes) as $key) {
851+
if (isset($cascadeCSS[$key])) {
852+
$this->setMergedCss($cascadeCSS[$key]);
853+
}
854+
}
830855
}
831856

832857
/**
@@ -848,6 +873,30 @@ private function langKey($rules, $prefix, $lang, $languageCode)
848873
return $prefix . $lang;
849874
}
850875

876+
/**
877+
* The keys of the rules for an id with classes that can match an element, in the order they apply: for each
878+
* combination of its classes, #id.class and then tag#id.class
879+
*
880+
* @param string $tag
881+
* @param string $id
882+
* @param string[] $classes Combinations of the element's classes, as merge() builds them
883+
* @return string[]
884+
*/
885+
private function idClassKeys($tag, $id, $classes)
886+
{
887+
$keys = [];
888+
if ($id === '') {
889+
return $keys;
890+
}
891+
892+
foreach ($classes as $class) {
893+
$keys[] = 'ID>>' . $id . '>>CLASS>>' . $class;
894+
$keys[] = $tag . '>>ID>>' . $id . '>>CLASS>>' . $class;
895+
}
896+
897+
return $keys;
898+
}
899+
851900
/**
852901
* Merge CSS properties into target array.
853902
*
@@ -981,6 +1030,12 @@ protected function mergeFullCssRules($p, &$t, $tag, $classes, $id, $lang)
9811030
if (isset($id) && isset($p[$tag . '>>ID>>' . $id])) {
9821031
$this->mergeCssProperties($p[$tag . '>>ID>>' . $id], $t);
9831032
}
1033+
1034+
foreach ($this->idClassKeys($tag, $id, $classes) as $key) {
1035+
if (isset($p[$key])) {
1036+
$this->mergeCssProperties($p[$key], $t);
1037+
}
1038+
}
9841039
}
9851040

9861041
/**

‎src/Css/SelectorParser.php‎

Lines changed: 46 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66

77
class SelectorParser
88
{
9+
/**
10+
* A class or id name, without the . or #. Stylesheets are uppercased before they are parsed, so the lowercase
11+
* letters are only for callers that do not.
12+
*/
13+
const NAME = '[A-Za-z0-9_\-\x80-\xFF]+';
14+
915
/**
1016
* @var Mpdf
1117
*/
@@ -75,24 +81,14 @@ public function parseSimpleSelector($tags)
7581
}
7682

7783
$tag = '';
78-
if (preg_match('/^[.](.*)$/', $t, $m)) {
79-
$classes = explode('.', $m[1]);
80-
sort($classes);
81-
$tag = 'CLASS>>' . implode('.', $classes);
82-
} elseif (preg_match('/^[#](.*)$/', $t, $m)) {
83-
$tag = 'ID>>' . $m[1];
84+
if (preg_match('/^(' . $this->mpdf->allowedCSStags . ')?((?:[.#]' . self::NAME . ')+)$/', $t, $m)) {
85+
$tag = $this->compoundKey($m[1], $m[2]);
8486
} elseif (preg_match('/^\[LANG=[\'\"]{0,1}([A-Z\-]{2,11})[\'\"]{0,1}\]$/', $t, $m)) {
8587
$tag = 'LANG>>' . strtolower($m[1]);
8688
} elseif (preg_match('/^:LANG\([\'\"]{0,1}([A-Z\-]{2,11})[\'\"]{0,1}\)$/', $t, $m)) { // mPDF 6 Special case for lang as attribute selector
8789
$tag = 'LANG>>' . strtolower($m[1]);
88-
} elseif (preg_match('/^(' . $this->mpdf->allowedCSStags . ')[.](.*)$/', $t, $m)) { // mPDF 6 Special case for lang as attribute selector
89-
$classes = explode('.', $m[2]);
90-
sort($classes);
91-
$tag = $m[1] . '>>CLASS>>' . implode('.', $classes);
9290
} elseif (preg_match('/^(' . $this->mpdf->allowedCSStags . ')\s*:NTH-CHILD\(([\-+]?\d*N(?:[\-+]\d+)?|[\-+]?\d+|ODD|EVEN)\)$/', $t, $m)) { // the whole argument is a formula, with nothing after it
9391
$tag = $m[1] . '>>SELECTORNTHCHILD>>' . $m[2];
94-
} elseif (preg_match('/^(' . $this->mpdf->allowedCSStags . ')[#](.*)$/', $t, $m)) {
95-
$tag = $m[1] . '>>ID>>' . $m[2];
9692
} elseif (preg_match('/^(' . $this->mpdf->allowedCSStags . ')\[LANG=[\'\"]{0,1}([A-Z\-]{2,11})[\'\"]{0,1}\]$/', $t, $m)) {
9793
$tag = $m[1] . '>>LANG>>' . strtolower($m[2]);
9894
} elseif (preg_match('/^(' . $this->mpdf->allowedCSStags . '):LANG\([\'\"]{0,1}([A-Z\-]{2,11})[\'\"]{0,1}\)$/', $t, $m)) { // mPDF 6 Special case for lang as attribute selector
@@ -104,6 +100,44 @@ public function parseSimpleSelector($tags)
104100
return $tag ?: null;
105101
}
106102

103+
/**
104+
* The key for a tag, id and classes written as one part, such as P#I.C or .B.A: the tag, then the id, then the
105+
* classes in alphabetical order, so P.C#I and P#I.C give the same key, P>>ID>>I>>CLASS>>C
106+
*
107+
* @param string $tag The tag, or an empty string
108+
* @param string $names The id and classes, each with its # or .
109+
* @return string|null Null for two different ids, which no element has
110+
*/
111+
private function compoundKey($tag, $names)
112+
{
113+
preg_match_all('/([.#])(' . self::NAME . ')/', $names, $parts, PREG_SET_ORDER);
114+
115+
$id = null;
116+
$classes = [];
117+
foreach ($parts as $part) {
118+
if ($part[1] === '.') {
119+
$classes[] = $part[2];
120+
} elseif ($id !== null && $id !== $part[2]) {
121+
return null;
122+
} else {
123+
$id = $part[2];
124+
}
125+
}
126+
127+
$key = $tag === '' ? [] : [$tag];
128+
if ($id !== null) {
129+
$key[] = 'ID>>' . $id;
130+
}
131+
132+
if ($classes) {
133+
$classes = array_unique($classes);
134+
sort($classes);
135+
$key[] = 'CLASS>>' . implode('.', $classes);
136+
}
137+
138+
return implode('>>', $key);
139+
}
140+
107141
/**
108142
* Parse cascaded selector (depth > 1).
109143
*
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
<?php
2+
3+
namespace Mpdf;
4+
5+
use Yoast\PHPUnitPolyfills\TestCases\TestCase;
6+
7+
/**
8+
* Selectors that write an id and classes as one part, such as `p#i.c`, `p.c#i`, `#i.c` and `p.a.b#i`, on their own
9+
* and as parts of descendant rules.
10+
*
11+
* They are applied after `tag#id`, so each beats `p#i` and `.c`.
12+
*/
13+
class CompoundIdClassSelectorTest extends TestCase
14+
{
15+
16+
use PageStreams;
17+
18+
const GREEN = '0.000 0.502 0.000 rg';
19+
const RED = '1.000 0.000 0.000 rg';
20+
const BLACK = '0.000 g';
21+
22+
/**
23+
* The text is drawn in the colour the rules leave it in
24+
*
25+
* @dataProvider rules
26+
*
27+
* @param string $css
28+
* @param string $html
29+
* @param string $expected The fill colour the text should be drawn in
30+
*/
31+
public function testTheRuleColoursTheText($css, $html, $expected)
32+
{
33+
$colours = $this->textColours('<style>' . $css . '</style>' . $html);
34+
35+
$this->assertArrayHasKey('text', $colours);
36+
$this->assertSame($expected, $colours['text']);
37+
}
38+
39+
/**
40+
* A stylesheet, a document for it, and the colour its text should be drawn in
41+
*
42+
* @return array[]
43+
*/
44+
public function rules()
45+
{
46+
$cases = [];
47+
foreach (['p#i.c', 'p.c#i', '#i.c', 'p.a.c#i'] as $selector) {
48+
$cases[$selector] = [
49+
'.c { color: red; } p#i { color: red; } ' . $selector . ' { color: green; } p#i { color: red; } .c { color: red; }',
50+
'<p id="i" class="a c">text</p>',
51+
self::GREEN,
52+
];
53+
$cases[$selector . ' after an ancestor'] = [
54+
'div .c { color: red; } div p#i { color: red; } div ' . $selector . ' { color: green; } div p#i { color: red; }',
55+
'<div><p id="i" class="a c">text</p></div>',
56+
self::GREEN,
57+
];
58+
$cases[$selector . ' in a table cell'] = [
59+
'table .c { color: red; } table td#i { color: red; } table ' . str_replace('p', 'td', $selector) . ' { color: green; }',
60+
'<table><tr><td id="i" class="a c">text</td></tr></table>',
61+
self::GREEN,
62+
];
63+
}
64+
65+
return $cases + [
66+
'an ancestor' => [
67+
'div#o.x p { color: green; }',
68+
'<div id="o" class="x"><p>text</p></div>',
69+
self::GREEN,
70+
],
71+
'an ancestor with its classes in another order' => [
72+
'div.y#o.x p { color: green; }',
73+
'<div id="o" class="x y"><p>text</p></div>',
74+
self::GREEN,
75+
],
76+
'a table cell as the ancestor' => [
77+
'td#o.x span { color: green; }',
78+
'<table><tr><td id="o" class="x"><span>text</span></td></tr></table>',
79+
self::GREEN,
80+
],
81+
'another id' => [
82+
'p#j.c { color: red; }',
83+
'<p id="i" class="c">text</p>',
84+
self::BLACK,
85+
],
86+
'a class the element does not have' => [
87+
'p#i.c.d { color: red; }',
88+
'<p id="i" class="c">text</p>',
89+
self::BLACK,
90+
],
91+
'another tag' => [
92+
'div#i.c { color: red; }',
93+
'<p id="i" class="c">text</p>',
94+
self::BLACK,
95+
],
96+
'an ancestor with another class' => [
97+
'div#o.y p { color: red; }',
98+
'<div id="o" class="x"><p>text</p></div>',
99+
self::BLACK,
100+
],
101+
'more classes after a tag' => [
102+
'#i.c.d { color: green; } p#i.c { color: red; }',
103+
'<p id="i" class="c d">text</p>',
104+
self::GREEN,
105+
],
106+
'a tag after the same classes' => [
107+
'p#i.c { color: green; } #i.c { color: red; }',
108+
'<p id="i" class="c">text</p>',
109+
self::GREEN,
110+
],
111+
];
112+
}
113+
114+
}

‎tests/Mpdf/Css/SelectorParserTest.php‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,74 @@ public function unparseableCascadedSelectors()
8686
'in the middle' => [['DIV', '*', 'P']],
8787
'last, after two parts' => [['DIV', 'P', '>', 'SPAN']],
8888
'last, after one part' => [['TABLE', 'TR:LAST-CHILD']],
89+
'a class with a pseudo-class' => [['DIV', 'P.C:HOVER']],
90+
'an id with a pseudo-class' => [['DIV', '#I:FIRST-CHILD']],
91+
];
92+
}
93+
94+
/**
95+
* An id written with classes gives one key whatever order they are written in: the tag, the id, then the classes
96+
* in alphabetical order
97+
*
98+
* @dataProvider compoundSelectors
99+
*
100+
* @param string $selector
101+
* @param string $expected
102+
*/
103+
public function testParseSimpleSelectorGivesAnIdWithClassesOneKey($selector, $expected)
104+
{
105+
$this->assertSame($expected, $this->parser->parseSimpleSelector([$selector]));
106+
$this->assertSame(['DIV', $expected], $this->parser->parseCascadedSelector(['DIV', $selector]));
107+
}
108+
109+
/**
110+
* Parts naming an id with classes, and the key each gives
111+
*
112+
* @return array[]
113+
*/
114+
public function compoundSelectors()
115+
{
116+
return [
117+
'tag, id, class' => ['P#I.C', 'P>>ID>>I>>CLASS>>C'],
118+
'tag, class, id' => ['P.C#I', 'P>>ID>>I>>CLASS>>C'],
119+
'id, class' => ['#I.C', 'ID>>I>>CLASS>>C'],
120+
'class, id' => ['.C#I', 'ID>>I>>CLASS>>C'],
121+
'two classes around the id' => ['P.B#I.A', 'P>>ID>>I>>CLASS>>A.B'],
122+
'tag, two classes, id' => ['P.A.B#I', 'P>>ID>>I>>CLASS>>A.B'],
123+
'the same class twice' => ['.C.C', 'CLASS>>C'],
124+
'the same id twice' => ['#I#I.C', 'ID>>I>>CLASS>>C'],
125+
];
126+
}
127+
128+
/**
129+
* A part with a class or id that mPDF cannot match gives no key, so the rule is dropped
130+
*
131+
* @dataProvider malformedCompoundSelectors
132+
*
133+
* @param string $selector
134+
*/
135+
public function testParseSimpleSelectorGivesNothingForAMalformedClassOrId($selector)
136+
{
137+
$this->assertNull($this->parser->parseSimpleSelector([$selector]));
138+
}
139+
140+
/**
141+
* Parts with a class or id followed by something that is not a class or id, or with two ids
142+
*
143+
* @return array[]
144+
*/
145+
public function malformedCompoundSelectors()
146+
{
147+
return [
148+
'a class with a pseudo-class' => ['.C:HOVER'],
149+
'a tag and class with a pseudo-class' => ['P.C:FIRST-CHILD'],
150+
'an id with an attribute' => ['#I[TITLE]'],
151+
'a tag and id with a pseudo-element' => ['P#I::BEFORE'],
152+
'a child combinator without spaces' => ['.A>.B'],
153+
'two ids' => ['#I#J'],
154+
'an empty class' => ['.A..B'],
155+
'a bare dot' => ['.'],
156+
'a bare hash' => ['#'],
89157
];
90158
}
91159

0 commit comments

Comments
 (0)