e0d565c5c6d29fba577e38aaec204edabae55fa7
[Packages/TYPO3.CMS.git] / typo3 / sysext / install / Classes / ViewHelpers / Object / ArrayValueByKeyViewHelper.php
1 <?php
2 namespace TYPO3\CMS\Install\ViewHelpers\Object;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Fluid\Core\ViewHelper\AbstractViewHelper;
18 use TYPO3\CMS\Install\ViewHelpers\Exception;
19 use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
20
21 /**
22 * View helper which allows you to access a key in an array.
23 *
24 * = Examples =
25 *
26 * <code title="Defaults">
27 * <i:object.key array="{array}" key="{key}" />
28 * </code>
29 * <output>
30 * The key in the array, if it exists, otherwise an empty string.
31 * </output>
32 *
33 * @internal
34 */
35 class ArrayValueByKeyViewHelper extends AbstractViewHelper
36 {
37 /**
38 * Get the value of an key in an array.
39 *
40 * @param array $array The array being processed
41 * @param mixed $key The key being accessed
42 * @return string
43 */
44 public function render(array $array, $key)
45 {
46 return static::renderStatic(
47 array(
48 'array' => $array,
49 'key' => $key,
50 ),
51 $this->buildRenderChildrenClosure(),
52 $this->renderingContext
53 );
54 }
55
56 /**
57 * @param array $arguments
58 * @param \Closure $renderChildrenClosure
59 * @param RenderingContextInterface $renderingContext
60 *
61 * @return string
62 * @throws Exception
63 */
64 public static function renderStatic(array $arguments, \Closure $renderChildrenClosure, RenderingContextInterface $renderingContext)
65 {
66 $array = $arguments['array'];
67 $key = $arguments['key'];
68 $result = '';
69 if (isset($array[$key])) {
70 $result = $array[$key];
71 }
72 if (!is_scalar($result)) {
73 throw new Exception(
74 'Only scalar return values (string, int, float or double) are supported.',
75 1430852128
76 );
77 }
78 return (string)$result;
79 }
80 }