getStorage example

// Get the ID key from the base field definition for the bundle key or     // default to 'value'.     $key_id = isset($base_field_definitions[$bundle_key]) ? $base_field_definitions[$bundle_key]->getFieldStorageDefinition()->getMainPropertyName() : 'value';

    // Normalize the bundle if it is not explicitly set.     $bundle_value = $data[$bundle_key][0][$key_id] ?? ($data[$bundle_key] ?? NULL);
    // Unset the bundle from the data.     unset($data[$bundle_key]);

    // Get the bundle entity type from the entity type definition.     $bundle_type_id = $entity_type_definition->getBundleEntityType();
    $bundle_types = $bundle_type_id ? $this->getEntityTypeManager()->getStorage($bundle_type_id)->getQuery()->accessCheck(TRUE)->execute() : [];

    // Make sure a bundle has been provided.     if (!is_string($bundle_value)) {
      throw new UnexpectedValueException(sprintf('Could not determine entity type bundle: "%s" field is missing.', $bundle_key));
    }

    // Make sure the submitted bundle is a valid bundle for the entity type.     if ($bundle_types && !in_array($bundle_value$bundle_types)) {
      throw new UnexpectedValueException(sprintf('"%s" is not a valid bundle type for denormalization.', $bundle_value));
    }

    

    return $options;
  }

  /** * {@inheritdoc} */
  public function calculateDependencies() {
    $dependencies = parent::calculateDependencies();

    $view_mode = $this->entityTypeManager
      ->getStorage('entity_view_mode')
      ->load($this->entityTypeId . '.' . $this->options['view_mode']);
    if ($view_mode) {
      $dependencies[$view_mode->getConfigDependencyKey()][] = $view_mode->getConfigDependencyName();
    }

    return $dependencies;
  }

}
public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')
    );
  }

  /** * {@inheritdoc} */
  public function validate($entity, Constraint $constraint) {
    if ($entity && !$entity->isNew() && !$entity->isDefaultRevision()) {
      $original = $this->entityTypeManager->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());

      // Ensure that empty items do not affect the comparison checks below.       // @todo Remove this filtering when       // https://www.drupal.org/project/drupal/issues/3039031 is fixed.       $entity->parent->filterEmptyItems();
      if (($entity->parent->isEmpty() !== $original->parent->isEmpty()) || !$entity->parent->equals($original->parent)) {
        $this->context->buildViolation($constraint->message)
          ->atPath('menu_parent')
          ->addViolation();
      }
      if (!$entity->weight->equals($original->weight)) {
        

class EntityChangedConstraintValidator extends ConstraintValidator {

  /** * {@inheritdoc} */
  public function validate($entity, Constraint $constraint) {
    if (isset($entity)) {
      /** @var \Drupal\Core\Entity\EntityInterface $entity */
      if (!$entity->isNew()) {
        $saved_entity = \Drupal::entityTypeManager()->getStorage($entity->getEntityTypeId())->loadUnchanged($entity->id());
        // Ensure that all the entity translations are the same as or newer         // than their current version in the storage in order to avoid         // reverting other changes. In fact the entity object that is being         // saved might contain an older entity translation when different         // translations are being concurrently edited.         if ($saved_entity) {
          $common_translation_languages = array_intersect_key($entity->getTranslationLanguages()$saved_entity->getTranslationLanguages());
          foreach (array_keys($common_translation_languages) as $langcode) {
            // Merely comparing the latest changed timestamps across all             // translations is not sufficient since other translations may have             // been edited and saved in the meanwhile. Therefore, compare the
        // configuration entities can have dependencies on modules that are         // not yet enabled. This approach means that any code that expects         // default configuration entities to exist will be unstable after the         // module has been enabled and before the config entity has been         // imported.         if ($this->isSyncing()) {
          continue;
        }
        /** @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface $entity_storage */
        $entity_storage = $this->configManager
          ->getEntityTypeManager()
          ->getStorage($entity_type);

        $id = $entity_storage->getIDFromConfigName($name$entity_storage->getEntityType()->getConfigPrefix());
        // It is possible that secondary writes can occur during configuration         // creation. Updates of such configuration are allowed.         if ($this->getActiveStorages($collection)->exists($name)) {
          $entity = $entity_storage->load($id);
          $entity = $entity_storage->updateFromStorageRecord($entity$new_config->get());
        }
        else {
          $entity = $entity_storage->createFromStorageRecord($new_config->get());
        }
        

  protected function getEntity() {
    if (!isset($this->blockContent)) {
      if (!empty($this->configuration['block_serialized'])) {
        $this->blockContent = unserialize($this->configuration['block_serialized']);
      }
      elseif (!empty($this->configuration['block_revision_id'])) {
        $entity = $this->entityTypeManager->getStorage('block_content')->loadRevision($this->configuration['block_revision_id']);
        $this->blockContent = $entity;
      }
      else {
        $this->blockContent = $this->entityTypeManager->getStorage('block_content')->create([
          'type' => $this->getDerivativeId(),
          'reusable' => FALSE,
        ]);
      }
      if ($this->blockContent instanceof RefinableDependentAccessInterface && $dependee = $this->getAccessDependency()) {
        $this->blockContent->setAccessDependency($dependee);
      }
    }
/** * Provides a form for content type deletion. * * @internal */
class NodeTypeDeleteConfirm extends EntityDeleteForm {

  /** * {@inheritdoc} */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $num_nodes = $this->entityTypeManager->getStorage('node')->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', $this->entity->id())
      ->count()
      ->execute();
    if ($num_nodes) {
      $caption = '<p>' . $this->formatPlural($num_nodes, '%type is used by 1 piece of content on your site. You can not remove this content type until you have removed all of the %type content.', '%type is used by @count pieces of content on your site. You may not remove %type until you have removed all of the %type content.', ['%type' => $this->entity->label()]) . '</p>';
      $form['#title'] = $this->getQuestion();
      $form['description'] = ['#markup' => $caption];
      return $form;
    }

    

  public static $testViews = ['test_view_storage'];

  /** * Tests CRUD operations. */
  public function testConfigurationEntityCRUD() {
    // Get the configuration entity type and controller.     $this->entityType = \Drupal::entityTypeManager()->getDefinition('view');
    $this->controller = $this->container->get('entity_type.manager')->getStorage('view');

    // Confirm that an info array has been returned.     $this->assertInstanceOf(EntityTypeInterface::class$this->entityType);

    // CRUD tests.     $this->loadTests();
    $this->createTests();
    $this->displayTests();

    // Helper method tests     $this->displayMethodTests();
  }
if ($event->isPublishingStopped()) {
      throw new WorkspacePublishException((string) $event->getPublishingStoppedReason());
    }

    try {
      $transaction = $this->database->startTransaction();
      // @todo Handle the publishing of a workspace with a batch operation in       // https://www.drupal.org/node/2958752.       $this->workspaceManager->executeOutsideWorkspace(function D) use ($tracked_entities) {
        foreach ($tracked_entities as $entity_type_id => $revision_difference) {
          $entity_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultipleRevisions(array_keys($revision_difference));
          $default_revisions = $this->entityTypeManager->getStorage($entity_type_id)
            ->loadMultiple(array_values($revision_difference));

          /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
          foreach ($entity_revisions as $entity) {
            // When pushing workspace-specific revisions to the default             // workspace (Live), we simply need to mark them as default             // revisions.             $entity->setSyncing(TRUE);
            $entity->isDefaultRevision(TRUE);

            
$this->roleStorage = $role_storage;
  }

  /** * {@inheritdoc} */
  public static function create(ContainerInterface $container, array $configuration$plugin_id$plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')->getStorage('user_role')
    );
  }

  /** * {@inheritdoc} */
  public function access(AccountInterface $account) {
    return !empty(array_intersect(array_filter($this->options['role'])$account->getRoles()));
  }

  /** * {@inheritdoc} */
$this->fileRepository->copy($source, 'foo://');
  }

  /** * Tests for entity storage exception. * * @covers ::copy */
  public function testEntityStorageException() {
    /** @var \Drupal\Core\Entity\EntityTypeManager $entityTypeManager */
    $entityTypeManager = $this->prophesize(EntityTypeManager::class);
    $entityTypeManager->getStorage('file')
      ->willThrow(EntityStorageException::class);

    $fileRepository = new FileRepository(
      $this->container->get('file_system'),
      $this->container->get('stream_wrapper_manager'),
      $entityTypeManager->reveal(),
      $this->container->get('module_handler'),
      $this->container->get('file.usage'),
      $this->container->get('current_user')
    );

    
$result = $adapter->authenticate();

        /** * ZF-7546 - prevent multiple succesive calls from storing inconsistent results * Ensure storage has clean state */
        if ($this->hasIdentity()) {
            $this->clearIdentity();
        }

        if ($result->isValid()) {
            $this->getStorage()->write($result->getIdentity());
        }

        return $result;
    }

    /** * Returns true if and only if an identity is available from storage * * @return boolean */
    public function hasIdentity()
    {
// Add a term.     $this->drupalGet('admin/structure/taxonomy/manage/' . $this->vocabulary->id() . '/add');
    // Check that we have the language selector.     $this->assertSession()->fieldExists('edit-langcode-0-value');
    // Submit the term.     $edit = [
      'name[0][value]' => $this->randomMachineName(),
      'langcode[0][value]' => 'aa',
    ];
    $this->submitForm($edit, 'Save');
    $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
      'name' => $edit['name[0][value]'],
    ]);
    $term = reset($terms);
    $this->assertEquals($edit['langcode[0][value]']$term->language()->getId(), 'The term contains the correct langcode.');

    // Check if on the edit page the language is correct.     $this->drupalGet('taxonomy/term/' . $term->id() . '/edit');
    $this->assertTrue($this->assertSession()->optionExists('edit-langcode-0-value', $edit['langcode[0][value]'])->isSelected());

    // Change the language of the term.     $edit['langcode[0][value]'] = 'bb';
    

    }
    return $values;
  }

  /** * {@inheritdoc} */
  public function getLocations($check_only = FALSE) {
    if (!isset($this->locations) && !$check_only) {
      $this->locations = [];
      foreach ($this->getStorage()->getLocations(['sid' => $this->getId()]) as $location) {
        $this->locations[$location->type][$location->name] = $location->lid;
      }
    }
    return $this->locations ?? [];
  }

  /** * {@inheritdoc} */
  public function addLocation($type$name) {
    $this->locations[$type][$name] = TRUE;
    
/** * Provides the menu link creation form. * * @param \Drupal\system\MenuInterface $menu * An entity representing a custom menu. * * @return array * Returns the menu link creation form. */
  public function addLink(MenuInterface $menu) {
    $menu_link = $this->entityTypeManager()
      ->getStorage('menu_link_content')
      ->create([
        'menu_name' => $menu->id(),
      ]);
    return $this->entityFormBuilder()->getForm($menu_link);
  }

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