Skip to content

Instantly share code, notes, and snippets.

@smichaelsen
Created December 10, 2015 15:16
Show Gist options
  • Save smichaelsen/21d55fc4da584898e9ea to your computer and use it in GitHub Desktop.
Save smichaelsen/21d55fc4da584898e9ea to your computer and use it in GitHub Desktop.
ObjectStorageService that groups your objects by property (PHP 5.5 required)
<?php
namespace Smichaelsen\Gist\Service;
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
class ObjectStorageService
{
/**
* Groups the given ObjectStorage by the property and yields the groups.
*
* Usage example:
*
* foreach($objectStorageService->groupByProperty($people, 'hairColor') as $hairColor => $groupedPeople) {
* // The $groupedPeople have $hairColor
* }
*
* @param ObjectStorage $objects
* @param string
* @return \Generator|object[]
*/
public function groupByProperty(ObjectStorage $objects, $property) {
$objectGroups = [];
foreach ($objects as $object) {
$value = ObjectAccess::getProperty($object, $property);
if (!isset($objectGroups[$value])) {
$objectGroups[$value] = new ObjectStorage();
}
$objectGroups[$value]->attach($object);
}
foreach ($objectGroups as $value => $groupedObjects) {
yield $value => $groupedObjects;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment