You are here

public function CalendarEventManager::getReferencingCalendarEvents in Opigno calendar event 8

Same name and namespace in other branches
  1. 3.x src/CalendarEventManager.php \Drupal\opigno_calendar_event\CalendarEventManager::getReferencingCalendarEvents()

Returns all calendar events referencing the specified entity.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: An entity object.

Return value

\Drupal\opigno_calendar_event\CalendarEventInterface[] An array of calendar event entity objects.

File

src/CalendarEventManager.php, line 133

Class

CalendarEventManager
The calendar event manager.

Namespace

Drupal\opigno_calendar_event

Code

public function getReferencingCalendarEvents(ContentEntityInterface $entity) {
  $calendar_events = [];
  $field_definition = $this
    ->getReferencingFieldDefinition($entity
    ->getEntityTypeId(), $entity
    ->bundle());
  if (!$field_definition) {
    return $calendar_events;
  }
  try {
    $entity_type_id = CalendarEventInterface::ENTITY_TYPE_ID;
    $storage = $this->entityTypeManager
      ->getStorage($entity_type_id);
    $entity_type = $this->entityTypeManager
      ->getDefinition($entity_type_id);
    $field_name = $field_definition
      ->getName();
    $bundle_key = $entity_type
      ->getKey('bundle');
    $bundle_id = $field_definition
      ->getTargetBundle();

    // If a user has no access to a group, we assume they would also not have
    // access to the related calendar, so we keep the access check in place.
    $ids = $storage
      ->getQuery()
      ->condition($bundle_key, $bundle_id)
      ->condition($field_name, $entity
      ->id())
      ->execute();
    if ($ids) {
      $calendar_events = $storage
        ->loadMultiple($ids);
    }
    else {
      $values = [
        $bundle_key => $bundle_id,
        $field_name => $entity
          ->id(),
        'displayed' => FALSE,
      ];
      $calendar_events = [
        $storage
          ->create($values),
      ];
    }
  } catch (PluginException $e) {
    $this
      ->logException($e);
  }
  return $calendar_events;
}