diff options
author | Stefan Giehl <stefan@piwik.org> | 2017-12-13 23:49:21 +0300 |
---|---|---|
committer | Matthieu Aubry <mattab@users.noreply.github.com> | 2017-12-13 23:49:21 +0300 |
commit | 56f7bc5a879e868436c4286cb4cfb6983d12bf54 (patch) | |
tree | 6ea24ff036561415ee66c6f1985afc02503a9bf3 | |
parent | f91f646c2f5df8d4432aa86db2a2f4a3d9a50452 (diff) |
Improves truncate twig filter (#12347)
* respect encoded entities in truncate filter
* adds some simple tests
-rwxr-xr-x | core/Twig.php | 6 | ||||
-rw-r--r-- | tests/PHPUnit/Unit/TwigTest.php | 40 |
2 files changed, 43 insertions, 3 deletions
diff --git a/core/Twig.php b/core/Twig.php index c36452055b..24fd09eec2 100755 --- a/core/Twig.php +++ b/core/Twig.php @@ -25,11 +25,11 @@ use Twig_SimpleTest; function piwik_filter_truncate($string, $size) { - if (strlen($string) < $size) { + if (Common::mb_strlen(html_entity_decode($string)) <= $size) { return $string; } else { - $array = str_split($string, $size); - return array_shift($array) . "..."; + preg_match('/^(&(?:[a-z\d]+|#\d+|#x[a-f\d]+);|.){'.$size.'}/i', $string, $shortenString); + return reset($shortenString) . "..."; } } diff --git a/tests/PHPUnit/Unit/TwigTest.php b/tests/PHPUnit/Unit/TwigTest.php new file mode 100644 index 0000000000..85fce40bf0 --- /dev/null +++ b/tests/PHPUnit/Unit/TwigTest.php @@ -0,0 +1,40 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Tests\Unit; + +require_once(PIWIK_INCLUDE_PATH . '/core/Twig.php'); + +/** + * @group Twig + */ +class TwigTest extends \PHPUnit_Framework_TestCase +{ + /** + * @dataProvider getTruncateTests + */ + public function testPiwikFilterTruncate($in, $size, $out) + { + $truncated = \Piwik\piwik_filter_truncate($in, $size); + $this->assertEquals($out, $truncated); + } + + public function getTruncateTests() + { + return [ + ['abc', 4, 'abc'], + ['abc"', 4, 'abc"'], + ['abc ', 4, 'abc '], + ['abcdef', 3, 'abc...'], + ['ab&ef', 3, 'ab&...'], + ['some▼thing', 5, 'some▼...'], + ['ab&ef ;', 3, 'ab&...'], + ['<>▼ ', 4, '<>▼ '] + ]; + } +}
\ No newline at end of file |