awareness-1.0.0-alpha5/src/Context/ContextRespositoryAwareTrait.php
src/Context/ContextRespositoryAwareTrait.php
<?php
namespace Drupal\awareness\Context;
use Drupal\Core\Entity\Plugin\DataType\EntityAdapter;
/**
* Trait for classes that utilize context.repository service.
*/
trait ContextRespositoryAwareTrait {
/**
* Get the context repository service.
*
* @return \Drupal\Core\Plugin\Context\ContextRepositoryInterface
* The context repository service.
*/
protected function getContextRepository() {
return \Drupal::service('context.repository');
}
/**
* Get a value from context.
*
* @param string $context_id
* The context ID.
*
* @return \Drupal\Core\Plugin\Context\ContextInterface|null
* The context, or NULL if not available.
*/
protected function getContextValue($context_id) {
$contexts = $this->getContextRepository()->getRuntimeContexts([$context_id]);
return $contexts[$context_id] ?? NULL;
}
/**
* Get the entity value from a context.
*
* @param string $context_id
* The context ID.
*
* @return \Drupal\Core\Entity\EntityInterface|null
* The entity, or NULL if not available.
*/
protected function getContextEntityValue($context_id) {
$data = $this->getContextValue($context_id)->getContextData();
return $data instanceof EntityAdapter ? $data->getEntity() : NULL;
}
}
