You are here

media_parent_entity_link.module in Media Parent Entity Link 8

File

media_parent_entity_link.module
View source
<?php

/**
 * @file
 * Contains media_parent_entity_link.module.
 */
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Field\FormatterInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;

/**
 * Implements hook_help().
 */
function media_parent_entity_link_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Main module help for the media_parent_entity_link module.
    case 'help.page.media_parent_entity_link':
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('Link media items to their parent (referencing) entities') . '</p>';
      return $output;
    default:
  }
}

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function media_parent_entity_link_media_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {

  /* @var \Drupal\media_parent_entity_link\InitialSettingsService $initialSettings */
  $initialSettings = \Drupal::service('media_parent_entity_link.initial');
  $mediaType = \Drupal::entityTypeManager()
    ->getStorage('media_type')
    ->load($display
    ->getTargetBundle());
  if (in_array($mediaType
    ->get('source'), $initialSettings
    ->getMediasources())) {
    $sourceconfig = $mediaType
      ->get('source_configuration');
    $fieldsettings = $display
      ->getComponent($sourceconfig['source_field']);
    if (!empty($fieldsettings['third_party_settings']['media_parent_entity_link']['link_to_parent'])) {
      if ($entity->_referringItem) {
        if ($entity->_referringItem
          ->getParent()) {
          if ($entity->_referringItem
            ->getParent()
            ->getParent()) {

            /* @var \Drupal\Core\Entity\EntityInterface $parententity */
            if ($parententity = $entity->_referringItem
              ->getParent()
              ->getParent()
              ->getValue()) {
              if (!$parententity
                ->isNew() && $parententity
                ->hasLinkTemplate('canonical')) {
                $url = $parententity
                  ->toUrl();
                if ($display
                  ->getThirdPartySetting('layout_builder', 'enabled')) {
                  foreach (Element::children($build['_layout_builder']) as $delta) {
                    $section = $build['_layout_builder'][$delta];
                    if (!Element::isEmpty($section)) {

                      /** @var \Drupal\Core\Layout\LayoutDefinition $layout */
                      $layout = $section['#layout'];
                      $regions = $layout
                        ->getRegionNames();
                      foreach ($regions as $region) {
                        if (isset($section[$region])) {
                          foreach ($section[$region] as $uuid => $component) {
                            if (!empty($component['content']['#items']) && $component['content']['#field_name'] == $sourceconfig['source_field']) {
                              $items = $component['content']['#items']
                                ->count();
                              _media_parent_entity_link_set_url($build['_layout_builder'][$delta][$region][$uuid]['content'], $items, $url);
                              break;
                            }
                          }
                        }
                      }
                    }
                  }
                }
                else {
                  $items = $build[$sourceconfig['source_field']]['#items']
                    ->count();
                  _media_parent_entity_link_set_url($build[$sourceconfig['source_field']], $items, $url);
                }
              }
            }
          }
        }
      }
    }
  }
}

/**
 * Sets url property for each item in field render array.
 *
 * @param array $build
 *   Render array.
 * @param int $count
 *   Count of items in field.
 * @param \Drupal\Core\Url $url
 *   Url of parent entity.
 */
function _media_parent_entity_link_set_url(array &$build, $count, Url $url) {
  $i = 0;
  while ($i < $count) {
    $build[$i]['#url'] = $url;
    $i++;
  }
}

/**
 * Implements hook_field_formatter_third_party_settings_form().
 */
function media_parent_entity_link_field_formatter_third_party_settings_form(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, $view_mode, $form, FormStateInterface $form_state) {
  $element = [];

  /* @var \Drupal\media_parent_entity_link\InitialSettingsService $initialSettings */
  $initialSettings = \Drupal::service('media_parent_entity_link.initial');
  if ($field_definition
    ->getTargetEntityTypeId() == 'media') {
    if (in_array($plugin
      ->getPluginId(), $initialSettings
      ->getFormatters())) {
      $targetBundle = $field_definition
        ->getTargetBundle();
      if (!empty($targetBundle)) {
        $mediaType = \Drupal::entityTypeManager()
          ->getStorage('media_type')
          ->load($targetBundle);
        if (in_array($mediaType
          ->get('source'), $initialSettings
          ->getMediasources())) {
          $element['link_to_parent'] = [
            '#type' => 'checkbox',
            '#title' => t('Link to parent entity (if applicable)'),
            '#default_value' => $plugin
              ->getThirdPartySetting('media_parent_entity_link', 'link_to_parent'),
          ];
        }
      }
    }
  }
  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary_alter().
 */
function media_parent_entity_link_field_formatter_settings_summary_alter(&$summary, $context) {

  /* @var \Drupal\media_parent_entity_link\InitialSettingsService $initialSettings */
  $initialSettings = \Drupal::service('media_parent_entity_link.initial');
  if (in_array($context['formatter']
    ->getPluginId(), $initialSettings
    ->getFormatters())) {
    if ($context['formatter']
      ->getThirdPartySetting('media_parent_entity_link', 'link_to_parent')) {
      $summary[] = t('Link to parent entity (if applicable)');
    }
  }
}

/**
 * Implements hook_entity_build_defaults_alter().
 */
function media_parent_entity_link_entity_build_defaults_alter(array &$build, EntityInterface $entity, $view_mode) {

  /* @var \Drupal\media_parent_entity_link\InitialSettingsService $initialSettings */
  $initialSettings = \Drupal::service('media_parent_entity_link.initial');
  if ($entity
    ->getEntityType()
    ->id() == 'media') {
    $mediaType = \Drupal::entityTypeManager()
      ->getStorage('media_type')
      ->load($entity
      ->bundle());
    if (in_array($mediaType
      ->get('source'), $initialSettings
      ->getMediasources())) {
      $sourceconfig = $mediaType
        ->get('source_configuration');
      $display = \Drupal::entityTypeManager()
        ->getStorage('entity_view_display')
        ->load($entity
        ->getEntityType()
        ->id() . '.' . $entity
        ->bundle() . '.' . $view_mode);
      if ($display) {
        $fieldsettings = $display
          ->getComponent($sourceconfig['source_field']);
        if (!empty($fieldsettings['third_party_settings']['media_parent_entity_link']['link_to_parent'])) {
          if ($entity->_referringItem) {
            if ($entity->_referringItem
              ->getParent()) {
              if ($entity->_referringItem
                ->getParent()
                ->getParent()) {
                if ($parententity = $entity->_referringItem
                  ->getParent()
                  ->getParent()
                  ->getValue()) {
                  if (!$parententity
                    ->isNew()) {
                    $build['#cache']['contexts'][] = 'media_parent_entity:' . $parententity
                      ->bundle() . '-' . $parententity
                      ->id();
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}