You are here

public function FieldContextHandler::getContexts in Core Context 8

Returns all contexts attached to an entity.

Parameters

\Drupal\Core\Entity\EntityInterface $entity:

Return value

\Drupal\Component\Plugin\Context\ContextInterface[]

Overrides EntityContextHandlerInterface::getContexts

File

src/FieldContextHandler.php, line 59

Class

FieldContextHandler
Exposes contexts stored on an entity field.

Namespace

Drupal\core_context

Code

public function getContexts(EntityInterface $entity) {
  assert($entity instanceof FieldableEntityInterface);
  $entity_type_id = $entity
    ->getEntityTypeId();
  $field_map = $this->entityFieldManager
    ->getFieldMapByFieldType('context');
  if (empty($field_map[$entity_type_id])) {
    return [];
  }
  $field_name = key($field_map[$entity_type_id]);
  $contexts = [];
  if ($entity
    ->hasField($field_name) === FALSE) {
    return $contexts;
  }
  $items = $entity
    ->get($field_name);
  if ($items
    ->isEmpty()) {
    return $contexts;
  }

  /** @var \Drupal\core_context\Plugin\Field\FieldType\ContextItem $item */
  foreach ($items as $item) {
    $contexts[$item->id] = $item
      ->getValue();
  }
  $contexts = $this->contextMapper
    ->getContextValues($contexts);
  return $this
    ->applyCaching($contexts, $entity);
}