From 4751edbced737728e5fa543362a0e3907b949b1b Mon Sep 17 00:00:00 2001 From: Grigore Mihai Date: Thu, 26 Sep 2019 15:46:58 +0300 Subject: [PATCH] fix: searching through multiple classes the right way, added tests --- inc/tag_replacer.php | 21 ++++++++- tests/test-lazyload-class-exclusion.php | 60 +++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 tests/test-lazyload-class-exclusion.php diff --git a/inc/tag_replacer.php b/inc/tag_replacer.php index 27dd006a..6a78e55d 100644 --- a/inc/tag_replacer.php +++ b/inc/tag_replacer.php @@ -55,10 +55,27 @@ public function init() { } public function contains_banned_lazyload_class( $image_tag ) { + $class_list = strstr( $image_tag, 'class="' ); + $tmp_class_list = $class_list; + if ( $class_list === false ) { + return false; + } foreach ( self::$filters[ Optml_Settings::FILTER_TYPE_LAZYLOAD ][ Optml_Settings::FILTER_CLASS ] as $rule_flag => $status ) { - $regex = '/(class="*' . $rule_flag . '*")/m'; - return preg_match( $regex, $image_tag ); + $class = strtok( $tmp_class_list, '" ' ); + $loop = true; + while ( $class !== false && $loop === true ) { + if ( substr( $class, -1 ) === '"' ) { + $class = substr( $class, 0, strlen( $class ) - 1 ); + $loop = false; + } + if ( $class === $rule_flag ) { + return true; + } + $class = strtok( ' ' ); + } + $tmp_class_list = $class_list; } + return false; } diff --git a/tests/test-lazyload-class-exclusion.php b/tests/test-lazyload-class-exclusion.php new file mode 100644 index 00000000..78e1a84e --- /dev/null +++ b/tests/test-lazyload-class-exclusion.php @@ -0,0 +1,60 @@ +update('service_data', [ + 'cdn_key' => 'test123', + 'cdn_secret' => '12345', + 'whitelist' => ['example.com'], + ]); + + $settings->update('lazyload', 'enabled'); + $settings->update('filters', array( + Optml_Settings::FILTER_TYPE_LAZYLOAD => array ( + Optml_Settings::FILTER_CLASS => array ( + 'test' => true, + 'whatever' => true, + 'testing' => true, + ) + ))); + Optml_Url_Replacer::instance()->init(); + Optml_Tag_Replacer::instance()->init(); + Optml_Lazyload_Replacer::instance()->init(); + Optml_Manager::instance()->init(); + + self::$sample_attachement = self::factory()->attachment->create_upload_object(OPTML_PATH . 'assets/img/logo.png'); + } + + public function test_class_exclusions() + { + $content = '
+ ; + ; + ; + +
'; + $replaced_content = Optml_Manager::instance()->process_images_from_content($content); + var_dump($replaced_content); + $this->assertEquals( 3, substr_count( $replaced_content, 'i.optimole.com' ) ); + $this->assertNotContains('data-opt-src', $replaced_content); + + } +}