Skip to content

Instantly share code, notes, and snippets.

@xphere
Created February 26, 2015 10:01
Show Gist options
  • Save xphere/6d45b4fd481ec59eddc0 to your computer and use it in GitHub Desktop.
Save xphere/6d45b4fd481ec59eddc0 to your computer and use it in GitHub Desktop.
Twig filter for `merge_concat` between arrays, making easier to add classes and csv lists as attributes.
<?php
/**
* Copyright © 2015 Berny Cantos <[email protected]>
*
* This work is free. You can redistribute it and/or modify it under the
* terms of the Do What The Fuck You Want To Public License Version 2 as
* published by Sam Hocevar.
*
* See http://www.wtfpl.net/about file for more details.
*/
class MergeConcatTwigExtension extends \Twig_Extension
{
/**
* Returns a list of filters to add to the existing list.
*
* @return array An array of filters
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('merge_concat', function ($source, $strings, $trim = ' ') {
return $this->mergeConcat($source, $strings, $trim);
}),
);
}
/**
* Merge string values in an array concatenating them with an optional separator
*
* @param array $source Array to filter
* @param array $strings Array of strings to concat into $source
* @param string $separator Optional character separator (may be empty)
*
* @return array
*/
protected function mergeConcat(array $source, array $strings, $separator)
{
if (!is_array($source)) {
throw new \UnexpectedValueException(
'Filtered value should be an array'
);
}
if (!is_array($strings)) {
throw new \UnexpectedValueException(
'Merging value should be an array'
);
}
$merged = array();
foreach ($strings as $key => $value) {
if (array_key_exists($key, $source)) {
$oldValue = $source[$key];
if (is_array($oldValue)) {
$value = $this->mergeConcat($source[$key], $value, $separator);
} else if (is_string($oldValue)) {
$value = $source[$key].$separator.$value;
} else {
throw new \UnexpectedValueException(
'Only merge strings or arrays'
);
}
}
$merged[$key] = is_string($value) && !empty($separator)
? trim($value, $separator)
: $value;
}
return array_merge($source, $merged);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'merge_concat';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment