Created
December 10, 2015 15:16
-
-
Save smichaelsen/21d55fc4da584898e9ea to your computer and use it in GitHub Desktop.
ObjectStorageService that groups your objects by property (PHP 5.5 required)
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 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