Last active
March 9, 2016 08:43
-
-
Save tremby/cdf7ef824291554b6a80 to your computer and use it in GitHub Desktop.
Twig filter to make sure a variable is an array
This file contains hidden or 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 Tremby\Twig\Extension; | |
use Twig_Extension; | |
use Twig_SimpleFilter; | |
/** | |
* Filter to leave a variable alone if it's array, | |
* pass an empty array if the variable was missing, | |
* and wrap anything else in an array. | |
*/ | |
class WrapArray extends Twig_Extension | |
{ | |
public function getName() | |
{ | |
return 'WrapArray'; | |
} | |
public function getFilters() | |
{ | |
return [ | |
new Twig_SimpleFilter('wrapArray', function ($var) { | |
if ($var === null) { | |
return []; | |
} | |
if (!is_array($var)) { | |
return [$var]; | |
} | |
return $var; | |
}), | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment