/** * {@inheritDoc} */ public function groupBy(callable $groupKeyFunction) { $groupedMap = new self(); foreach ($this->keyIdentityPositionMap as $identityHash => $position) { $keyCopy = $key = $this->keys[$position]; $valueCopy = $value =& $this->values[$position]; $groupKey = $groupKeyFunction($valueCopy, $keyCopy); if ($groupedMap->contains($groupKey)) { $groupMap = $groupedMap->get($groupKey); } else { $groupMap = new self(); $groupedMap->set($groupKey, $groupMap); } $groupMap->setInternal($key, $value, $identityHash, true); } return $groupedMap; }
/** * Create a new collection from an array, validate the keys, and add default values where missing * * @param array $config Configuration values to apply. * @param array $defaults Default parameters * @param array $required Required parameter names * * @return self * @throws InvalidArgumentException if a parameter is missing */ public static function fromConfig(array $config = null, array $defaults = null, array $required = null) { $collection = new self($defaults); foreach ((array) $config as $key => $value) { $collection->add($key, $value); } foreach ((array) $required as $key) { if ($collection->contains($key) === false) { throw new InvalidArgumentException("Config must contain a '{$key}' key"); } } return $collection; }
/** * Get all the unique values in the collection. * * @param bool $preserveKeys * * @return CollectionInterface */ public function unique($preserveKeys = true) { $values = new self(); $this->each(function ($item) use($values, $preserveKeys) { if (!$values->contains($item)) { if ($preserveKeys) { } $values->push($item); } }); return $values; }
/** * {@inheritdoc} */ public function groupBy(callable $discriminator) : MapInterface { if ($this->size() === 0) { throw new GroupEmptyMapException(); } $map = null; foreach ($this->pairs as $pair) { $key = $discriminator($pair->key(), $pair->value()); if ($map === null) { $type = gettype($key); $map = new self($type === 'object' ? get_class($key) : $type, SequenceInterface::class); } if ($map->contains($key)) { $map = $map->put($key, $map->get($key)->add($pair)); } else { $map = $map->put($key, new Sequence($pair)); } } return $map; }