EntityContextDefinition.php in Drupal 10
File
core/lib/Drupal/Core/Plugin/Context/EntityContextDefinition.php
View source
<?php
namespace Drupal\Core\Plugin\Context;
use Drupal\Core\Entity\ContentEntityStorageInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Plugin\DataType\EntityAdapter;
use Drupal\Core\Entity\Plugin\Validation\Constraint\BundleConstraint;
use Drupal\Core\Entity\TypedData\EntityDataDefinition;
class EntityContextDefinition extends ContextDefinition {
public function __construct($data_type = 'any', $label = NULL, $required = TRUE, $multiple = FALSE, $description = NULL, $default_value = NULL) {
if (strpos($data_type, 'entity:') !== 0) {
$data_type = "entity:{$data_type}";
}
parent::__construct($data_type, $label, $required, $multiple, $description, $default_value);
}
protected function getEntityTypeId() {
return substr($this
->getDataType(), 7);
}
protected function getConstraintObjects() {
if (!$this
->getConstraint('EntityType')) {
$this
->addConstraint('EntityType', [
'type' => $this
->getEntityTypeId(),
]);
}
return parent::getConstraintObjects();
}
protected function getSampleValues() {
$constraints = $this
->getConstraintObjects();
$entity_type_manager = \Drupal::entityTypeManager();
$entity_type_id = $this
->getEntityTypeId();
$entity_type = $entity_type_manager
->getDefinition($entity_type_id);
$storage = $entity_type_manager
->getStorage($entity_type_id);
if ($storage instanceof ContentEntityStorageInterface) {
if (!empty($constraints['Bundle']) && $constraints['Bundle'] instanceof BundleConstraint) {
foreach ($constraints['Bundle']
->getBundleOption() as $bundle) {
$values = [
$entity_type
->getKey('bundle') => $bundle,
];
(yield EntityAdapter::createFromEntity($storage
->create($values)));
}
return;
}
}
$definition = EntityDataDefinition::create($entity_type_id);
(yield new EntityAdapter($definition));
}
public static function fromEntityTypeId($entity_type_id) {
$entity_type = \Drupal::entityTypeManager()
->getDefinition($entity_type_id);
return static::fromEntityType($entity_type);
}
public static function fromEntityType(EntityTypeInterface $entity_type) {
return new static('entity:' . $entity_type
->id(), $entity_type
->getLabel());
}
public static function fromEntity(EntityInterface $entity) {
return static::fromEntityType($entity
->getEntityType());
}
}