-
Notifications
You must be signed in to change notification settings - Fork 93
/
CountViewHelper.php
87 lines (79 loc) · 2.04 KB
/
CountViewHelper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/*
* This file belongs to the package "TYPO3 Fluid".
* See LICENSE.txt that was shipped with this package.
*/
namespace TYPO3Fluid\Fluid\ViewHelpers;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithContentArgumentAndRenderStatic;
/**
* This ViewHelper counts elements of the specified array or countable object.
*
* Examples
* ========
*
* Count array elements
* --------------------
*
* ::
*
* <f:count subject="{0:1, 1:2, 2:3, 3:4}" />
*
* Output::
*
* 4
*
* inline notation
* ---------------
*
* ::
*
* {objects -> f:count()}
*
* Output::
*
* 10 (depending on the number of items in ``{objects}``)
*
* @api
*/
class CountViewHelper extends AbstractViewHelper
{
use CompileWithContentArgumentAndRenderStatic;
/**
* @var bool
*/
protected $escapeChildren = false;
/**
* @var bool
*/
protected $escapeOutput = false;
public function initializeArguments()
{
parent::initializeArguments();
$this->registerArgument('subject', 'array', 'Countable subject, array or \Countable');
}
/**
* @param array $arguments
* @param \Closure $renderChildrenClosure
* @param RenderingContextInterface $renderingContext
* @return int
*/
public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
{
$countable = $renderChildrenClosure();
if ($countable === null) {
return 0;
}
if (!$countable instanceof \Countable && !is_array($countable)) {
throw new ViewHelper\Exception(
sprintf(
'Subject given to f:count() is not countable (type: %s)',
is_object($countable) ? get_class($countable) : gettype($countable),
),
);
}
return count($countable);
}
}