Repository navigation
Fix integrity hash not rendering due to quote mismatch - #34
Conversation
The output_integrity_for_script() and output_integrity_for_style() functions use str_replace() looking for single-quoted attributes (src=' and href='), but WordPress and plugins may output tags with double quotes. This change uses preg_replace() with a pattern that captures the quote character and reuses it in the replacement, supporting both quote styles.
|
I'd like to see some automated tests for the cases this fix covers, please. We missed them in the existing tests, so it would be great to know we can confirm the functionality and easily spot any regression. |
Cover single- and double-quoted src/href for scripts and styles, and the no-hash passthrough case.
7f07e28 to
eb2b47a
Compare
|
Thanks for the review. @jerico @mikelittle I've added the unit tests in
The full suite passes locally in the |
rmccue
left a comment
There was a problem hiding this comment.
The regexes are overly complex with the capture groups here for no reason, which hurts readability of the code; in both cases, the attribute is fixed so there's no point capturing it.
| '/( src=)([\'"])/', | ||
| sprintf( | ||
| " integrity='%s' src='", | ||
| ' integrity=$2%s$2$1$2', |
There was a problem hiding this comment.
| '/( src=)([\'"])/', | |
| sprintf( | |
| " integrity='%s' src='", | |
| ' integrity=$2%s$2$1$2', | |
| '/ src=([\'"])/', | |
| sprintf( | |
| ' integrity=$1%s$1 src=$1', |
| '/( href=)([\'"])/', | ||
| sprintf( | ||
| " integrity='%s' href='", | ||
| ' integrity=$2%s$2$1$2', |
There was a problem hiding this comment.
| '/( href=)([\'"])/', | |
| sprintf( | |
| " integrity='%s' href='", | |
| ' integrity=$2%s$2$1$2', | |
| '/ href=([\'"])/', | |
| sprintf( | |
| ' integrity=$1%s$1 href=$1', |
|
Thanks @rmccue, good catch. I've applied both suggestions. |
Problem
The
output_integrity_for_script()andoutput_integrity_for_style()functions usestr_replace()looking for single-quoted attributes (src='andhref='), but WordPress core and plugins may output script/style tags with double quotes.This causes the integrity hash to be generated but never rendered in the HTML output.
Solution
Replace
str_replace()withpreg_replace()using a pattern that captures the quote character (['"]) and reuses it in the replacement string. This supports both single and double quote styles.Before
After
Testing