OgResolvedGroupCollection.php in Organic groups 8
File
src/OgResolvedGroupCollection.php
View source
<?php
declare (strict_types=1);
namespace Drupal\og;
use Drupal\Core\Entity\ContentEntityInterface;
class OgResolvedGroupCollection implements OgResolvedGroupCollectionInterface {
protected $groupInfo = [];
protected $voteWeight = 0;
public function addGroup(ContentEntityInterface $group, array $cache_contexts = [], $weight = NULL) {
if ($weight !== NULL && !is_int($weight)) {
throw new \InvalidArgumentException('Vote weight should be an integer.');
}
$key = $this
->generateKey($group);
$this->groupInfo[$key]['entity'] = $group;
$this->groupInfo[$key]['votes'][] = $weight !== NULL ? $weight : $this
->getVoteWeight();
foreach ($cache_contexts as $cache_context) {
$this->groupInfo[$key]['cache_contexts'][$cache_context] = $cache_context;
}
}
public function hasGroup(ContentEntityInterface $group) {
$key = $this
->generateKey($group);
return array_key_exists($key, $this->groupInfo);
}
public function getGroupInfo() {
return $this->groupInfo;
}
public function removeGroup(ContentEntityInterface $group) {
$key = $this
->generateKey($group);
unset($this->groupInfo[$key]);
}
public function getVoteWeight() {
return $this->voteWeight;
}
public function setVoteWeight($weight) {
if (!is_int($weight)) {
throw new \InvalidArgumentException('Vote weight should be an integer.');
}
$this->voteWeight = $weight;
}
public function sort() {
uasort($this->groupInfo, function ($a, $b) {
if (count($a['votes']) == count($b['votes'])) {
return array_sum($a['votes']) < array_sum($b['votes']) ? 1 : -1;
}
return count($a['votes']) < count($b['votes']) ? 1 : -1;
});
}
protected function generateKey(ContentEntityInterface $group) {
return $group
->getEntityTypeId() . '|' . $group
->id();
}
}