Created
June 4, 2013 12:49
-
-
Save akovalyov/5705639 to your computer and use it in GitHub Desktop.
filtering function for collections of objects for twig
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
use Doctrine\Common\Collections\Collection; | |
use Symfony\Component\PropertyAccess\PropertyAccess; | |
public function getFilters() | |
{ | |
return array( | |
'sortCollection' => new \Twig_Filter_Method($this, 'sortCollection'), | |
); | |
} | |
public function sortCollection(Collection $collection, $column, $direction = 'ASC') | |
{ | |
$iterator = $collection->getIterator(); | |
$accessor = PropertyAccess::createPropertyAccessor(); | |
$iterator->uasort(function ($first, $second) use ($accessor, $column, $direction) { | |
if ($direction == 'ASC') { | |
return ((int)$accessor->getValue($first, $column) > (int)$accessor->getValue($second, $column) ? 1 : -1); | |
} else { | |
return ((int)$accessor->getValue($first, $column) < (int)$accessor->getValue($second, $column) ? 1 : -1); | |
} | |
}); | |
return $iterator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment