Browse Source

Add Text::truncateWidth() method

Add more tests
chinpei215 9 years ago
parent
commit
9ded4a6f6f
2 changed files with 26 additions and 0 deletions
  1. 14 0
      src/Utility/Text.php
  2. 12 0
      tests/TestCase/Utility/TextTest.php

+ 14 - 0
src/Utility/Text.php

@@ -649,6 +649,20 @@ class Text
     }
 
     /**
+     * Truncate text with specified width.
+     *
+     * @param string $text String to truncate.
+     * @param int $length Length of returned string, including ellipsis.
+     * @param array $options An array of HTML attributes and options.
+     * @return string Trimmed string.
+     * @see \Cake\Utility\Text::truncate()
+     */
+    public static function truncateWidth($text, $length = 100, array $options = [])
+    {
+        return static::truncate($text, $length, ['trimWidth' => true] + $options);
+    }
+
+    /**
      * Get string length.
      *
      * ### Options:

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

@@ -570,6 +570,7 @@ TEXT;
         $this->assertSame('НОПРСТУ...', $this->Text->truncate($text9, 10));
         $this->assertSame('http://example.com/somethin...', $this->Text->truncate($text10, 30));
         $this->assertSame('1 <b>2...</b>', $this->Text->truncate('1 <b>2 345</b>', 6, ['exact' => false, 'html' => true, 'ellipsis' => '...']));
+        $this->assertSame('&amp;', $this->Text->truncate('&amp;', 1, ['html' => true]));
 
         $text = '<p><span style="font-size: medium;"><a>Iamatestwithnospacesandhtml</a></span></p>';
         $result = $this->Text->truncate($text, 10, [
@@ -1784,6 +1785,17 @@ HTML;
     }
 
     /**
+     * Text truncateWidth method
+     *
+     * @return void
+     */
+    public function testTruncateWidth()
+    {
+        $this->assertSame('<p>あ...', Text::truncateWidth('<p>あいうえお</p>', 8));
+        $this->assertSame('<p>あい...</p>', Text::truncateWidth('<p>あいうえお</p>', 8, ['html' => true, 'ellipsis' => '...']));
+    }
+
+    /**
      * Test _strlen method
      *
      * @return void