function EntityContextDefinition::getSampleValues

Same name in other branches
  1. 9 core/lib/Drupal/Core/Plugin/Context/EntityContextDefinition.php \Drupal\Core\Plugin\Context\EntityContextDefinition::getSampleValues()
  2. 8.9.x core/lib/Drupal/Core/Plugin/Context/EntityContextDefinition.php \Drupal\Core\Plugin\Context\EntityContextDefinition::getSampleValues()
  3. 11.x core/lib/Drupal/Core/Plugin/Context/EntityContextDefinition.php \Drupal\Core\Plugin\Context\EntityContextDefinition::getSampleValues()

Overrides ContextDefinition::getSampleValues

File

core/lib/Drupal/Core/Plugin/Context/EntityContextDefinition.php, line 55

Class

EntityContextDefinition
Defines a class to provide entity context definitions.

Namespace

Drupal\Core\Plugin\Context

Code

protected function getSampleValues() {
    // Get the constraints from the context's definition.
    $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 the storage can generate a sample entity we might delegate to that.
    if ($storage instanceof ContentEntityStorageInterface) {
        if (!empty($constraints['Bundle']) && $constraints['Bundle'] instanceof BundleConstraint) {
            foreach ($constraints['Bundle']->getBundleOption() as $bundle) {
                // We have a bundle, we are bundleable and we can generate a sample.
                $values = [
                    $entity_type->getKey('bundle') => $bundle,
                ];
                (yield EntityAdapter::createFromEntity($storage->create($values)));
            }
            return;
        }
    }
    // Either no bundle, or not bundleable, so generate an entity adapter.
    $definition = EntityDataDefinition::create($entity_type_id);
    (yield new EntityAdapter($definition));
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.