From 4345a629f16e50bb8b2cbed25db80e91fc20e368 Mon Sep 17 00:00:00 2001 From: Matias Griese Date: Wed, 23 Dec 2020 21:05:58 +0200 Subject: [PATCH] Added `FlexCollection::getDistinctValues()` to get all the assigned values from the field --- CHANGELOG.md | 1 + .../Grav/Framework/Flex/FlexCollection.php | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e4b5a5f6..c0b0accd4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * Added support for overriding configuration by using environment variables * Use PHP 7.4 serialization (the old `Serializable` methods are now final and cannot be overridden) * Enabled `ETag` setting by default for 304 responses + * Added `FlexCollection::getDistinctValues()` to get all the assigned values from the field 1. [](#improved) * Make it possible to use an absolute path when loading a blueprint * Make serialize methods final in `ContentBlock`, `AbstractFile`, `FormTrait`, `ObjectCollectionTrait` and `ObjectTrait` diff --git a/system/src/Grav/Framework/Flex/FlexCollection.php b/system/src/Grav/Framework/Flex/FlexCollection.php index 26e20573c..44a8e2a73 100644 --- a/system/src/Grav/Framework/Flex/FlexCollection.php +++ b/system/src/Grav/Framework/Flex/FlexCollection.php @@ -71,6 +71,7 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface 'isAuthorized' => 'session', 'search' => true, 'sort' => true, + 'getDistinctValues' => true ]; } @@ -272,6 +273,33 @@ class FlexCollection extends ObjectCollection implements FlexCollectionInterface return $keys; } + /** + * Get all the values in property. + * + * Supports either single scalar values or array of scalar values. + * + * @param string $property Object property to be used to make groups. + * @param string|null $separator Separator, defaults to '.' + * @return array + */ + public function getDistinctValues(string $property, string $separator = null): array + { + $list = []; + + /** @var FlexObjectInterface $element */ + foreach ($this->getIterator() as $element) { + $value = (array)$element->getNestedProperty($property, null, $separator); + foreach ($value as $v) { + if (is_scalar($v)) { + $t = gettype($v) . (string)$v; + $list[$t] = $v; + } + } + } + + return array_values($list); + } + /** * {@inheritdoc} * @see FlexCollectionInterface::withKeyField()