Last active
December 18, 2015 11:29
-
-
Save pdrosos/5776107 to your computer and use it in GitHub Desktop.
Typo3 FLOW Fluid template view helper: Array or object access by dynamic key/property/method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace My\Package\ViewHelpers; | |
use TYPO3\Flow\Annotations as Flow; | |
/** | |
* Allows accessing an array's value by its key or object's property or method by its name | |
* in order to achieve a "dynamic" path in Fluid, kind of | |
* {fooarray.{dynamic}}, which is not possible yet, can be replaced | |
* with {my:objectAccess(haystack: fooarray, needle: key)} | |
*/ | |
class ObjectAccessViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper { | |
/** | |
* @param mixed $haystack | |
* @param string $needle | |
* @param string $methodPrefix | |
* @return mixed | |
*/ | |
public function render($haystack, $needle, $methodPrefix = null) { | |
if (is_array($haystack)) { | |
if (array_key_exists($needle, $haystack)) { | |
return $haystack[$needle]; | |
} else { | |
return null; | |
} | |
} elseif (is_object($haystack)) { | |
if (isset($haystack->$needle) || property_exists($haystack, $needle)) { | |
return $haystack->$needle; | |
} elseif (method_exists($haystack, $methodPrefix . $needle)) { | |
return $haystack->{$methodPrefix . $needle}(); | |
} | |
} else { | |
return null; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you.
Note: For 6.2 use