Passed
Push — master ( 19f06a...8d1e35 )
by Ralf
24:17
created

JsonViewHelper::initializeArguments()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
namespace EWW\Dpf\ViewHelpers\Format;
3
4
// backport of TYPO3 8.7!
5
6
/*
7
 * This file is part of the TYPO3 CMS project.
8
 *
9
 * It originated from the Neos.Form package (www.neos.io)
10
 *
11
 * It is free software; you can redistribute it and/or modify it under
12
 * the terms of the GNU General Public License, either version 2
13
 * of the License, or any later version.
14
 *
15
 * For the full copyright and license information, please read the
16
 * LICENSE.txt file that was distributed with this source code.
17
 *
18
 * The TYPO3 project - inspiring people to share!
19
 */
20
21
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;
22
23
/**
24
 * Wrapper for PHPs json_encode function.
25
 *
26
 * = Examples =
27
 *
28
 * <code title="encoding a view variable">
29
 * {someArray -> f:format.json()}
30
 * </code>
31
 * <output>
32
 * ["array","values"]
33
 * // depending on the value of {someArray}
34
 * </output>
35
 *
36
 * <code title="associative array">
37
 * {f:format.json(value: {foo: 'bar', bar: 'baz'})}
38
 * </code>
39
 * <output>
40
 * {"foo":"bar","bar":"baz"}
41
 * </output>
42
 *
43
 * <code title="non-associative array with forced object">
44
 * {f:format.json(value: {0: 'bar', 1: 'baz'}, forceObject: true)}
45
 * </code>
46
 * <output>
47
 * {"0":"bar","1":"baz"}
48
 * </output>
49
 *
50
 */
51
class JsonViewHelper extends AbstractViewHelper
52
{
53
    public function initializeArguments()
54
    {
55
        parent::initializeArguments();
56
57
        $this->registerArgument('value', 'array', '', true);
58
        $this->registerArgument('forceObject', 'boolean', '', false, false);
59
    }
60
61
    /**
62
     * Applies json_encode() on the specified value.
63
     *
64
     * Outputs content with its JSON representation. To prevent issues in HTML context, occurrences
65
     * of greater-than or less-than characters are converted to their hexadecimal representations.
66
     *
67
     * If $forceObject is TRUE a JSON object is outputted even if the value is a non-associative array
68
     * Example: array('foo', 'bar') as input will not be ["foo","bar"] but {"0":"foo","1":"bar"}
69
     *
70
     * @see http://www.php.net/manual/en/function.json-encode.php
71
     * @return string
72
     */
73
    public function render()
74
    {
75
        $value = $this->arguments['value'];
76
        $forceObject = $this->arguments['forceObject'];
77
78
        $options = JSON_HEX_TAG;
79
        if ($forceObject !== false) {
80
            $options = $options | JSON_FORCE_OBJECT;
81
        }
82
        return json_encode($value, $options);
83
    }
84
}
85