|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +/** |
| 4 | + * Test: |limit filter |
| 5 | + */ |
| 6 | + |
| 7 | +use Tester\Assert; |
| 8 | + |
| 9 | +require __DIR__ . '/../bootstrap.php'; |
| 10 | + |
| 11 | + |
| 12 | +function limit(string|iterable $value, int $length): string|array|\Generator |
| 13 | +{ |
| 14 | + return \Latte\Essential\Filters::slice($value, 0, $length, preserveKeys: true); |
| 15 | +} |
| 16 | + |
| 17 | + |
| 18 | +test('arrays', function () { |
| 19 | + Assert::same([], limit([], 5)); |
| 20 | + Assert::same([0 => 'a', 1 => 'b'], limit(['a', 'b', 'c', 'd'], 2)); |
| 21 | + Assert::same([0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd'], limit(['a', 'b', 'c', 'd'], 99)); |
| 22 | + Assert::same([], limit(['a', 'b', 'c'], 0)); |
| 23 | +}); |
| 24 | + |
| 25 | + |
| 26 | +test('arrays preserve keys', function () { |
| 27 | + $arr = ['a', 'b', 10 => 'c', 'd']; |
| 28 | + Assert::same([0 => 'a', 1 => 'b'], limit($arr, 2)); |
| 29 | + Assert::same([0 => 'a', 1 => 'b', 10 => 'c'], limit($arr, 3)); |
| 30 | +}); |
| 31 | + |
| 32 | + |
| 33 | +test('iterators', function () { |
| 34 | + $gen = function () { |
| 35 | + yield 'a' => 1; |
| 36 | + yield 'b' => 2; |
| 37 | + yield 'c' => 3; |
| 38 | + yield 'd' => 4; |
| 39 | + }; |
| 40 | + |
| 41 | + Assert::same(['a' => 1, 'b' => 2], iterator_to_array(limit($gen(), 2))); |
| 42 | + Assert::same(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4], iterator_to_array(limit($gen(), 99))); |
| 43 | + Assert::same([], iterator_to_array(limit($gen(), 0))); |
| 44 | +}); |
| 45 | + |
| 46 | + |
| 47 | +test('strings (UTF-8)', function () { |
| 48 | + Assert::same('Příl', limit('Příliš', 4)); |
| 49 | + Assert::same('Příliš', limit('Příliš', 99)); |
| 50 | + Assert::same('', limit('Příliš', 0)); |
| 51 | + Assert::same('', limit('', 5)); |
| 52 | + Assert::same('ř', limit('řeč', 1)); |
| 53 | +}); |
| 54 | + |
| 55 | + |
| 56 | +test('via Latte', function () { |
| 57 | + $latte = new Latte\Engine; |
| 58 | + $latte->setLoader(new Latte\Loaders\StringLoader); |
| 59 | + $latte->setTempDirectory(sys_get_temp_dir()); |
| 60 | + |
| 61 | + Assert::same('ab', $latte->renderToString('{$s|limit:2}', ['s' => 'abcdef'])); |
| 62 | + Assert::same('Př', $latte->renderToString('{$s|limit:2}', ['s' => 'Příliš'])); |
| 63 | + Assert::same('a, b', $latte->renderToString('{$arr|limit:2|implode:", "}', ['arr' => ['a', 'b', 'c']])); |
| 64 | +}); |
0 commit comments