You are here

class RecentGroupContentBlock in Organic groups 8

Provides a block that shows recent group content for the current group.

Plugin annotation


@Block(
  id = "og_recent_group_content",
  admin_label = @Translation("Recent group content")
)

Hierarchy

Expanded class hierarchy of RecentGroupContentBlock

File

src/Plugin/Block/RecentGroupContentBlock.php, line 27

Namespace

Drupal\og\Plugin\Block
View source
class RecentGroupContentBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The OG context provider.
   *
   * @var \Drupal\og\OgContextInterface
   */
  protected $ogContext;

  /**
   * The entity type manager, needed to load entities.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The OG group type manager.
   *
   * @var \Drupal\og\GroupTypeManagerInterface
   */
  protected $groupTypeManager;

  /**
   * The bundle information service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * Constructs a RecentGroupContentBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\og\OgContextInterface $og_context
   *   The OG context provider.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\og\GroupTypeManagerInterface $group_type_manager
   *   The OG group type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The bundle info service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, OgContextInterface $og_context, EntityTypeManagerInterface $entity_type_manager, GroupTypeManagerInterface $group_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
    $this->ogContext = $og_context;
    $this->entityTypeManager = $entity_type_manager;
    $this->groupTypeManager = $group_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@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('entity_type.manager'), $container
      ->get('og.group_type_manager'), $container
      ->get('entity_type.bundle.info'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {

    // Default to the first entity type in the list.
    $bundles = $this->groupTypeManager
      ->getAllGroupContentBundleIds();
    reset($bundles);
    $entity_type_default = key($bundles);

    // Enable all bundles by default.
    $bundle_defaults = [];
    foreach ($bundles as $entity_type_id => $bundle_ids) {
      foreach ($bundle_ids as $bundle_id) {
        $bundle_defaults[$entity_type_id][$bundle_id] = $bundle_id;
      }
    }
    return [
      'entity_type' => $entity_type_default,
      'bundles' => $bundle_defaults,
      'count' => 5,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['entity_type'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Entity type'),
      '#default_value' => $this->configuration['entity_type'],
      '#description' => $this
        ->t('The entity type of the group content to show.'),
    ];
    $entity_type_options = [];
    foreach ($this->groupTypeManager
      ->getAllGroupContentBundleIds() as $entity_type_id => $bundle_ids) {
      $entity_definition = $this->entityTypeManager
        ->getDefinition($entity_type_id);
      $entity_type_options[$entity_type_id] = $entity_definition
        ->getLabel();
      $bundle_options = [];
      $bundle_info = $this->entityTypeBundleInfo
        ->getBundleInfo($entity_type_id);
      foreach ($bundle_ids as $bundle_id) {
        $bundle_options[$bundle_id] = $bundle_info[$bundle_id]['label'];
      }
      $form['bundles'][$entity_type_id] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Bundles'),
        '#default_value' => $this->configuration['bundles'][$entity_type_id],
        '#options' => $bundle_options,
        '#description' => $this
          ->t('The group content bundles to show.'),
        '#states' => [
          'visible' => [
            ':input[name="settings[entity_type]"]' => [
              'value' => $entity_type_id,
            ],
          ],
        ],
      ];
    }
    $form['entity_type']['#options'] = $entity_type_options;
    $range = range(2, 20);
    $form['count'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Number of results to show'),
      '#default_value' => $this->configuration['count'],
      '#options' => array_combine($range, $range),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    foreach ([
      'entity_type',
      'bundles',
      'count',
    ] as $setting) {
      $this->configuration[$setting] = $form_state
        ->getValue($setting);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    // Do not render anything if there is no group in the current context.
    if (empty($this->ogContext
      ->getGroup())) {
      return [];
    }
    $list = array_map(function ($entity) {
      return [
        '#type' => 'link',
        '#title' => $entity
          ->label(),
        '#url' => $entity
          ->toUrl(),
      ];
    }, $this
      ->getGroupContent());
    return [
      'list' => [
        '#theme' => 'item_list',
        '#items' => $list,
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $tags = parent::getCacheTags();
    if ($group = $this->ogContext
      ->getGroup()) {
      $tags = Cache::mergeTags(Cache::buildTags('og-group-content', $group
        ->getCacheTagsToInvalidate()), $tags);
    }
    return $tags;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {

    // The block varies by user because of the access check on the query that
    // retrieves the group content.
    return Cache::mergeContexts(parent::getCacheContexts(), [
      'user',
      'og_group_context',
    ]);
  }

  /**
   * Returns the most recent group content for the active group.
   *
   * @return \Drupal\Core\Entity\EntityInterface[]
   *   The most recent group content for the group which is currently active
   *   according to OgContext.
   */
  protected function getGroupContent() {
    $group = $this->ogContext
      ->getGroup();
    $entity_type = $this->configuration['entity_type'];
    $bundles = array_filter($this->configuration['bundles'][$entity_type]);
    $definition = $this->entityTypeManager
      ->getDefinition($entity_type);

    // Retrieve the fields which reference our entity type and bundle.
    $field_storage_config_storage = $this->entityTypeManager
      ->getStorage('field_storage_config');
    $query = $field_storage_config_storage
      ->getQuery()
      ->condition('type', OgGroupAudienceHelperInterface::GROUP_REFERENCE)
      ->condition('entity_type', $entity_type);

    /** @var \Drupal\field\FieldStorageConfigInterface[] $fields */
    $fields = array_filter($field_storage_config_storage
      ->loadMultiple($query
      ->execute()), function (FieldStorageConfigInterface $field) use ($group) {
      $type_matches = $field
        ->getSetting('target_type') === $group
        ->getEntityTypeId();

      // If the list of target bundles is empty, it targets all bundles.
      $bundle_matches = empty($field
        ->getSetting('target_bundles')) || in_array($group
        ->bundle(), $field
        ->getSetting('target_bundles'));
      return $type_matches && $bundle_matches;
    });

    // Compile the group content.
    $ids = [];
    foreach ($fields as $field) {

      // Query all group content that references the group through this field.
      $results = $this->entityTypeManager
        ->getStorage($entity_type)
        ->getQuery()
        ->condition($field
        ->getName() . '.target_id', $group
        ->id())
        ->condition($definition
        ->getKey('bundle'), $bundles, 'IN')
        ->accessCheck()
        ->sort('created', 'DESC')
        ->range(0, $this->configuration['count'])
        ->execute();
      $ids = array_merge($ids, $results);
    }
    return $this->entityTypeManager
      ->getStorage($entity_type)
      ->loadMultiple($ids);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. 2
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function
PluginWithFormsTrait::hasFormClass public function
RecentGroupContentBlock::$entityTypeBundleInfo protected property The bundle information service.
RecentGroupContentBlock::$entityTypeManager protected property The entity type manager, needed to load entities.
RecentGroupContentBlock::$groupTypeManager protected property The OG group type manager.
RecentGroupContentBlock::$ogContext protected property The OG context provider.
RecentGroupContentBlock::blockForm public function Overrides BlockPluginTrait::blockForm
RecentGroupContentBlock::blockSubmit public function Overrides BlockPluginTrait::blockSubmit
RecentGroupContentBlock::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
RecentGroupContentBlock::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
RecentGroupContentBlock::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
RecentGroupContentBlock::getCacheContexts public function The cache contexts associated with this object. Overrides ContextAwarePluginBase::getCacheContexts
RecentGroupContentBlock::getCacheTags public function The cache tags associated with this object. Overrides ContextAwarePluginBase::getCacheTags
RecentGroupContentBlock::getGroupContent protected function Returns the most recent group content for the active group.
RecentGroupContentBlock::__construct public function Constructs a RecentGroupContentBlock object. Overrides BlockPluginTrait::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2