Completed
Pull Request — master (#293)
by Christian
02:05
created

CountViewHelper::renderStatic()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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