From 0fd6fda4d8ffb29d3462a88ec9333e72534cdf1a Mon Sep 17 00:00:00 2001 From: Matias Griese Date: Tue, 26 Sep 2017 18:26:39 +0300 Subject: [PATCH] Add method ObjectCollection::collectionGroup() --- .../Object/Base/ObjectCollectionTrait.php | 26 +++++++++++++++++-- .../Interfaces/ObjectCollectionInterface.php | 10 ++++++- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php b/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php index 916502b678..a122ee3e7e 100644 --- a/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php +++ b/system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php @@ -142,9 +142,8 @@ public function call($method, array $arguments = []) return $list; } - /** - * Group items in the collection by a field. + * Group items in the collection by a field and return them as associated array. * * @param string $property * @return array @@ -161,6 +160,29 @@ public function group($property) return $list; } + /** + * Group items in the collection by a field and return them as associated array of collections. + * + * @param string $property + * @return static[] + */ + public function collectionGroup($property) + { + $collections = []; + foreach ($this->group($property) as $id => $elements) { + // TODO: remove when PHP 5.6 is minimum (with doctrine/collections v1.4). + if (!method_exists($this, 'createFrom')) { + $collection = new static(array_reverse($this->toArray())); + } else { + $collection = $this->createFrom(array_reverse($this->toArray())); + } + + $collections[$id] = $collection; + } + + return $collections; + } + /** * @return \Traversable */ diff --git a/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php b/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php index 5f4646e3b4..3cba932f61 100644 --- a/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php +++ b/system/src/Grav/Framework/Object/Interfaces/ObjectCollectionInterface.php @@ -49,10 +49,18 @@ public function getProperty($property, $default = null); public function call($name, array $arguments); /** - * Group items in the collection by a field. + * Group items in the collection by a field and return them as associated array. * * @param string $property * @return array */ public function group($property); + + /** + * Group items in the collection by a field and return them as associated array of collections. + * + * @param string $property + * @return static[] + */ + public function collectionGroup($property); }