WooCommerce Code Reference

CssInliner extends AbstractHtmlProcessor
in package

This class provides functions for converting CSS styles into inline style attributes in your HTML code.

Table of Contents

CONTENT_TYPE_META_TAG  = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'
DEFAULT_DOCUMENT_TYPE  = '<!DOCTYPE html>'
HTML_COMMENT_PATTERN  = '/<!--[^-]*+(?:-(?!->)[^-]*+)*+(?:-->|$)/'
regular expression pattern to match an HTML comment, including delimiters and modifiers
HTML_TEMPLATE_ELEMENT_PATTERN  = '%<template[\s>][^<]*+(?:<(?!/template>)[^<]*+)*+(?:</template>|$)%i'
regular expression pattern to match an HTML `<template>` element, including delimiters and modifiers
PHP_UNRECOGNIZED_VOID_TAGNAME_MATCHER  = '(?:command|embed|keygen|source|track|wbr)'
TAGNAME_ALLOWED_BEFORE_BODY_MATCHER  = '(?:html|head|base|command|link|meta|noscript|script|style|template|title)'
Regular expression part to match tag names that may appear before the start of the `<body>` element. A start tag for any other element would implicitly start the `<body>` element due to tag omission rules.
CACHE_KEY_COMBINED_STYLES  = 1
CACHE_KEY_SELECTOR  = 0
COMBINATOR_MATCHER  = '(?:\s++|\s*+[>+~]\s*+)(?=[[:alpha:]_\-.#*:\[])'
regular expression component to match a selector combinator
OF_TYPE_PSEUDO_CLASS_MATCHER  = '(?:first|last|nth(?:-last)?+|only)-of-type'
This regular expression componenet matches an `...of-type` pseudo class name, without the preceding ":". These pseudo-classes can currently online be inlined if they have an associated type in the selector expression.
PSEUDO_CLASS_MATCHER  = 'empty|(?:first|last|nth(?:-last)?+|only)-(?:child|of-type)|not\([[:ascii:]]*\)|root'
Regular expression component matching a static pseudo class in a selector, without the preceding ":", for which the applicable elements can be determined (by converting the selector to an XPath expression).
QSA_ALWAYS_THROW_PARSE_EXCEPTION  = 'alwaysThrowParseException'
options array key for `querySelectorAll`
$domDocument  : DOMDocument|null
$allowedMediaTypes  : array<string, bool>
$caches  : array{0: array, 1: array}
$cssSelectorConverter  : CssSelectorConverter|null
$debug  : bool
Emogrifier will throw Exceptions when it encounters an error instead of silently ignoring them.
$excludedCssSelectors  : array<non-empty-string, bool>
$excludedSelectors  : array<string, bool>
$isInlineStyleAttributesParsingEnabled  : bool
Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved.
$isStyleBlocksParsingEnabled  : bool
Determines whether the `<style>` blocks in the HTML passed to this class should be parsed.
$matchingUninlinableCssRules  : array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>|null
array of data describing CSS rules which apply to the document but cannot be inlined, in the format returned by {@see collateCssRules}
$selectorPrecedenceMatchers  : array<string, int>
For calculating selector precedence order.
$styleAttributesForNodes  : array<string, array<string, string>>
the styles to apply to the nodes with the XPath paths as array keys for the outer array and the attribute names/values as key/value pairs for the inner array
$visitedNodes  : array<string, DOMElement>
the visited nodes with the XPath paths as array keys
$xPath  : DOMXPath|null
addAllowedMediaType()  : $this
Marks a media query type to keep.
addExcludedCssSelector()  : $this
Adds a selector to exclude CSS selector from emogrification.
addExcludedSelector()  : $this
Adds a selector to exclude nodes from emogrification.
disableInlineStyleAttributesParsing()  : $this
Disables the parsing of inline styles.
disableStyleBlocksParsing()  : $this
Disables the parsing of `<style>` blocks.
fromDomDocument()  : static
Builds a new instance from the given DOM document.
fromHtml()  : static
Builds a new instance from the given HTML.
getDomDocument()  : DOMDocument
Provides access to the internal DOMDocument representation of the HTML in its current state.
getMatchingUninlinableSelectors()  : array<array-key, string>
Gets the array of selectors present in the CSS provided to `inlineCss()` for which the declarations could not be applied as inline styles, but which may affect elements in the HTML. The relevant CSS will have been placed in a `<style>` element. The selectors may include those used within `@media` rules or those involving dynamic pseudo-classes (such as `:hover`) or pseudo-elements (such as `::after`).
inlineCss()  : $this
Inlines the given CSS into the existing HTML.
removeAllowedMediaType()  : $this
Drops a media query type from the allowed list.
removeExcludedCssSelector()  : $this
No longer excludes the CSS selector from emogrification.
removeExcludedSelector()  : $this
No longer excludes the nodes matching this selector from emogrification.
render()  : string
Renders the normalized and processed HTML.
renderBodyContent()  : string
Renders the content of the BODY element of the normalized and processed HTML.
setDebug()  : $this
Sets the debug mode.
addStyleElementToDocument()  : void
Adds a style element with $css to $this->domDocument.
getHtmlElement()  : DOMElement
Returns the HTML element.
getXPath()  : DOMXPath
__construct()  : mixed
The constructor.
addContentTypeMetaTag()  : string
Adds a Content-Type meta tag for the charset.
attributeValueIsImportant()  : bool
Checks whether $attributeValue is marked as !important.
clearAllCaches()  : void
Clears all caches.
collateCssRules()  : array<string, array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>>
Collates the individual rules from a `CssDocument` object.
copyInlinableCssToStyleAttribute()  : void
Copies $cssRule into the style attribute of $node.
copyUninlinableCssToStyleNode()  : void
Applies `$this->matchingUninlinableCssRules` to `$this->domDocument` by placing them as CSS in a `<style>` element.
createRawDomDocument()  : void
Creates a DOMDocument instance from the given HTML and stores it in $this->domDocument.
createUnifiedDomDocument()  : void
Creates a DOM document from the given HTML and stores it in $this->domDocument.
determineMatchingUninlinableCssRules()  : void
Determines which of `$cssRules` actually apply to `$this->domDocument`, and sets them in `$this->matchingUninlinableCssRules`.
ensureDocumentType()  : string
Makes sure that the passed HTML has a document type, with lowercase "html".
ensureExistenceOfBodyElement()  : void
Checks that $this->domDocument has a BODY element and adds it if it is missing.
ensureNodeIsElement()  : DOMElement
ensurePhpUnrecognizedSelfClosingTagsAreXml()  : string
Makes sure that any self-closing tags not recognized as such by PHP's DOMDocument implementation have a self-closing slash.
existsMatchForCssSelector()  : bool
Checks whether there is at least one matching element for $cssSelector.
existsMatchForSelectorInCssRule()  : bool
Checks whether there is at least one matching element for the CSS selector contained in the `selector` element of the provided CSS rule.
fillStyleAttributesWithMergedStyles()  : void
Merges styles from styles attributes and style nodes and applies them to the attribute nodes
generateStyleStringFromDeclarationsArrays()  : string
This method merges old or existing name/value array with new name/value array and then generates a string of the combined style suitable for placing inline.
generateStyleStringFromSingleDeclarationsArray()  : string
Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array.
getAllNodesWithStyleAttribute()  : DOMNodeList
Returns a list with all DOM nodes that have a style attribute.
getBodyElement()  : DOMElement
Returns the BODY element.
getCssFromAllStyleNodes()  : string
Returns CSS content.
getCssSelectorConverter()  : CssSelectorConverter
getCssSelectorPrecedence()  : int
getHeadElement()  : DOMElement
Returns the HEAD element.
getMatchingUninlinableCssRules()  : array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>
getNodesToExclude()  : array<int, DOMElement>
Find the nodes that are not to be emogrified.
hasContentTypeMetaTagInHead()  : bool
Tests whether the given HTML has a valid `Content-Type` metadata element within the `<head>` element. Due to tag omission rules, HTML parsers are expected to end the `<head>` element and start the `<body>` element upon encountering a start tag for any element which is permitted only within the `<body>`.
hasEndOfHeadElement()  : bool
Tests whether the `<head>` element ends within the given HTML. Due to tag omission rules, HTML parsers are expected to end the `<head>` element and start the `<body>` element upon encountering a start tag for any element which is permitted only within the `<body>`.
hasUnsupportedPseudoClass()  : bool
Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for inlining CSS declarations.
normalizeDocumentType()  : string
Makes sure the document type in the passed HTML has lowercase "html".
normalizeStyleAttributes()  : void
Normalizes the value of the "style" attribute and saves it.
normalizeStyleAttributesOfAllNodes()  : void
Parses the document and normalizes all existing CSS attributes.
prepareHtmlForDomConversion()  : string
Returns the HTML with added document type, Content-Type meta tag, and self-closing slashes, if needed, ensuring that the HTML will be good for creating a DOM document from it.
purgeVisitedNodes()  : void
Purges the visited nodes.
querySelectorAll()  : DOMNodeList<string|int, DOMNode>
removeHtmlComments()  : string
Removes comments from the given HTML, including any which are unterminated, for which the remainder of the string is removed.
removeHtmlTemplateElements()  : string
Removes `<template>` elements from the given HTML, including any without an end tag, for which the remainder of the string is removed.
removeImportantAnnotationFromAllInlineStyles()  : void
Searches for all nodes with a style attribute and removes the "!important" annotations out of the inline style declarations, eventually by rearranging declarations.
removeImportantAnnotationFromNodeInlineStyle()  : void
Removes the "!important" annotations out of the inline style declarations, eventually by rearranging declarations.
removeSelectorComponents()  : string
Removes components from a CSS selector, replacing them with "*" if necessary.
removeSelfClosingTagsClosingTags()  : string
Eliminates any invalid closing tags for void elements from the given HTML.
removeUnmatchablePseudoComponents()  : string
Removes pseudo-elements and dynamic pseudo-classes from a CSS selector, replacing them with "*" if necessary.
removeUnsupportedOfTypePseudoClasses()  : string
Removes any `...-of-type` pseudo-classes from part of a CSS selector, if it does not have a type, replacing them with "*" if necessary.
replaceUnmatchableNotComponent()  : string
Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument contains pseudo-elements or dynamic pseudo-classes.
selectorPartHasUnsupportedOfTypePseudoClass()  : bool
Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath expression.
setDomDocument()  : void
setHtml()  : void
Sets the HTML to process.
sortBySelectorPrecedence()  : int

Constants

TAGNAME_ALLOWED_BEFORE_BODY_MATCHER

Regular expression part to match tag names that may appear before the start of the `<body>` element. A start tag for any other element would implicitly start the `<body>` element due to tag omission rules.

protected string TAGNAME_ALLOWED_BEFORE_BODY_MATCHER = '(?:html|head|base|command|link|meta|noscript|script|style|template|title)'

OF_TYPE_PSEUDO_CLASS_MATCHER

This regular expression componenet matches an `...of-type` pseudo class name, without the preceding ":". These pseudo-classes can currently online be inlined if they have an associated type in the selector expression.

private string OF_TYPE_PSEUDO_CLASS_MATCHER = '(?:first|last|nth(?:-last)?+|only)-of-type'

PSEUDO_CLASS_MATCHER

Regular expression component matching a static pseudo class in a selector, without the preceding ":", for which the applicable elements can be determined (by converting the selector to an XPath expression).

private string PSEUDO_CLASS_MATCHER = 'empty|(?:first|last|nth(?:-last)?+|only)-(?:child|of-type)|not\([[:ascii:]]*\)|root'

(Contains alternation without a group and is intended to be placed within a capturing, non-capturing or lookahead group, as appropriate for the usage context.)

Properties

$isInlineStyleAttributesParsingEnabled

Determines whether the "style" attributes of tags in the the HTML passed to this class should be preserved.

private bool $isInlineStyleAttributesParsingEnabled = true

If set to false, the value of the style attributes will be discarded.

$isStyleBlocksParsingEnabled

Determines whether the `<style>` blocks in the HTML passed to this class should be parsed.

private bool $isStyleBlocksParsingEnabled = true

If set to true, the <style> blocks will be removed from the HTML and their contents will be applied to the HTML via inline styles.

If set to false, the <style> blocks will be left as they are in the HTML.

$matchingUninlinableCssRules

array of data describing CSS rules which apply to the document but cannot be inlined, in the format returned by {@see collateCssRules}

private array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>|null $matchingUninlinableCssRules = null

$selectorPrecedenceMatchers

For calculating selector precedence order.

private array<string, int> $selectorPrecedenceMatchers = [ // IDs: worth 10000 '\#' => 10000, // classes, attributes, pseudo-classes (not pseudo-elements) except `:not`: worth 100 '(?:\.|\[|(?<!:):(?!not\())' => 100, // elements (not attribute values or `:not`), pseudo-elements: worth 1 '(?:(?<![="':\w\-])|::)' => 1, ]

Keys are a regular expression part to match before a CSS name. Values are a multiplier factor per match to weight specificity.

$styleAttributesForNodes

the styles to apply to the nodes with the XPath paths as array keys for the outer array and the attribute names/values as key/value pairs for the inner array

private array<string, array<string, string>> $styleAttributesForNodes = []

Methods

addAllowedMediaType()

Marks a media query type to keep.

public addAllowedMediaType(string $mediaName) : $this
Parameters
$mediaName : string

the media type name, e.g., "braille"

Return values
$this

addExcludedCssSelector()

Adds a selector to exclude CSS selector from emogrification.

public addExcludedCssSelector(non-empty-string $selector) : $this
Parameters
$selector : non-empty-string

the selector to exclude, e.g., .editor

Return values
$this

addExcludedSelector()

Adds a selector to exclude nodes from emogrification.

public addExcludedSelector(string $selector) : $this

Any nodes that match the selector will not have their style altered.

Parameters
$selector : string

the selector to exclude, e.g., ".editor"

Return values
$this

fromHtml()

Builds a new instance from the given HTML.

public static fromHtml(string $unprocessedHtml) : static
Parameters
$unprocessedHtml : string

raw HTML, must be UTF-encoded, must not be empty

Tags
throws
InvalidArgumentException

if $unprocessedHtml is anything other than a non-empty string

Return values
static

getMatchingUninlinableSelectors()

Gets the array of selectors present in the CSS provided to `inlineCss()` for which the declarations could not be applied as inline styles, but which may affect elements in the HTML. The relevant CSS will have been placed in a `<style>` element. The selectors may include those used within `@media` rules or those involving dynamic pseudo-classes (such as `:hover`) or pseudo-elements (such as `::after`).

public getMatchingUninlinableSelectors() : array<array-key, string>
Tags
throws
BadMethodCallException

if inlineCss has not been called first

Return values
array<array-key, string>

inlineCss()

Inlines the given CSS into the existing HTML.

public inlineCss([string $css = '' ]) : $this
Parameters
$css : string = ''

the CSS to inline, must be UTF-8-encoded

Tags
throws
ParseException

in debug mode, if an invalid selector is encountered

throws
RuntimeException

in debug mode, if an internal PCRE error occurs or CssSelectorConverter::toXPath returns an invalid XPath expression

throws
UnexpectedValueException

if a selector query result includes a node which is not a DOMElement

Return values
$this

removeAllowedMediaType()

Drops a media query type from the allowed list.

public removeAllowedMediaType(string $mediaName) : $this
Parameters
$mediaName : string

the tag name, e.g., "braille"

Return values
$this

removeExcludedCssSelector()

No longer excludes the CSS selector from emogrification.

public removeExcludedCssSelector(non-empty-string $selector) : $this
Parameters
$selector : non-empty-string

the selector to no longer exclude, e.g., .editor

Return values
$this

removeExcludedSelector()

No longer excludes the nodes matching this selector from emogrification.

public removeExcludedSelector(string $selector) : $this
Parameters
$selector : string

the selector to no longer exclude, e.g., ".editor"

Return values
$this

attributeValueIsImportant()

Checks whether $attributeValue is marked as !important.

private attributeValueIsImportant(string $attributeValue) : bool
Parameters
$attributeValue : string
Return values
bool

collateCssRules()

Collates the individual rules from a `CssDocument` object.

private collateCssRules(CssDocument $parsedCss) : array<string, array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>>
Parameters
$parsedCss : CssDocument
Return values
array<string, array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>>This 2-entry array has the key "inlinable" containing rules which can be inlined as `style` attributes and the key "uninlinable" containing rules which cannot. Each value is an array of sub-arrays with the following keys: - "media" (the media query string, e.g. "@media screen and (max-width: 480px)", or an empty string if not from a `@media` rule); - "selector" (the CSS selector, e.g., "*" or "header h1"); - "hasUnmatchablePseudo" (`true` if that selector contains pseudo-elements or dynamic pseudo-classes such that the declarations cannot be applied inline); - "declarationsBlock" (the semicolon-separated CSS declarations for that selector, e.g., `color: red; height: 4px;`); - "line" (the line number, e.g. 42).

copyInlinableCssToStyleAttribute()

Copies $cssRule into the style attribute of $node.

private copyInlinableCssToStyleAttribute(DOMElement $node, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int} $cssRule) : void

Note: This method does not check whether $cssRule matches $node.

Parameters
$node : DOMElement
$cssRule : array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}
Return values
void

copyUninlinableCssToStyleNode()

Applies `$this->matchingUninlinableCssRules` to `$this->domDocument` by placing them as CSS in a `<style>` element.

private copyUninlinableCssToStyleNode(CssDocument $parsedCss) : void

If there are no uninlinable CSS rules to copy there, a <style> element will be created containing only the applicable at-rules from $parsedCss. If there are none of either, an empty <style> element will not be created.

Parameters
$parsedCss : CssDocument

This may contain various at-rules whose content CssInliner does not currently attempt to inline or process in any other way, such as @import, @font-face, @keyframes, etc., and which should precede the processed but found-to-be-uninlinable CSS placed in the <style> element. Note that CssInliner processes @media rules so that they can be ordered correctly with respect to other uninlinable rules; these will not be duplicated from $parsedCss.

Return values
void

createUnifiedDomDocument()

Creates a DOM document from the given HTML and stores it in $this->domDocument.

private createUnifiedDomDocument(string $html) : void

The DOM document will always have a BODY element and a document type.

Parameters
$html : string
Return values
void

determineMatchingUninlinableCssRules()

Determines which of `$cssRules` actually apply to `$this->domDocument`, and sets them in `$this->matchingUninlinableCssRules`.

private determineMatchingUninlinableCssRules(array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}> $cssRules) : void
Parameters
$cssRules : array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>

the "uninlinable" array of CSS rules returned by collateCssRules

Return values
void

ensureNodeIsElement()

private ensureNodeIsElement(DOMNode $node) : DOMElement
Parameters
$node : DOMNode
Tags
throws
UnexpectedValueException

if $node is not a DOMElement

Return values
DOMElement

ensurePhpUnrecognizedSelfClosingTagsAreXml()

Makes sure that any self-closing tags not recognized as such by PHP's DOMDocument implementation have a self-closing slash.

private ensurePhpUnrecognizedSelfClosingTagsAreXml(string $html) : string
Parameters
$html : string
Return values
stringHTML with problematic tags converted.

existsMatchForCssSelector()

Checks whether there is at least one matching element for $cssSelector.

private existsMatchForCssSelector(string $cssSelector) : bool

When not in debug mode, it returns true also for invalid selectors (because they may be valid, just not implemented/recognized yet by Emogrifier).

Parameters
$cssSelector : string
Tags
throws
ParseException

in debug mode, if an invalid selector is encountered

throws
RuntimeException

in debug mode, if CssSelectorConverter::toXPath returns an invalid XPath expression

Return values
bool

existsMatchForSelectorInCssRule()

Checks whether there is at least one matching element for the CSS selector contained in the `selector` element of the provided CSS rule.

private existsMatchForSelectorInCssRule(array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int} $cssRule) : bool

Any dynamic pseudo-classes will be assumed to apply. If the selector matches a pseudo-element, it will test for a match with its originating element.

Parameters
$cssRule : array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}
Tags
throws
ParseException
Return values
bool

fillStyleAttributesWithMergedStyles()

Merges styles from styles attributes and style nodes and applies them to the attribute nodes

private fillStyleAttributesWithMergedStyles() : void
Return values
void

generateStyleStringFromDeclarationsArrays()

This method merges old or existing name/value array with new name/value array and then generates a string of the combined style suitable for placing inline.

private generateStyleStringFromDeclarationsArrays(array<string, string> $oldStyles, array<string, string> $newStyles) : string

This becomes the single point for CSS string generation allowing for consistent CSS output no matter where the CSS originally came from.

Parameters
$oldStyles : array<string, string>
$newStyles : array<string, string>
Tags
throws
UnexpectedValueException

if an empty property name is encountered (which should not happen)

Return values
string

generateStyleStringFromSingleDeclarationsArray()

Generates a CSS style string suitable to be used inline from the $styleDeclarations property => value array.

private generateStyleStringFromSingleDeclarationsArray(array<string, string> $styleDeclarations) : string
Parameters
$styleDeclarations : array<string, string>
Return values
string

getAllNodesWithStyleAttribute()

Returns a list with all DOM nodes that have a style attribute.

private getAllNodesWithStyleAttribute() : DOMNodeList
Tags
throws
RuntimeException
Return values
DOMNodeList

getHeadElement()

Returns the HEAD element.

private getHeadElement() : DOMElement

This method assumes that there always is a HEAD element.

Tags
throws
UnexpectedValueException
Return values
DOMElement

getMatchingUninlinableCssRules()

private getMatchingUninlinableCssRules() : array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>
Tags
throws
BadMethodCallException

if inlineCss has not been called first

Return values
array<array-key, array{media: string, selector: string, hasUnmatchablePseudo: bool, declarationsBlock: string, line: int}>

getNodesToExclude()

Find the nodes that are not to be emogrified.

private getNodesToExclude() : array<int, DOMElement>
Tags
throws
ParseException

in debug mode, if an invalid selector is encountered

throws
RuntimeException

in debug mode, if CssSelectorConverter::toXPath returns an invalid XPath expression

throws
UnexpectedValueException

if the selector query result includes a node which is not a DOMElement

Return values
array<int, DOMElement>

hasContentTypeMetaTagInHead()

Tests whether the given HTML has a valid `Content-Type` metadata element within the `<head>` element. Due to tag omission rules, HTML parsers are expected to end the `<head>` element and start the `<body>` element upon encountering a start tag for any element which is permitted only within the `<body>`.

private hasContentTypeMetaTagInHead(string $html) : bool
Parameters
$html : string
Return values
bool

hasEndOfHeadElement()

Tests whether the `<head>` element ends within the given HTML. Due to tag omission rules, HTML parsers are expected to end the `<head>` element and start the `<body>` element upon encountering a start tag for any element which is permitted only within the `<body>`.

private hasEndOfHeadElement(string $html) : bool
Parameters
$html : string
Tags
throws
RuntimeException
Return values
bool

hasUnsupportedPseudoClass()

Tests if a selector contains a pseudo-class which would mean it cannot be converted to an XPath expression for inlining CSS declarations.

private hasUnsupportedPseudoClass(string $selector) : bool

Any pseudo class that does not match {@see} cannot be converted. Additionally, ...of-type pseudo-classes cannot be converted if they are not associated with a type selector.

Parameters
$selector : string
Return values
bool

normalizeStyleAttributes()

Normalizes the value of the "style" attribute and saves it.

private normalizeStyleAttributes(DOMElement $node) : void
Parameters
$node : DOMElement
Return values
void

normalizeStyleAttributesOfAllNodes()

Parses the document and normalizes all existing CSS attributes.

private normalizeStyleAttributesOfAllNodes() : void

This changes 'DISPLAY: none' to 'display: none'. We wouldn't have to do this if DOMXPath supported XPath 2.0. Also stores a reference of nodes with existing inline styles so we don't overwrite them.

Return values
void

prepareHtmlForDomConversion()

Returns the HTML with added document type, Content-Type meta tag, and self-closing slashes, if needed, ensuring that the HTML will be good for creating a DOM document from it.

private prepareHtmlForDomConversion(string $html) : string
Parameters
$html : string
Return values
stringthe unified HTML

querySelectorAll()

private querySelectorAll(string $selectors[, array{}|array{alwaysThrowParseException: bool} $options = [] ]) : DOMNodeList<string|int, DOMNode>
Parameters
$selectors : string
$options : array{}|array{alwaysThrowParseException: bool} = []

This is an array of option values to control behaviour:

  • QSA_ALWAYS_THROW_PARSE_EXCEPTION - bool - throw any ParseException regardless of debug setting.
Tags
throws
ParseException

in debug mode (or with QSA_ALWAYS_THROW_PARSE_EXCEPTION option), if an invalid selector is encountered

throws
RuntimeException

in debug mode, if CssSelectorConverter::toXPath returns an invalid XPath expression

Return values
DOMNodeList<string|int, DOMNode>the HTML elements that match the provided CSS `$selectors`

removeHtmlComments()

Removes comments from the given HTML, including any which are unterminated, for which the remainder of the string is removed.

private removeHtmlComments(string $html) : string
Parameters
$html : string
Tags
throws
RuntimeException
Return values
string

removeHtmlTemplateElements()

Removes `<template>` elements from the given HTML, including any without an end tag, for which the remainder of the string is removed.

private removeHtmlTemplateElements(string $html) : string
Parameters
$html : string
Tags
throws
RuntimeException
Return values
string

removeImportantAnnotationFromAllInlineStyles()

Searches for all nodes with a style attribute and removes the "!important" annotations out of the inline style declarations, eventually by rearranging declarations.

private removeImportantAnnotationFromAllInlineStyles() : void
Tags
throws
RuntimeException
Return values
void

removeImportantAnnotationFromNodeInlineStyle()

Removes the "!important" annotations out of the inline style declarations, eventually by rearranging declarations.

private removeImportantAnnotationFromNodeInlineStyle(DOMElement $node) : void

Rearranging needed when !important shorthand properties are followed by some of their not !important expanded-version properties. For example "font: 12px serif !important; font-size: 13px;" must be reordered to "font-size: 13px; font: 12px serif;" in order to remain correct.

Parameters
$node : DOMElement
Tags
throws
RuntimeException
Return values
void

removeSelectorComponents()

Removes components from a CSS selector, replacing them with "*" if necessary.

private removeSelectorComponents(string $matcher, string $selector) : string
Parameters
$matcher : string

regular expression part to match the components to remove

$selector : string
Return values
stringselector which will match the relevant DOM elements if the removed components are assumed to apply (or in the case of pseudo-elements will match their originating element)

removeUnmatchablePseudoComponents()

Removes pseudo-elements and dynamic pseudo-classes from a CSS selector, replacing them with "*" if necessary.

private removeUnmatchablePseudoComponents(string $selector) : string

If such a pseudo-component is within the argument of :not, the entire :not component is removed or replaced.

Parameters
$selector : string
Return values
stringselector which will match the relevant DOM elements if the pseudo-classes are assumed to apply, or in the case of pseudo-elements will match their originating element

removeUnsupportedOfTypePseudoClasses()

Removes any `...-of-type` pseudo-classes from part of a CSS selector, if it does not have a type, replacing them with "*" if necessary.

private removeUnsupportedOfTypePseudoClasses(string $selectorPart) : string
Parameters
$selectorPart : string

part of a selector which has been split up at combinators

Return values
stringselector part which will match the relevant DOM elements if the pseudo-classes are assumed to apply

replaceUnmatchableNotComponent()

Helps `removeUnmatchablePseudoComponents()` replace or remove a selector `:not(...)` component if its argument contains pseudo-elements or dynamic pseudo-classes.

private replaceUnmatchableNotComponent(array<array-key, string> $matches) : string
Parameters
$matches : array<array-key, string>

array of elements matched by the regular expression

Return values
stringthe full match if there were no unmatchable pseudo components within; otherwise, any preceding combinator followed by "*", or an empty string if there was no preceding combinator

selectorPartHasUnsupportedOfTypePseudoClass()

Tests if part of a selector contains an `...of-type` pseudo-class such that it cannot be converted to an XPath expression.

private selectorPartHasUnsupportedOfTypePseudoClass(string $selectorPart) : bool
Parameters
$selectorPart : string

part of a selector which has been split up at combinators

Return values
bool`true` if the selector part does not have a type but does have an `...of-type` pseudo-class

sortBySelectorPrecedence()

private sortBySelectorPrecedence(array{selector: string, line: int} $first, array{selector: string, line: int} $second) : int
Parameters
$first : array{selector: string, line: int}
$second : array{selector: string, line: int}
Return values
int