c458955790c68841b5f3e7451d33e1a31131f14b
[Packages/TYPO3.CMS.git] / typo3 / sysext / fluid / Classes / ViewHelpers / CountViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Fluid\ViewHelpers;
3
4 /* *
5 * This script is backported from the TYPO3 Flow package "TYPO3.Fluid". *
6 * *
7 * It is free software; you can redistribute it and/or modify it under *
8 * the terms of the GNU Lesser General Public License, either version 3 *
9 * of the License, or (at your option) any later version. *
10 * *
11 * The TYPO3 project - inspiring people to share! *
12 * */
13 use TYPO3\CMS\Fluid\Core\Rendering\RenderingContextInterface;
14 use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
15 use TYPO3\CMS\Fluid\Core\ViewHelper\Exception;
16 use TYPO3\CMS\Fluid\Core\ViewHelper\Facets\CompilableInterface;
17
18 /**
19 * This ViewHelper counts elements of the specified array or countable object.
20 *
21 * = Examples =
22 *
23 * <code title="Count array elements">
24 * <f:count subject="{0:1, 1:2, 2:3, 3:4}" />
25 * </code>
26 * <output>
27 * 4
28 * </output>
29 *
30 * <code title="inline notation">
31 * {objects -> f:count()}
32 * </code>
33 * <output>
34 * 10 (depending on the number of items in {objects})
35 * </output>
36 *
37 * @api
38 */
39 class CountViewHelper extends AbstractViewHelper implements CompilableInterface {
40
41 /**
42 * @var bool
43 */
44 protected $escapingInterceptorEnabled = FALSE;
45
46 /**
47 * Counts the items of a given property.
48 *
49 * @param array $subject The array or \Countable to be counted
50 * @return int The number of elements
51 * @throws Exception
52 * @api
53 */
54 public function render($subject = NULL) {
55 return self::renderStatic(
56 array('subject' => $subject),
57 $this->buildRenderChildrenClosure(),
58 $this->renderingContext
59 );
60 }
61
62 /**
63 * @param array $arguments
64 * @param callable $renderChildrenClosure
65 * @param RenderingContextInterface $renderingContext
66 *
67 * @return int
68 * @throws Exception
69 */
70 static public function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext) {
71 $subject = $arguments['subject'];
72 if ($subject === NULL) {
73 $subject = $renderChildrenClosure();
74 }
75 if (is_object($subject) && !$subject instanceof \Countable) {
76 throw new Exception('CountViewHelper only supports arrays and objects implementing \Countable interface. Given: "' . get_class($subject) . '"', 1279808078);
77 }
78 return count($subject);
79 }
80
81 }