loadByProperties example



    // Create a Tools menu link for 'node', move the last parent node menu     // link below it, and verify a full breadcrumb for the last child node.     $menu = 'tools';
    $edit = [
      'title[0][value]' => 'Root',
      'link[0][uri]' => '/node',
    ];
    $this->drupalGet("admin/structure/menu/manage/{$menu}/add");
    $this->submitForm($edit, 'Save');
    $menu_links = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['title' => 'Root']);
    $link = reset($menu_links);

    $edit = [
      'menu[menu_parent]' => $link->getMenuName() . ':' . $link->getPluginId(),
    ];
    $this->drupalGet('node/' . $parent->id() . '/edit');
    $this->submitForm($edit, 'Save');

    // Add a taxonomy term/tag to last node, and add a link for that term to the     // Tools menu.     $tags = [
      
    $node = $this->drupalCreateNode(['uid' => $account->id()]);

    // Create comment.     $edit = [];
    $edit['subject[0][value]'] = $this->randomMachineName(8);
    $edit['comment_body[0][value]'] = $this->randomMachineName(16);

    $this->drupalGet('comment/reply/node/' . $node->id() . '/comment');
    $this->submitForm($edit, 'Preview');
    $this->submitForm([], 'Save');
    $this->assertSession()->pageTextContains('Your comment has been posted.');
    $comments = \Drupal::entityTypeManager()->getStorage('comment')->loadByProperties(['subject' => $edit['subject[0][value]']]);
    $comment = reset($comments);
    $this->assertNotEmpty($comment->id(), 'Comment found.');

    // Create a node with two revisions, the initial one belonging to the     // cancelling user.     $revision_node = $this->drupalCreateNode(['uid' => $account->id()]);
    $revision = $revision_node->getRevisionId();
    $settings = get_object_vars($revision_node);
    $settings['revision'] = 1;
    // Set new/current revision to someone else.     $settings['uid'] = 1;
    
$this->submitForm([], 'Delete');

    // Attempt to uninstall forum.     $this->drupalGet('admin/modules/uninstall');
    // Assert forum is still required.     $this->assertSession()->fieldDisabled('uninstall[forum]');
    $this->assertSession()->pageTextContains('To uninstall Forum, first delete all Forums terms');

    // Delete any forum terms.     $vid = $this->config('forum.settings')->get('vocabulary');
    $storage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
    $terms = $storage->loadByProperties(['vid' => $vid]);
    $storage->delete($terms);

    // Ensure that the forum node type can not be deleted.     $this->drupalGet('admin/structure/types/manage/forum');
    $this->assertSession()->linkNotExists('Delete');

    // Now attempt to uninstall forum.     $this->drupalGet('admin/modules/uninstall');
    // Assert forum is no longer required.     $this->assertSession()->fieldExists('uninstall[forum]');
    $this->drupalGet('admin/modules/uninstall');
    


    // Login as a limited-access user and create a workspace.     $this->drupalLogin($editor);
    $this->createWorkspaceThroughUi('Bears', 'bears');

    // Now edit that same workspace; We shouldn't be able to do so, since     // we don't have edit permissions.     /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $etm */
    $etm = \Drupal::service('entity_type.manager');
    /** @var \Drupal\workspaces\WorkspaceInterface $bears */
    $entity_list = $etm->getStorage('workspace')->loadByProperties(['label' => 'Bears']);
    $bears = current($entity_list);

    $this->drupalGet("/admin/config/workflow/workspaces/manage/{$bears->id()}/edit");
    $this->assertSession()->statusCodeEquals(403);
  }

  /** * Verifies that a user can create and edit only their own workspace. */
  public function testEditOwnWorkspace() {
    $permissions = [
      
$flood_config = $this->configFactory->get('user.flood');
    $username = $request->headers->get('PHP_AUTH_USER');
    $password = $request->headers->get('PHP_AUTH_PW');
    // Flood protection: this is very similar to the user login form code.     // @see \Drupal\user\Form\UserLoginForm::validateAuthentication()     // Do not allow any login from the current user's IP if the limit has been     // reached. Default is 50 failed attempts allowed in one hour. This is     // independent of the per-user limit to catch attempts from one IP to log     // in to many different user accounts. We have a reasonably high limit     // since there may be only one apparent IP for all users at an institution.     if ($this->flood->isAllowed('basic_auth.failed_login_ip', $flood_config->get('ip_limit')$flood_config->get('ip_window'))) {
      $accounts = $this->entityTypeManager->getStorage('user')->loadByProperties(['name' => $username, 'status' => 1]);
      $account = reset($accounts);
      if ($account) {
        if ($flood_config->get('uid_only')) {
          // Register flood events based on the uid only, so they apply for any           // IP address. This is the most secure option.           $identifier = $account->id();
        }
        else {
          // The default identifier is a combination of uid and IP address. This           // is less secure but more resistant to denial-of-service attacks that           // could lock out all users with public user names.
/** * Checks if the given entity exists. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity for which to test existence. * * @return bool * Whether the entity already has been created. */
  protected function entityExists(EntityInterface $entity) {
    $entity_storage = $this->entityTypeManager->getStorage($entity->getEntityTypeId());
    return !empty($entity_storage->loadByProperties([
      'uuid' => $entity->uuid(),
    ]));
  }

  /** * Extracts JSON:API query parameters from the request. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The JSON:API resource type. * * @return array * An array of JSON:API parameters like `sort` and `filter`. */

  public function testLoadMissingFid() {
    $this->assertNull(File::load(-1), 'Try to load an invalid fid fails.');
    $this->assertFileHooksCalled([]);
  }

  /** * Try to load a non-existent file by URI. */
  public function testLoadMissingFilepath() {
    $files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => 'foobar://misc/druplicon.png']);
    $this->assertFalse(reset($files), "Try to load a file that doesn't exist in the database fails.");
    $this->assertFileHooksCalled([]);
  }

  /** * Try to load a non-existent file by status. */
  public function testLoadInvalidStatus() {
    $files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['status' => -99]);
    $this->assertFalse(reset($files), 'Trying to load a file with an invalid status fails.');
    $this->assertFileHooksCalled([]);
  }
$resource_type_repository
      ->getByTypeName(Argument::any())
      ->willReturn(new ResourceType('node', 'article', NULL));

    $entity_storage = $this->prophesize(EntityStorageInterface::class);
    $self = $this;
    $uuid_to_id = [
      '76dd5c18-ea1b-4150-9e75-b21958a2b836' => 1,
      'fcce1b61-258e-4054-ae36-244d25a9e04c' => 2,
    ];
    $entity_storage->loadByProperties(Argument::type('array'))
      ->will(function D$args) use ($self$uuid_to_id) {
        $result = [];
        foreach ($args[0]['uuid'] as $uuid) {
          $entity = $self->prophesize(EntityInterface::class);
          $entity->uuid()->willReturn($uuid);
          $entity->id()->willReturn($uuid_to_id[$uuid]);
          $result[$uuid] = $entity->reveal();
        }
        return $result;
      });
    $entity_type_manager = $this->prophesize(EntityTypeManagerInterface::class);
    
->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', $bundle)
      ->execute();
    $this->assertCount(10, $found, 'Correct number of entities found before deleting');

    // Delete the field.     $field = FieldConfig::loadByName($this->entityTypeId, $bundle$field_name);
    $field->delete();

    // The field still exists, deleted.     $fields = \Drupal::entityTypeManager()->getStorage('field_config')->loadByProperties(['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
    $this->assertCount(1, $fields, 'There is one deleted field');
    $field = $fields[$field->uuid()];
    $this->assertEquals($bundle$field->getTargetBundle(), 'The deleted field is for the correct bundle');

    // Check that the actual stored content did not change during delete.     /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage->getTableMapping();
    $table = $table_mapping->getDedicatedDataTableName($field_storage);
    $column = $table_mapping->getFieldColumnName($field_storage, 'value');
    $result = Database::getConnection()->select($table, 't')
      ->fields('t')
      
'enabled[value]' => 1,
      'expanded[value]' => $expanded,
      'menu_parent' => $menu_id . ':' . $parent,
      'weight[0][value]' => $weight,
    ];

    // Add menu link.     $this->submitForm($edit, 'Save');
    $this->assertSession()->pageTextContains('The menu link has been saved.');

    $storage = $this->container->get('entity_type.manager')->getStorage('menu_link_content');
    $menu_links = $storage->loadByProperties(['title' => $title]);
    $menu_link = reset($menu_links);

    // Check that the stored menu link meeting the expectations.     $this->assertNotNull($menu_link);
    $this->assertMenuLink([
      'menu_name' => $menu_id,
      'children' => [],
      'parent' => $parent,
    ]$menu_link->getPluginId());

    return $menu_link;
  }
$label = $this->menu->label();

    // Delete custom menu.     $this->drupalGet("admin/structure/menu/manage/{$menu_name}/delete");
    $this->submitForm([], 'Delete');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->addressEquals("admin/structure/menu");
    $this->assertSession()->pageTextContains("The menu $label has been deleted.");
    $this->assertNull(Menu::load($menu_name), 'Custom menu was deleted');
    // Test if all menu links associated with the menu were removed from     // database.     $result = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(['menu_name' => $menu_name]);
    $this->assertEmpty($result, 'All menu links associated with the custom menu were deleted.');

    // Make sure there's no delete button on system menus.     $this->drupalGet('admin/structure/menu/manage/main');
    $this->assertSession()->responseNotContains('edit-delete');

    // Try to delete the main menu.     $this->drupalGet('admin/structure/menu/manage/main/delete');
    $this->assertSession()->pageTextContains('You are not authorized to access this page.');
  }

  
/** * Returns an array of permissions. * * @return string[][] * An array whose keys are permission names and whose corresponding values * are defined in \Drupal\user\PermissionHandlerInterface::getPermissions(). */
  public function permissions() {
    $permissions = [];

    /** @var \Drupal\layout_builder\Entity\LayoutEntityDisplayInterface[] $entity_displays */
    $entity_displays = $this->entityTypeManager->getStorage('entity_view_display')->loadByProperties(['third_party_settings.layout_builder.allow_custom' => TRUE]);
    foreach ($entity_displays as $entity_display) {
      $entity_type_id = $entity_display->getTargetEntityTypeId();
      $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);
      $bundle = $entity_display->getTargetBundle();
      $args = [
        '%entity_type' => $entity_type->getCollectionLabel(),
        '@entity_type_singular' => $entity_type->getSingularLabel(),
        '@entity_type_plural' => $entity_type->getPluralLabel(),
        '%bundle' => $this->bundleInfo->getBundleInfo($entity_type_id)[$bundle]['label'],
      ];
      // These permissions are generated on behalf of $entity_display entity
$this->submitForm($edit, 'Save');
    $this->assertSession()->statusCodeEquals(200);
    $type = ($type == 'container') ? 'forum container' : 'forum';
    $this->assertSession()->pageTextContains('Created new ' . $type . ' ' . $name . '.');

    // Verify that the creation message contains a link to a term.     $this->assertSession()->elementExists('xpath', '//div[@data-drupal-messages]//a[contains(@href, "term/")]');

    /** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_term_storage */
    $taxonomy_term_storage = $this->container->get('entity_type.manager')->getStorage('taxonomy_term');
    // Verify forum.     $term = $taxonomy_term_storage->loadByProperties([
      'vid' => $this->config('forum.settings')->get('vocabulary'),
      'name' => $name,
      'description__value' => $description,
    ]);
    $term = array_shift($term);
    $this->assertNotEmpty($term, "The forum type '$type' should exist in the database.");

    // Verify forum hierarchy.     $tid = $term->id();
    $parent_tid = $taxonomy_term_storage->loadParents($tid);
    $parent_tid = empty($parent_tid) ? 0 : array_shift($parent_tid)->id();
    
// Now enable moderation state.     $this->enableModerationThroughUi('not_moderated');

    // Check that the 'Create new revision' checkbox is checked and disabled.     $this->drupalGet('/admin/structure/types/manage/not_moderated');
    $this->assertSession()->checkboxChecked('options[revision]');
    $this->assertSession()->fieldDisabled('options[revision]');

    // And make sure it works.     $nodes = \Drupal::entityTypeManager()->getStorage('node')
      ->loadByProperties(['title' => 'Test']);
    if (empty($nodes)) {
      $this->fail('Could not load node with title Test');
      return;
    }
    $node = reset($nodes);
    $this->drupalGet('node/' . $node->id());
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->linkByHrefExists('node/' . $node->id() . '/edit');
    $this->drupalGet('node/' . $node->id() . '/edit');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->optionExists('moderation_state[0][state]', 'draft');
    
    $block_storage->resetCache();
    $node_storage->resetCache();

    // Assert the removal of blocks on uninstall.     foreach ($this->expectedBlocks() as $block_info) {
      $count = $block_storage->getQuery()
        ->accessCheck(FALSE)
        ->condition('type', $block_info['type'])
        ->count()
        ->execute();
      $this->assertEquals(0, $count);
      $block = $block_storage->loadByProperties(['uuid' => $block_info['uuid']]);
      $this->assertCount(0, $block);
    }

    // Assert the removal of nodes on uninstall.     $count = $node_storage->getQuery()
      ->accessCheck(FALSE)
      ->condition('type', 'article')
      ->count()
      ->execute();
    $this->assertEquals(0, $count);

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