Skip to content

Commit

Permalink
Add method ObjectCollection::collectionGroup()
Browse files Browse the repository at this point in the history
  • Loading branch information
mahagr committed Sep 26, 2017
1 parent 71b1136 commit 0fd6fda
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
26 changes: 24 additions & 2 deletions system/src/Grav/Framework/Object/Base/ObjectCollectionTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 0fd6fda

Please sign in to comment.