diff --git a/phpcs-sniffs/PluginCheck/Sniffs/CodeAnalysis/OffloadingSniff.php b/phpcs-sniffs/PluginCheck/Sniffs/CodeAnalysis/OffloadingSniff.php index eb4b61450..a50776dbe 100644 --- a/phpcs-sniffs/PluginCheck/Sniffs/CodeAnalysis/OffloadingSniff.php +++ b/phpcs-sniffs/PluginCheck/Sniffs/CodeAnalysis/OffloadingSniff.php @@ -65,19 +65,21 @@ public function process_token( $stackPtr ) { return; } - // Only match HTML markup not arbitrary strings, as those could be covered by EnqueuedResourceOffloadingSniff already. - - if ( - false === strpos( $content, 'tokens[ $stackPtr ]['nested_parenthesis'] ) ) { + foreach ( $this->tokens[ $stackPtr ]['nested_parenthesis'] as $opener => $closer ) { + $prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $opener - 1 ), null, true ); + if ( false !== $prev && \T_STRING === $this->tokens[ $prev ]['code'] ) { + $function_name = $this->tokens[ $prev ]['content']; + if ( in_array( $function_name, array( 'wp_enqueue_script', 'wp_enqueue_style', 'wp_register_script', 'wp_register_style' ), true ) ) { + return ( $end_ptr + 1 ); + } + } + } } + // First check: Always check against known offloading services pattern for all strings. $pattern = $this->get_offloading_services_pattern(); $matches = array(); @@ -92,6 +94,20 @@ public function process_token( $stackPtr ) { return ( $end_ptr + 1 ); } + // Second check: For HTML markup strings only, also check file extension-based patterns. + // This is limited to HTML context to avoid false positives on arbitrary URLs. + + if ( + false === strpos( $content, ' + + 'https://cdn.jsdelivr.net/npm/intl-tel-input@21.2.4/build/js/intlTelInput.min.js', +); + +// CDN URL in array assignment for CSS. +$assets[] = array( + 'type' => 'css', + 'url' => 'https://cdn.jsdelivr.net/npm/intl-tel-input@21.2.4/build/css/intlTelInput.css', +); + +// CDN URL in variable assignment. +$script_url = 'https://unpkg.com/some-library@1.0.0/dist/lib.js'; + +// Non-CDN URL should NOT be flagged. +$api_url = 'https://api.example.com/data'; + +// Non-CDN safe URL should NOT be flagged. +$safe_url = 'https://mysite.com/wp-content/themes/my-theme/style.css'; diff --git a/phpcs-sniffs/PluginCheck/Tests/CodeAnalysis/OffloadingUnitTest.php b/phpcs-sniffs/PluginCheck/Tests/CodeAnalysis/OffloadingUnitTest.php index 6b7c77572..c8f1aa48d 100644 --- a/phpcs-sniffs/PluginCheck/Tests/CodeAnalysis/OffloadingUnitTest.php +++ b/phpcs-sniffs/PluginCheck/Tests/CodeAnalysis/OffloadingUnitTest.php @@ -23,9 +23,12 @@ final class OffloadingUnitTest extends AbstractSniffUnitTest { */ public function getErrorList() { return array( - 1 => 1, - 3 => 1, - 5 => 1, + 1 => 1, + 3 => 1, + 5 => 1, + 11 => 1, + 17 => 1, + 21 => 1, ); }