@@ -20,6 +20,52 @@ class AMP_Layout_Sanitizer extends AMP_Base_Sanitizer {
2020 public function sanitize () {
2121 $ xpath = new DOMXPath ( $ this ->dom );
2222
23+ /*
24+ * Convert all percentage-based width or height values into style properties.
25+ *
26+ * The following query could be made simpler by using the `ends-with` function, but it is not a valid function in
27+ * XPath 1.0, which the `DOMXPath` class uses.
28+ */
29+ $ nodes = $ xpath ->query ( '//*[ "%" = substring( @width, string-length( @width ) ) or "%" = substring( @height, string-length( @height ) ) ] ' );
30+
31+ foreach ( $ nodes as $ node ) {
32+ $ width = $ node ->getAttribute ( 'width ' );
33+ $ height = $ node ->getAttribute ( 'height ' );
34+ $ style = $ node ->getAttribute ( 'style ' );
35+
36+ $ styles = $ this ->is_empty_attribute_value ( $ style ) ? [] : $ this ->parse_style_string ( $ style );
37+ $ attr_converted = false ;
38+
39+ // Convert the percentage-based width attribute to a style property.
40+ if ( ! isset ( $ styles ['width ' ] ) && '% ' === substr ( $ width , -1 ) ) {
41+ // Ignore if its an AMP component and the width is `100%`.
42+ if ( '100% ' === $ width && strpos ( $ node ->tagName , 'amp- ' ) === 0 ) {
43+ continue ;
44+ }
45+
46+ $ styles ['width ' ] = $ width ;
47+ $ attr_converted = true ;
48+ $ node ->removeAttribute ( 'width ' );
49+ }
50+
51+ // Convert the percentage-based height attribute to a style property.
52+ if ( ! isset ( $ styles ['height ' ] ) && '% ' === substr ( $ height , -1 ) ) {
53+ // Ignore if its an AMP component and the height is `100%`.
54+ if ( '100% ' === $ height && strpos ( $ node ->tagName , 'amp- ' ) === 0 ) {
55+ continue ;
56+ }
57+
58+ $ styles ['height ' ] = $ height ;
59+ $ attr_converted = true ;
60+ $ node ->removeAttribute ( 'height ' );
61+ }
62+
63+ // If either dimension was converted, update the style property with it.
64+ if ( $ attr_converted ) {
65+ $ node ->setAttribute ( 'style ' , $ this ->reassemble_style_string ( $ styles ) );
66+ }
67+ }
68+
2369 /**
2470 * Sanitize AMP nodes to be AMP compatible. Elements with the `layout` attribute will be validated by
2571 * `AMP_Tag_And_Attribute_Sanitizer`.
0 commit comments