6bc4c22866287e00eed5d01d498effa5479e04ec
[Packages/TYPO3.CMS.git] / typo3 / sysext / install / Classes / ViewHelpers / Format / CropViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Install\ViewHelpers\Format;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
18 use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
19
20 /**
21 * Simplified crop view helper that does not need a frontend environment
22 *
23 * = Examples =
24 *
25 * <code title="Defaults">
26 * <f:format.crop maxCharacters="10">This is some very long text</f:format.crop>
27 * </code>
28 * <output>
29 * This is...
30 * </output>
31 *
32 * <code title="Inline notation">
33 * {someLongText -> f:format.crop(maxCharacters: 10)}
34 * </code>
35 * <output>
36 * someLongText cropped after 10 characters...
37 * (depending on the value of {someLongText})
38 * </output>
39 *
40 * @internal
41 */
42 class CropViewHelper extends AbstractViewHelper
43 {
44 /**
45 * Output is escaped already. We must not escape children, to avoid double encoding.
46 *
47 * @var bool
48 */
49 protected $escapeChildren = false;
50
51 /**
52 * Render the cropped text
53 *
54 * @param int $maxCharacters Place where to truncate the string
55 * @throws \TYPO3\CMS\Install\ViewHelpers\Exception
56 * @return string cropped text
57 */
58 public function render($maxCharacters)
59 {
60 return static::renderStatic(
61 array(
62 'maxCharacters' => $maxCharacters,
63 ),
64 $this->buildRenderChildrenClosure(),
65 $this->renderingContext
66 );
67 }
68
69 /**
70 * @param array $arguments
71 * @param \Closure $renderChildrenClosure
72 * @param RenderingContextInterface $renderingContext
73 * @throws \TYPO3\CMS\Install\ViewHelpers\Exception
74 * @return string
75 */
76 public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
77 {
78 $maxCharacters = $arguments['maxCharacters'];
79 if (empty($maxCharacters) || $maxCharacters < 1) {
80 throw new \TYPO3\CMS\Install\ViewHelpers\Exception(
81 'maxCharacters must be a positive integer',
82 1371410113
83 );
84 }
85 $stringToTruncate = $renderChildrenClosure();
86 return substr($stringToTruncate, 0, $maxCharacters);
87 }
88 }