diff --git a/includes/rules/img_alt_long.php b/includes/rules/img_alt_long.php index e66388bd..58c782e5 100644 --- a/includes/rules/img_alt_long.php +++ b/includes/rules/img_alt_long.php @@ -17,11 +17,20 @@ function edac_rule_img_alt_long( $content, $post ) { // phpcs:ignore -- $post is $dom = $content['html']; $errors = array(); $images = $dom->find( 'img' ); + + /** + * Filter the max alt text length checked by the img_alt_long rule before it is considered an issue. + * + * @since 1.11.0 + * + * @param int $length The length used in the rule to determine the max length before flagging as an issue. + */ + $max_alt_length = max( 1, absint( apply_filters( 'edac_max_alt_length', 300 ) ) ); foreach ( $images as $image ) { if ( isset( $image ) && $image->hasAttribute( 'alt' ) && $image->getAttribute( 'alt' ) !== '' ) { $alt = $image->getAttribute( 'alt' ); - if ( strlen( $alt ) > 300 ) { + if ( strlen( $alt ) > $max_alt_length ) { $image_code = $image; $errors[] = $image_code; } diff --git a/tests/phpunit/EDACRuleImgAltLongTest.php b/tests/phpunit/EDACRuleImgAltLongTest.php new file mode 100644 index 00000000..cdfa3d57 --- /dev/null +++ b/tests/phpunit/EDACRuleImgAltLongTest.php @@ -0,0 +1,72 @@ +'; + $dom = str_get_html( $html ); + $content = array( + 'html' => $dom, + ); + $post = null; + $errors = edac_rule_img_alt_long( $content, $post ); + $this->assertEmpty( $errors ); + } + + /** + * Test that edac_rule_img_alt_long function returns an array with errors when images have alt text longer than the allowed length. + * + * @return void + */ + public function test_returns_errors_when_alt_text_is_longer_than_allowed_length() { + $html = '' . str_repeat( 'a', 301 ) . ''; + $dom = str_get_html( $html ); + $content = array( + 'html' => $dom, + ); + $post = null; + $errors = edac_rule_img_alt_long( $content, $post ); + $this->assertNotEmpty( $errors ); + } + + /** + * Test that the edac_max_alt_length filter modifies the maximum allowed alt text length. + * + * @return void + */ + public function test_edac_max_alt_length_filter_modifies_max_alt_length() { + // Add a filter to modify the maximum alt text length. + add_filter( + 'edac_max_alt_length', + function () { + return 10; + } + ); + + $html = 'This is a long alt text'; + $dom = str_get_html( $html ); + $content = array( + 'html' => $dom, + ); + $post = null; + $errors = edac_rule_img_alt_long( $content, $post ); + + // Remove the filter after the test. + remove_filter( 'edac_max_alt_length', '__return_true' ); + + $this->assertNotEmpty( $errors ); + } +}