fromEntity example

/** * {@inheritdoc} */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $current_user = $this->userStorage->load($this->account->id());

    if ($current_user) {
      // @todo Do not validate protected fields to avoid bug in TypedData,       // remove this in https://www.drupal.org/project/drupal/issues/2934192.       $current_user->_skipProtectedUserFieldConstraint = TRUE;

      $context = EntityContext::fromEntity($current_user$this->t('Current user'));
    }
    else {
      // If not user is available, provide an empty context object.       $context = EntityContext::fromEntityTypeId('user', $this->t('Current user'));
    }

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['user']);
    $context->addCacheableDependency($cacheability);

    $result = [
      

    return $key;
  }

  /** * {@inheritdoc} */
  public function deriveContextsFromRoute($value$definition$name, array $defaults) {
    $contexts = [];

    if ($entity = $this->extractEntityFromRoute($value$defaults)) {
      $contexts['entity'] = EntityContext::fromEntity($entity);
      // @todo Expand to work for all view modes in       // https://www.drupal.org/node/2907413.       $view_mode = 'full';
      // Retrieve the actual view mode from the returned view display as the       // requested view mode may not exist and a fallback will be used.       $view_mode = LayoutBuilderEntityViewDisplay::collectRenderDisplay($entity$view_mode)->getMode();
      $contexts['view_mode'] = new Context(new ContextDefinition('string')$view_mode);
    }
    return $contexts;
  }

  

  public function testValidateConfigEntityContext() {
    $display = EntityViewDisplay::create([
      'targetEntityType' => 'entity_test',
      'bundle' => 'entity_test',
      'mode' => 'default',
      'status' => TRUE,
    ]);
    $display->save();

    $violations = EntityContext::fromEntity($display)->validate();
    $this->assertCount(0, $violations);
  }

}
'bundle' => 'entity_test',
      'mode' => 'default',
      'status' => TRUE,
    ]);
    if ($is_enabled) {
      $display->enableLayoutBuilder();
    }
    $display
      ->setThirdPartySetting('layout_builder', 'sections', $section_data)
      ->save();

    $this->plugin->setContext('display', EntityContext::fromEntity($display));
    $result = $this->plugin->access($operation);
    $this->assertSame($expected$result);
  }

  /** * Provides test data for ::testAccess(). */
  public function providerTestAccess() {
    $section_data = [
      new Section(
        'layout_onecol',
        [],
public function __construct(AccountInterface $account, EntityTypeManagerInterface $entity_type_manager) {
    $this->account = $account;
    $this->userStorage = $entity_type_manager->getStorage('user');
  }

  /** * {@inheritdoc} */
  public function getRuntimeContexts(array $unqualified_context_ids) {
    $current_user = $this->userStorage->load($this->account->id());

    $context1 = EntityContext::fromEntity($current_user, 'User A');
    $context2 = EntityContext::fromEntity($current_user, 'User B');

    $cacheability = new CacheableMetadata();
    $cacheability->setCacheContexts(['user']);

    $context1->addCacheableDependency($cacheability);
    $context2->addCacheableDependency($cacheability);

    return [
      'userA' => $context1,
      'userB' => $context2,
    ];
/** * {@inheritdoc} */
  public function getContextsDuringPreview() {
    $contexts = parent::getContextsDuringPreview();

    // During preview add a sample entity for the target entity type and bundle.     $display = $this->getDisplay();
    $entity = $this->sampleEntityGenerator->get($display->getTargetEntityTypeId()$display->getTargetBundle());

    $contexts['layout_builder.entity'] = EntityContext::fromEntity($entity);
    return $contexts;
  }

  /** * {@inheritdoc} */
  public function deriveContextsFromRoute($value$definition$name, array $defaults) {
    $contexts = [];

    if ($entity = $this->extractEntityFromRoute($value$defaults)) {
      $contexts['display'] = EntityContext::fromEntity($entity);
    }
$section_storage_manager->load('')->willReturn(NULL);
    $section_storage_manager->findByContext(Argument::cetera())->will(function D$arguments) {
      return $arguments[0];
    });
    $this->container->set('plugin.manager.layout_builder.section_storage', $section_storage_manager->reveal());
    $entity = $this->container->get('entity_type.manager')->getStorage($entity_type_id)->create($values);
    $entity->save();
    $class = new TestLayoutEntityHelperTrait();
    $result = $class->getSectionStorageForEntity($entity);
    $this->assertEquals($expected_context_keysarray_keys($result));
    if ($entity instanceof EntityViewDisplayInterface) {
      $this->assertEquals(EntityContext::fromEntity($entity)$result['display']);
    }
    elseif ($entity instanceof FieldableEntityInterface) {
      $this->assertEquals(EntityContext::fromEntity($entity)$result['entity']);
      $this->assertInstanceOf(Context::class$result['view_mode']);
      $this->assertEquals('full', $result['view_mode']->getContextData()->getValue());

      $expected_display = EntityViewDisplay::collectRenderDisplay($entity, 'full');
      $this->assertInstanceOf(EntityContext::class$result['display']);
      /** @var \Drupal\Core\Plugin\Context\EntityContext $display_entity_context */
      $display_entity_context = $result['display'];

      

  public function testContextAvailable() {
    NodeType::create(['type' => 'example', 'name' => 'Example'])->save();
    /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
    $condition = \Drupal::service('plugin.manager.condition')
      ->createInstance('condition_test_optional_context')
      ->setContextMapping([
        'node' => 'node',
      ]);
    $node = Node::create(['type' => 'example']);
    $contexts['node'] = EntityContext::fromEntity($node);
    \Drupal::service('context.handler')->applyContextMapping($condition$contexts);
    $this->assertFalse($condition->execute());
  }

}
$error = [
      'entity' => $entity,
      'pointer' => $pointer,
      'reason' => NULL,
      'relationship_field' => $relationship_field,
    ];
    if ($entity_access instanceof AccessResultReasonInterface) {
      $error['reason'] = $entity_access->getReason();
    }
    $this->error = $error;
    // @todo: remove this ternary operation in https://www.drupal.org/project/drupal/issues/2997594.     $this->resourceIdentifier = $entity ? ResourceIdentifier::fromEntity($entity) : NULL;
  }

  /** * Returns the error. * * @return array * The error. */
  public function getError() {
    return $this->error;
  }

}
$display->enableLayoutBuilder();
    }
    $display
      ->setOverridable()
      ->save();

    $entity = EntityTest::create([OverridesSectionStorage::FIELD_NAME => $section_data]);
    $entity->save();

    $account = $this->setUpCurrentUser([]$permissions);

    $this->plugin->setContext('entity', EntityContext::fromEntity($entity));
    $this->plugin->setContext('view_mode', new Context(new ContextDefinition('string'), 'default'));

    // Check access with both the global current user as well as passing one in.     $result = $this->plugin->access('view');
    $this->assertSame($expected$result);
    $result = $this->plugin->access('view', $account);
    $this->assertSame($expected$result);

    // Create a translation.     ConfigurableLanguage::createFromLangcode('es')->save();
    $entity = EntityTest::load($entity->id());
    

  protected function getSectionStorageForEntity(EntityInterface $entity) {
    // @todo Take into account other view modes in     // https://www.drupal.org/node/3008924.     $view_mode = 'full';
    if ($entity instanceof LayoutEntityDisplayInterface) {
      $contexts['display'] = EntityContext::fromEntity($entity);
      $contexts['view_mode'] = new Context(new ContextDefinition('string')$entity->getMode());
    }
    else {
      $contexts['entity'] = EntityContext::fromEntity($entity);
      if ($entity instanceof FieldableEntityInterface) {
        $display = EntityViewDisplay::collectRenderDisplay($entity$view_mode);
        if ($display instanceof LayoutEntityDisplayInterface) {
          $contexts['display'] = EntityContext::fromEntity($display);
        }
        $contexts['view_mode'] = new Context(new ContextDefinition('string')$view_mode);
      }
    }

  protected function doTestIdenticalUser() {
    /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
    $condition = \Drupal::service('plugin.manager.condition')
      ->createInstance('condition_test_dual_user')
      // Map the anonymous user to both contexts.       ->setContextMapping([
        'user1' => 'anonymous',
        'user2' => 'anonymous',
      ]);
    $contexts['anonymous'] = EntityContext::fromEntity($this->anonymous);
    \Drupal::service('context.handler')->applyContextMapping($condition$contexts);
    $this->assertTrue($condition->execute());
  }

  /** * Tests with each context mapped to different users. */
  protected function doTestDifferentUser() {
    /** @var \Drupal\Core\Condition\ConditionPluginBase $condition */
    $condition = \Drupal::service('plugin.manager.condition')
      ->createInstance('condition_test_dual_user')
      

  protected function buildSections(FieldableEntityInterface $entity) {
    $contexts = $this->getContextsForEntity($entity);
    // @todo Remove in https://www.drupal.org/project/drupal/issues/3018782.     $label = new TranslatableMarkup('@entity being viewed', [
      '@entity' => $entity->getEntityType()->getSingularLabel(),
    ]);
    $contexts['layout_builder.entity'] = EntityContext::fromEntity($entity$label);

    $cacheability = new CacheableMetadata();
    $storage = $this->sectionStorageManager()->findByContext($contexts$cacheability);

    $build = [];
    if ($storage) {
      foreach ($storage->getSections() as $delta => $section) {
        $build[$delta] = $section->toRenderArray($contexts);
      }
    }
    // The render array is built based on decisions made by @SectionStorage

  public function testIsSatisfiedBy() {
    $this->installEntitySchema('user');

    $value = EntityTest::create([]);
    // Assert that the entity has at least one violation.     $this->assertNotEmpty($value->validate());
    // Assert that these violations do not prevent it from satisfying the     // requirements of another object.     $requirement = new ContextDefinition('any');
    $context = EntityContext::fromEntity($value);
    $this->assertTrue($requirement->isSatisfiedBy($context));

    // Test with multiple values.     $definition = EntityContextDefinition::create('entity_test');
    $definition->setMultiple();
    $entities = [
      EntityTest::create([]),
      EntityTest::create([]),
    ];
    $context = new Context($definition$entities);
    $this->assertTrue($definition->isSatisfiedBy($context));
  }

  protected static $modules = [
    'entity_test',
    'user',
  ];

  /** * @covers ::applyContextMapping */
  public function testApplyContextMapping() {
    $entity = EntityTest::create([]);
    $context_definition = EntityContextDefinition::fromEntity($entity);
    $context = EntityContext::fromEntity($entity);

    $definition = ['context_definitions' => ['a_context_id' => $context_definition]];
    $plugin = new TestContextAwarePlugin([], 'test_plugin_id', $definition);
    (new ContextHandler())->applyContextMapping($plugin['a_context_id' => $context]);

    $result = $plugin->getContext('a_context_id');

    $this->assertInstanceOf(EntityContext::class$result);
    $this->assertSame($context$result);
  }

  
Home | Imprint | This part of the site doesn't use cookies.