diff --git a/src/Plugin/views/argument_default/Membership.php b/src/Plugin/views/argument_default/Membership.php new file mode 100644 index 000000000..cfb7244a1 --- /dev/null +++ b/src/Plugin/views/argument_default/Membership.php @@ -0,0 +1,172 @@ +ogContext = $og_context; + $this->ogMembership = $og_membership; + $this->ogUser = $og_user; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->get('og.context'), + $container->get('og.membership_manager'), + $container->get('current_user')->getAccount() + ); + } + + /** + * {@inheritdoc} + */ + protected function defineOptions() { + $options = parent::defineOptions(); + $options['og_group_membership'] = ['default' => '']; + + return $options; + } + + /** + * {@inheritdoc} + */ + public function buildOptionsForm(&$form, FormStateInterface $form_state) { + $form['og_group_membership'] = []; + } + + /** + * {@inheritdoc} + */ + public function getArgument() { + // Currently restricted to node entities. + return implode(',', $this->getCurrentUserGroupIds('node')); + } + + /** + * {@inheritdoc} + */ + public function getCacheMaxAge() { + return Cache::PERMANENT; + } + + /** + * {@inheritdoc} + */ + public function getCacheContexts() { + // This cache context is the best thing we have right now. + // og_role takes in consideration the user memberships and + // the roles held in the corresponding groups, and while it + // is one level too granular, i.e. the context will be more + // fragmented than strictly needed, it works. + return ['og_role']; + } + + /** + * {@inheritdoc} + */ + public function getCacheTags() { + $group = $this->getGroup(); + if ($group instanceof ContentEntityInterface) { + $tag = $group->getEntityTypeId() . ':' . $group->id(); + return Cache::buildTags('og-group-content', [$tag]); + } + return []; + } + + /** + * Returns groups that current user is a member of. + * + * @param string $entity_type + * The entity type, defaults to 'node'. + * + * @return array + * An array of groups, or an empty array if no group is found. + */ + protected function getCurrentUserGroupIds($entity_type = 'node') { + $groups = $this->ogMembership->getUserGroupIds($this->ogUser); + if (!empty($groups) && isset($groups[$entity_type])) { + return $groups[$entity_type]; + } + return []; + } + + /** + * Returns the group from the runtime context. + * + * @return \Drupal\Core\Entity\ContentEntityInterface|null + * The group from context if found. + */ + protected function getGroup() { + $contexts = $this->ogContext->getRuntimeContexts(['og']); + if (!empty($contexts['og']) && $group = $contexts['og']->getContextValue()) { + if ($group instanceof ContentEntityInterface) { + return $group; + } + } + } + +}