Browse Source

Merge pull request #11571 from LifeOrYou/issue-11568

Fix style/script tag contents counting toward content length when they should not.
Mark Story 8 years ago
parent
commit
8fc1a55c23
2 changed files with 19 additions and 1 deletions
  1. 14 1
      src/Utility/Text.php
  2. 5 0
      tests/TestCase/Utility/TextTest.php

+ 14 - 1
src/Utility/Text.php

@@ -30,6 +30,16 @@ class Text
     protected static $_defaultTransliteratorId = 'Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove';
 
     /**
+     * Default html tags who must not be count for truncate text.
+     *
+     * @var array
+     */
+    protected static $_defaultHtmlNoCount = [
+        'style',
+        'script'
+    ];
+
+    /**
      * Generate a random UUID version 4
      *
      * Warning: This method should not be used as a random seed for any cryptographic operations.
@@ -608,7 +618,10 @@ class Text
 
             preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
             foreach ($tags as $tag) {
-                $contentLength = self::_strlen($tag[3], $options);
+                $contentLength = 0;
+                if (!in_array($tag[2], static::$_defaultHtmlNoCount, true)) {
+                    $contentLength = self::_strlen($tag[3], $options);
+                }
 
                 if ($truncate === '') {
                     if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/i', $tag[2])) {

+ 5 - 0
tests/TestCase/Utility/TextTest.php

@@ -592,6 +592,11 @@ TEXT;
         ]);
         $expected = '<p><span style="font-size: medium;"><a>Iamatestwi...</a></span></p>';
         $this->assertEquals($expected, $result);
+
+        $text = '<style>text-align: center;</style><script>console.log(\'test\');</script><p>The quick brown fox jumps over the lazy dog</p>';
+        $expected = '<style>text-align: center;</style><script>console.log(\'test\');</script><p>The qu...</p>';
+        $result = $this->Text->truncate($text, 9, ['html' => true, 'ellipsis' => '...']);
+        $this->assertSame($expected, $result);
     }
 
     /**