Completed
Push — master ( c49b70...dc1a3a )
by Fabien
06:24
created

ToJsonViewHelper::encodeItems()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
namespace Fab\Vidi\ViewHelpers\Result;
3
4
/*
5
 * This file is part of the Fab/Vidi project under GPLv2 or later.
6
 *
7
 * For the full copyright and license information, please read the
8
 * LICENSE.md file that was distributed with this source code.
9
 */
10
11
use Fab\Vidi\ViewHelpers\Grid\RowsViewHelper;
12
use TYPO3\CMS\Core\Utility\GeneralUtility;
13
use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
14
15
/**
16
 * View helper for rendering a JSON response.
17
 */
18
class ToJsonViewHelper extends AbstractViewHelper
19
{
20
21
    /**
22
     * Render a Json response
23
     *
24
     * @return boolean
25
     * @throws \TYPO3\CMS\Fluid\Core\ViewHelper\Exception\InvalidVariableException
26
     */
27
    public function render()
28
    {
29
30
        $objects = $this->templateVariableContainer->get('objects');
31
        $columns = $this->templateVariableContainer->get('columns');
32
        $output = array(
33
            'sEcho' => $this->getNextTransactionId(),
34
            'iTotalRecords' => $this->templateVariableContainer->get('numberOfObjects'),
35
            'iTotalDisplayRecords' => $this->templateVariableContainer->get('numberOfObjects'),
36
            'iNumberOfRecords' => count($objects),
37
            'aaData' => $this->getRowsViewHelper()->render($objects, $columns),
38
        );
39
40
        $this->setHttpHeaders();
41
        return json_encode($output);
42
    }
43
44
    /**
45
     * @return int
46
     */
47
    protected function getNextTransactionId()
48
    {
49
        $transaction = 0;
50
        if (GeneralUtility::_GET('sEcho')) {
51
            $transaction = (int)GeneralUtility::_GET('sEcho') + 1;
52
        }
53
        return $transaction;
54
    }
55
56
    /**
57
     * @return void
58
     * @throws \InvalidArgumentException
59
     */
60
    protected function setHttpHeaders()
61
    {
62
        /** @var \TYPO3\CMS\Extbase\Mvc\Web\Response $response */
63
        $response = $this->templateVariableContainer->get('response');
64
        $response->setHeader('Content-Type', 'application/json');
65
        $response->sendHeaders();
66
    }
67
68
    /**
69
     * @return RowsViewHelper
70
     */
71
    protected function getRowsViewHelper()
72
    {
73
        return $this->objectManager->get(RowsViewHelper::class);
74
    }
75
}
76