Skip to content

Commit

Permalink
Merge pull request #5634 from getkirby/v4/fix/collection-group-$caseI…
Browse files Browse the repository at this point in the history
…nsensitive

`$collection->group()`: rename parameter to `$caseInsensitive`
  • Loading branch information
bastianallgeier committed Sep 18, 2023
2 parents b26051f + 22f700b commit 9919720
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
12 changes: 8 additions & 4 deletions src/Cms/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,11 +147,11 @@ public function findBy(string $attribute, $value)
* with an item for each group and a collection for each group.
*
* @param string|Closure $field
* @param bool $i Ignore upper/lowercase for group names
* @param bool $caseInsensitive Ignore upper/lowercase for group names
* @return \Kirby\Cms\Collection
* @throws \Kirby\Exception\Exception
*/
public function group($field, bool $i = true)
public function group($field, bool $caseInsensitive = true)
{
if (is_string($field) === true) {
$groups = new Collection([], $this->parent());
Expand All @@ -164,8 +164,12 @@ public function group($field, bool $i = true)
throw new InvalidArgumentException('Invalid grouping value for key: ' . $key);
}

$value = (string)$value;

// ignore upper/lowercase for group names
$value = $i === true ? Str::lower($value) : (string)$value;
if ($caseInsensitive === true) {
$value = Str::lower($value);
}

if (isset($groups->data[$value]) === false) {
// create a new entry for the group if it does not exist yet
Expand All @@ -179,7 +183,7 @@ public function group($field, bool $i = true)
return $groups;
}

return parent::group($field, $i);
return parent::group($field, $caseInsensitive);
}

/**
Expand Down
11 changes: 7 additions & 4 deletions src/Toolkit/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -519,21 +519,24 @@ protected function getAttributeFromObject($object, string $attribute)
* Groups the elements by a given field or callback function
*
* @param string|Closure $field
* @param bool $i
* @return \Kirby\Toolkit\Collection A new collection with an element for
* each group and a subcollection in
* each group
* @throws \Exception if $field is not a string nor a callback function
*/
public function group($field, bool $i = true)
public function group($field, bool $caseInsensitive = true)
{
// group by field name
if (is_string($field) === true) {
return $this->group(function ($item) use ($field, $i) {
return $this->group(function ($item) use ($field, $caseInsensitive) {
$value = $this->getAttribute($item, $field);

// ignore upper/lowercase for group names
return $i === true ? Str::lower($value) : (string)$value;
if ($caseInsensitive === true) {
return Str::lower($value);
}

return (string)$value;
});
}

Expand Down

0 comments on commit 9919720

Please sign in to comment.