/**
  * Tests language fallback candidates.
  */
 public function testCandidates()
 {
     $language_list = $this->languageManager->getLanguages();
     $expected = array_keys($language_list + array(LanguageInterface::LANGCODE_NOT_SPECIFIED => NULL));
     // Check that language fallback candidates by default are all the available
     // languages sorted by weight.
     $candidates = $this->languageManager->getFallbackCandidates();
     $this->assertEqual(array_values($candidates), $expected, 'Language fallback candidates are properly returned.');
     // Check that candidates are alterable.
     $this->state->set('language_test.fallback_alter.candidates', TRUE);
     $expected = array_slice($expected, 0, count($expected) - 1);
     $candidates = $this->languageManager->getFallbackCandidates();
     $this->assertEqual(array_values($candidates), $expected, 'Language fallback candidates are alterable.');
     // Check that candidates are alterable for specific operations.
     $this->state->set('language_test.fallback_alter.candidates', FALSE);
     $this->state->set('language_test.fallback_operation_alter.candidates', TRUE);
     $expected[] = LanguageInterface::LANGCODE_NOT_SPECIFIED;
     $expected[] = LanguageInterface::LANGCODE_NOT_APPLICABLE;
     $candidates = $this->languageManager->getFallbackCandidates(array('operation' => 'test'));
     $this->assertEqual(array_values($candidates), $expected, 'Language fallback candidates are alterable for specific operations.');
     // Check that when the site is monolingual no language fallback is applied.
     $langcodes_to_delete = array();
     foreach ($language_list as $langcode => $language) {
         if (!$language->isDefault()) {
             $langcodes_to_delete[] = $langcode;
         }
     }
     entity_delete_multiple('configurable_language', $langcodes_to_delete);
     $candidates = $this->languageManager->getFallbackCandidates();
     $this->assertEqual(array_values($candidates), array(LanguageInterface::LANGCODE_DEFAULT), 'Language fallback is not applied when the Language module is not enabled.');
 }
  /**
   * Create a refresh token for the current user
   *
   * It will delete all the existing refresh tokens for that same user as well.
   *
   * @param int $uid
   *   The user ID.
   *
   * @return \RestfulTokenAuth
   *   The token entity.
   */
  private function generateRefreshToken($uid) {
    // Check if there are other refresh tokens for the user.
    $query = new \EntityFieldQuery();
    $results = $query
      ->entityCondition('entity_type', 'restful_token_auth')
      ->entityCondition('bundle', 'refresh_token')
      ->propertyCondition('uid', $uid)
      ->execute();

    if (!empty($results['restful_token_auth'])) {
      // Delete the tokens.
      entity_delete_multiple('restful_token_auth', array_keys($results['restful_token_auth']));
    }

    // Create a new refresh token.
    $values = array(
      'uid' => $uid,
      'type' => 'refresh_token',
      'created' => REQUEST_TIME,
      'name' => t('Refresh token for: @uid', array(
        '@uid' => $uid,
      )),
      'token' => drupal_random_key(),
    );
    $refresh_token = $this->create($values);
    $this->save($refresh_token);
    return $refresh_token;
  }
 /**
  * Create, update or delete Node Gallery relationships based on field values.
  */
 public function NodeGalleryRelationshipCrud($entity_type, $entity, $field, $instance, $langcode, &$items)
 {
     $diff = $this->galleriesGetDiff($entity_type, $entity, $field, $instance, $langcode, $items);
     if (!$diff) {
         return;
     }
     $diff += array('insert' => array(), 'delete' => array());
     // Delete first, so we don't trigger cardinality errors.
     if ($diff['delete']) {
         entity_delete_multiple('node_gallery_relationship', array_keys($diff['delete']));
         foreach (array_values($diff['delete']) as $ngid) {
             if (node_gallery_api_get_cover_nid($ngid) == $entity->nid) {
                 node_gallery_api_reset_cover_item($ngid);
             }
             node_gallery_api_clear_gallery_caches($ngid);
             node_gallery_api_update_image_counts($ngid);
         }
     }
     if (!empty($diff['insert'])) {
         $relationship_type = node_gallery_api_get_relationship_type(NULL, $entity->type);
         if (!empty($relationship_type)) {
             foreach ($diff['insert'] as $ngid) {
                 $r = new NodeGalleryRelationship();
                 $r->relationship_type = $relationship_type->id;
                 $r->nid = $entity->nid;
                 $r->ngid = $ngid;
                 $r->weight = NODE_GALLERY_DEFAULT_WEIGHT;
                 $r->save();
             }
         }
     }
 }
Пример #4
0
 /**
  * Deletes all terms of a vocabulary.
  *
  * @param $vid
  *   int a vocabulary vid.
  */
 protected function deleteVocabularyTerms($vid)
 {
     $tids = array();
     foreach (taxonomy_get_tree($vid) as $term) {
         $tids[] = $term->tid;
     }
     entity_delete_multiple('taxonomy_term', $tids);
 }
 /**
  * Deleting terms should also remove related vocabulary.
  * Deleting an invalid term should silently fail.
  */
 public function testTermDelete()
 {
     $vocabulary = $this->createVocabulary();
     $valid_term = $this->createTerm($vocabulary);
     // Delete a valid term.
     $valid_term->delete();
     $terms = entity_load_multiple_by_properties('taxonomy_term', array('vid' => $vocabulary->id()));
     $this->assertTrue(empty($terms), 'Vocabulary is empty after deletion');
     // Delete an invalid term. Should not throw any notices.
     entity_delete_multiple('taxonomy_term', array(42));
 }
Пример #6
0
 /**
  * Removes any nodes created after the last node id remembered.
  *
  * @AfterScenario @reset-nodes
  */
 public function resetNodes()
 {
     if (!isset($this->maxNodeId)) {
         return;
     }
     $all_nodes_after_query = (new \EntityFieldQuery())->entityCondition('entity_type', 'node')->propertyCondition('nid', $this->maxNodeId, '>');
     $all_nodes_after = $all_nodes_after_query->execute();
     $all_nodes_after = reset($all_nodes_after);
     if (is_array($all_nodes_after)) {
         entity_delete_multiple('node', array_keys($all_nodes_after));
     }
     unset($this->maxNodeId);
 }
 /**
  * Tests that comment links are output and can be hidden.
  */
 public function testCommentLinks()
 {
     // Bartik theme alters comment links, so use a different theme.
     \Drupal::service('theme_handler')->install(array('stark'));
     \Drupal::config('system.theme')->set('default', 'stark')->save();
     // Remove additional user permissions from $this->web_user added by setUp(),
     // since this test is limited to anonymous and authenticated roles only.
     $roles = $this->web_user->getRoles();
     entity_delete_multiple('user_role', array(reset($roles)));
     // Create a comment via CRUD API functionality, since
     // $this->postComment() relies on actual user permissions.
     $comment = entity_create('comment', array('cid' => NULL, 'entity_id' => $this->node->id(), 'entity_type' => 'node', 'field_name' => 'comment', 'pid' => 0, 'uid' => 0, 'status' => CommentInterface::PUBLISHED, 'subject' => $this->randomMachineName(), 'hostname' => '127.0.0.1', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'comment_body' => array(LanguageInterface::LANGCODE_NOT_SPECIFIED => array($this->randomMachineName()))));
     $comment->save();
     $this->comment = $comment;
     // Change comment settings.
     $this->setCommentSettings('form_location', CommentItemInterface::FORM_BELOW, 'Set comment form location');
     $this->setCommentAnonymous(TRUE);
     $this->node->comment = CommentItemInterface::OPEN;
     $this->node->save();
     // Change user permissions.
     $perms = array('access comments' => 1, 'post comments' => 1, 'skip comment approval' => 1, 'edit own comments' => 1);
     user_role_change_permissions(DRUPAL_ANONYMOUS_RID, $perms);
     $nid = $this->node->id();
     // Assert basic link is output, actual functionality is unit-tested in
     // \Drupal\comment\Tests\CommentLinkBuilderTest.
     foreach (array('node', "node/{$nid}") as $path) {
         $this->drupalGet($path);
         // In teaser view, a link containing the comment count is always
         // expected.
         if ($path == 'node') {
             $this->assertLink(t('1 comment'));
         }
         $this->assertLink('Add new comment');
     }
     // Make sure we can hide node links.
     entity_get_display('node', $this->node->bundle(), 'default')->removeComponent('links')->save();
     $this->drupalGet($this->node->url());
     $this->assertNoLink('1 comment');
     $this->assertNoLink('Add new comment');
     // Visit the full node, make sure there are links for the comment.
     $this->drupalGet('node/' . $this->node->id());
     $this->assertText($comment->getSubject());
     $this->assertLink('Reply');
     // Make sure we can hide comment links.
     entity_get_display('comment', 'comment', 'default')->removeComponent('links')->save();
     $this->drupalGet('node/' . $this->node->id());
     $this->assertText($comment->getSubject());
     $this->assertNoLink('Reply');
 }
Пример #8
0
 /**
  * Tests that comments are deleted with the node.
  */
 function testNodeDeletion()
 {
     $this->drupalLogin($this->webUser);
     $comment = $this->postComment($this->node, $this->randomMachineName(), $this->randomMachineName());
     $this->assertTrue($comment->id(), 'The comment could be loaded.');
     $this->node->delete();
     $this->assertFalse(Comment::load($comment->id()), 'The comment could not be loaded after the node was deleted.');
     // Make sure the comment field storage and all its fields are deleted when
     // the node type is deleted.
     $this->assertNotNull(FieldStorageConfig::load('node.comment'), 'Comment field storage exists');
     $this->assertNotNull(FieldConfig::load('node.article.comment'), 'Comment field exists');
     // Delete the node type.
     entity_delete_multiple('node_type', array($this->node->bundle()));
     $this->assertNull(FieldStorageConfig::load('node.comment'), 'Comment field storage deleted');
     $this->assertNull(FieldConfig::load('node.article.comment'), 'Comment field deleted');
 }
Пример #9
0
 /**
  * Tests that comments are deleted with the node.
  */
 function testNodeDeletion()
 {
     $this->drupalLogin($this->web_user);
     $comment = $this->postComment($this->node, $this->randomName(), $this->randomName());
     $this->assertTrue($comment->id(), 'The comment could be loaded.');
     $this->node->delete();
     $this->assertFalse(Comment::load($comment->id()), 'The comment could not be loaded after the node was deleted.');
     // Make sure the comment field and all its instances are deleted when node
     // type is deleted.
     $this->assertNotNull(entity_load('field_storage_config', 'node.comment'), 'Comment field exists');
     $this->assertNotNull(entity_load('field_instance_config', 'node.article.comment'), 'Comment instance exists');
     // Delete the node type.
     entity_delete_multiple('node_type', array($this->node->bundle()));
     $this->assertNull(entity_load('field_storage_config', 'node.comment'), 'Comment field deleted');
     $this->assertNull(entity_load('field_instance_config', 'node.article.comment'), 'Comment instance deleted');
 }
Пример #10
0
 /**
  * Executes a test set for a defined entity type and user.
  *
  * @param string $entity_type
  *   The entity type to run the tests with.
  * @param \Drupal\user\UserInterface $user1
  *   The user to run the tests with.
  */
 protected function assertCRUD($entity_type, UserInterface $user1)
 {
     // Create some test entities.
     $entity = entity_create($entity_type, array('name' => 'test', 'user_id' => $user1->id()));
     $entity->save();
     $entity = entity_create($entity_type, array('name' => 'test2', 'user_id' => $user1->id()));
     $entity->save();
     $entity = entity_create($entity_type, array('name' => 'test', 'user_id' => NULL));
     $entity->save();
     $entities = array_values(entity_load_multiple_by_properties($entity_type, array('name' => 'test')));
     $this->assertEqual($entities[0]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
     $this->assertEqual($entities[1]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
     // Test loading a single entity.
     $loaded_entity = entity_load($entity_type, $entity->id());
     $this->assertEqual($loaded_entity->id(), $entity->id(), format_string('%entity_type: Loaded a single entity by id.', array('%entity_type' => $entity_type)));
     // Test deleting an entity.
     $entities = array_values(entity_load_multiple_by_properties($entity_type, array('name' => 'test2')));
     $entities[0]->delete();
     $entities = array_values(entity_load_multiple_by_properties($entity_type, array('name' => 'test2')));
     $this->assertEqual($entities, array(), format_string('%entity_type: Entity deleted.', array('%entity_type' => $entity_type)));
     // Test updating an entity.
     $entities = array_values(entity_load_multiple_by_properties($entity_type, array('name' => 'test')));
     $entities[0]->name->value = 'test3';
     $entities[0]->save();
     $entity = entity_load($entity_type, $entities[0]->id());
     $this->assertEqual($entity->name->value, 'test3', format_string('%entity_type: Entity updated.', array('%entity_type' => $entity_type)));
     // Try deleting multiple test entities by deleting all.
     $ids = array_keys(entity_load_multiple($entity_type));
     entity_delete_multiple($entity_type, $ids);
     $all = entity_load_multiple($entity_type);
     $this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', array('%entity_type' => $entity_type)));
     // Verify that all data got deleted.
     $definition = \Drupal::entityManager()->getDefinition($entity_type);
     $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $definition->getBaseTable() . '}')->fetchField(), 'Base table was emptied');
     if ($data_table = $definition->getDataTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $data_table . '}')->fetchField(), 'Data table was emptied');
     }
     if ($revision_table = $definition->getRevisionTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $revision_table . '}')->fetchField(), 'Data table was emptied');
     }
 }
 /**
  * Test dependency injected Language object against a new default language
  * object.
  *
  * @see \Drupal\Core\Language\Language
  */
 function testDependencyInjectedNewDefaultLanguage()
 {
     $default_language = ConfigurableLanguage::load(\Drupal::languageManager()->getDefaultLanguage()->getId());
     // Change the language default object to different values.
     ConfigurableLanguage::createFromLangcode('fr')->save();
     $this->config('system.site')->set('default_langcode', 'fr')->save();
     // The language system creates a Language object which contains the
     // same properties as the new default language object.
     $result = \Drupal::languageManager()->getCurrentLanguage();
     $this->assertIdentical($result->getId(), 'fr');
     // Delete the language to check that we fallback to the default.
     try {
         entity_delete_multiple('configurable_language', array('fr'));
         $this->fail('Expected DeleteDefaultLanguageException thrown.');
     } catch (DeleteDefaultLanguageException $e) {
         $this->pass('Expected DeleteDefaultLanguageException thrown.');
     }
     // Re-save the previous default language and the delete should work.
     $this->config('system.site')->set('default_langcode', $default_language->getId())->save();
     entity_delete_multiple('configurable_language', array('fr'));
     $result = \Drupal::languageManager()->getCurrentLanguage();
     $this->assertIdentical($result->getId(), $default_language->getId());
 }
Пример #12
0
 /**
  * {@inheritdoc}
  */
 public static function postDelete(EntityStorageInterface $storage, array $entities)
 {
     parent::postDelete($storage, $entities);
     // See if any of the term's children are about to be become orphans.
     $orphans = array();
     foreach (array_keys($entities) as $tid) {
         if ($children = taxonomy_term_load_children($tid)) {
             foreach ($children as $child) {
                 // If the term has multiple parents, we don't delete it.
                 $parents = taxonomy_term_load_parents($child->id());
                 if (empty($parents)) {
                     $orphans[] = $child->id();
                 }
             }
         }
     }
     // Delete term hierarchy information after looking up orphans but before
     // deleting them so that their children/parent information is consistent.
     $storage->deleteTermHierarchy(array_keys($entities));
     if (!empty($orphans)) {
         entity_delete_multiple('taxonomy_term', $orphans);
     }
 }
Пример #13
0
 /**
  * Tests that forum nodes can't be added without a parent.
  *
  * Verifies that forum nodes are not created without choosing "forum" from the
  * select list.
  */
 function testAddOrphanTopic()
 {
     // Must remove forum topics to test creating orphan topics.
     $vid = $this->config('forum.settings')->get('vocabulary');
     $tids = \Drupal::entityQuery('taxonomy_term')->condition('vid', $vid)->execute();
     entity_delete_multiple('taxonomy_term', $tids);
     // Create an orphan forum item.
     $edit = array();
     $edit['title[0][value]'] = $this->randomMachineName(10);
     $edit['body[0][value]'] = $this->randomMachineName(120);
     $this->drupalLogin($this->adminUser);
     $this->drupalPostForm('node/add/forum', $edit, t('Save'));
     $nid_count = db_query('SELECT COUNT(nid) FROM {node}')->fetchField();
     $this->assertEqual(0, $nid_count, 'A forum node was not created when missing a forum vocabulary.');
     // Reset the defaults for future tests.
     \Drupal::service('module_installer')->install(array('forum'));
 }
Пример #14
0
 /**
  * Executes a test set for a defined entity type and user.
  *
  * @param string $entity_type
  *   The entity type to run the tests with.
  * @param \Drupal\user\UserInterface $user1
  *   The user to run the tests with.
  */
 protected function assertCRUD($entity_type, UserInterface $user1)
 {
     // Create some test entities.
     $entity = $this->container->get('entity_type.manager')->getStorage($entity_type)->create(array('name' => 'test', 'user_id' => $user1->id()));
     $entity->save();
     $entity = $this->container->get('entity_type.manager')->getStorage($entity_type)->create(array('name' => 'test2', 'user_id' => $user1->id()));
     $entity->save();
     $entity = $this->container->get('entity_type.manager')->getStorage($entity_type)->create(array('name' => 'test', 'user_id' => NULL));
     $entity->save();
     /** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
     $storage = $this->container->get('entity_type.manager')->getStorage($entity_type);
     $entities = array_values($storage->loadByProperties(['name' => 'test']));
     $this->assertEqual($entities[0]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
     $this->assertEqual($entities[1]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
     // Test loading a single entity.
     $loaded_entity = $storage->load($entity->id());
     $this->assertEqual($loaded_entity->id(), $entity->id(), format_string('%entity_type: Loaded a single entity by id.', array('%entity_type' => $entity_type)));
     // Test deleting an entity.
     $entities = array_values($storage->loadByProperties(['name' => 'test2']));
     $entities[0]->delete();
     $entities = array_values($storage->loadByProperties(['name' => 'test2']));
     $this->assertEqual($entities, array(), format_string('%entity_type: Entity deleted.', array('%entity_type' => $entity_type)));
     // Test updating an entity.
     $entities = array_values($storage->loadByProperties(['name' => 'test']));
     $entities[0]->name->value = 'test3';
     $entities[0]->save();
     $entity = $storage->load($entities[0]->id());
     $this->assertEqual($entity->name->value, 'test3', format_string('%entity_type: Entity updated.', array('%entity_type' => $entity_type)));
     // Try deleting multiple test entities by deleting all.
     $ids = array_keys($storage->loadMultiple());
     entity_delete_multiple($entity_type, $ids);
     $all = $storage->loadMultiple();
     $this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', array('%entity_type' => $entity_type)));
     // Verify that all data got deleted.
     $definition = \Drupal::entityManager()->getDefinition($entity_type);
     $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $definition->getBaseTable() . '}')->fetchField(), 'Base table was emptied');
     if ($data_table = $definition->getDataTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $data_table . '}')->fetchField(), 'Data table was emptied');
     }
     if ($revision_table = $definition->getRevisionTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $revision_table . '}')->fetchField(), 'Data table was emptied');
     }
     // Test deleting a list of entities not indexed by entity id.
     $entities = array();
     $entity = entity_create($entity_type, array('name' => 'test', 'user_id' => $user1->id()));
     $entity->save();
     $entities['test'] = $entity;
     $entity = entity_create($entity_type, array('name' => 'test2', 'user_id' => $user1->id()));
     $entity->save();
     $entities['test2'] = $entity;
     $controller = \Drupal::entityManager()->getStorage($entity_type);
     $controller->delete($entities);
     // Verify that entities got deleted.
     $all = $storage->loadMultiple();
     $this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', array('%entity_type' => $entity_type)));
     // Verify that all data got deleted from the tables.
     $definition = \Drupal::entityManager()->getDefinition($entity_type);
     $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $definition->getBaseTable() . '}')->fetchField(), 'Base table was emptied');
     if ($data_table = $definition->getDataTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $data_table . '}')->fetchField(), 'Data table was emptied');
     }
     if ($revision_table = $definition->getRevisionTable()) {
         $this->assertEqual(0, db_query('SELECT COUNT(*) FROM {' . $revision_table . '}')->fetchField(), 'Data table was emptied');
     }
 }
Пример #15
0
 /**
  * Deletes custom generated menus
  */
 protected function deleteMenus()
 {
     if (\Drupal::moduleHandler()->moduleExists('menu_ui')) {
         foreach (menu_ui_get_menus(FALSE) as $menu => $menu_title) {
             if (strpos($menu, 'devel-') === 0) {
                 Menu::load($menu)->delete();
             }
         }
     }
     // Delete menu links generated by devel.
     $result = db_select('menu_link_content_data', 'm')->fields('m', array('id'))->condition('m.menu_name', 'devel', '<>')->condition('m.link__options', '%' . db_like('s:5:"devel";b:1') . '%', 'LIKE')->execute()->fetchCol();
     if ($result) {
         entity_delete_multiple('menu_link_content', $result);
     }
 }
Пример #16
0
 /**
  * {@inheritdoc}
  */
 public static function preDelete(EntityStorageInterface $storage, array $entities)
 {
     parent::preDelete($storage, $entities);
     // Only load terms without a parent, child terms will get deleted too.
     entity_delete_multiple('taxonomy_term', $storage->getToplevelTids(array_keys($entities)));
 }
Пример #17
0
 /**
  * Test that cache tags are properly set and bubbled up to the page cache.
  *
  * Verify that invalidation of these cache tags works:
  * - "block:<block ID>"
  * - "block_plugin:<block plugin ID>"
  */
 public function testBlockCacheTags()
 {
     // The page cache only works for anonymous users.
     $this->drupalLogout();
     // Enable page caching.
     $config = \Drupal::config('system.performance');
     $config->set('cache.page.use_internal', 1);
     $config->set('cache.page.max_age', 300);
     $config->save();
     // Place the "Powered by Drupal" block.
     $block = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered', 'cache' => array('max_age' => 315360000)));
     // Prime the page cache.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Verify a cache hit, but also the presence of the correct cache tags in
     // both the page and block caches.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $cid_parts = array(url('<front>', array('absolute' => TRUE)), 'html');
     $cid = sha1(implode(':', $cid_parts));
     $cache_entry = \Drupal::cache('render')->get($cid);
     $expected_cache_tags = array('theme:stark', 'theme_global_settings:1', 'block_view:1', 'block:powered', 'block_plugin:system_powered_by_block', 'rendered:1');
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:en:stark');
     $expected_cache_tags = array('block_view:1', 'block:powered', 'theme:stark', 'block_plugin:system_powered_by_block', 'rendered:1');
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     // The "Powered by Drupal" block is modified; verify a cache miss.
     $block->set('region', 'content');
     $block->save();
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Now we should have a cache hit again.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     // Place the "Powered by Drupal" block another time; verify a cache miss.
     $block_2 = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered-2', 'cache' => array('max_age' => 315360000)));
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Verify a cache hit, but also the presence of the correct cache tags.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $cid_parts = array(url('<front>', array('absolute' => TRUE)), 'html');
     $cid = sha1(implode(':', $cid_parts));
     $cache_entry = \Drupal::cache('render')->get($cid);
     $expected_cache_tags = array('theme:stark', 'theme_global_settings:1', 'block_view:1', 'block:powered-2', 'block:powered', 'block_plugin:system_powered_by_block', 'rendered:1');
     $this->assertEqual($cache_entry->tags, $expected_cache_tags);
     $expected_cache_tags = array('block_view:1', 'block:powered', 'theme:stark', 'block_plugin:system_powered_by_block', 'rendered:1');
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:en:stark');
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     $expected_cache_tags = array('block_view:1', 'block:powered-2', 'theme:stark', 'block_plugin:system_powered_by_block', 'rendered:1');
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:en:stark');
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     // The plugin providing the "Powered by Drupal" block is modified; verify a
     // cache miss.
     Cache::invalidateTags(array('block_plugin:system_powered_by_block'));
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Now we should have a cache hit again.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     // Delete the "Powered by Drupal" blocks; verify a cache miss.
     entity_delete_multiple('block', array('powered', 'powered-2'));
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
 }
Пример #18
0
 /**
  * Test automatic reparenting of menu links.
  */
 function testMenuLinkReparenting($module = 'menu_test')
 {
     // Check the initial hierarchy.
     $links = $this->createLinkHierarchy($module);
     $expected_hierarchy = array('parent' => FALSE, 'child-1' => 'parent', 'child-1-1' => 'child-1', 'child-1-2' => 'child-1', 'child-2' => 'parent');
     $this->assertMenuLinkParents($links, $expected_hierarchy);
     // Start over, and move child-1 under child-2, and check that all the
     // childs of child-1 have been moved too.
     $links = $this->createLinkHierarchy($module);
     $links['child-1']['plid'] = $links['child-2']['mlid'];
     menu_link_save($links['child-1']);
     $expected_hierarchy = array('parent' => FALSE, 'child-1' => 'child-2', 'child-1-1' => 'child-1', 'child-1-2' => 'child-1', 'child-2' => 'parent');
     $this->assertMenuLinkParents($links, $expected_hierarchy);
     // Start over, and delete child-1, and check that the children of child-1
     // have been reassigned to the parent. menu_link_delete() will cowardly
     // refuse to delete a menu link defined by the system module, so skip the
     // test in that case.
     if ($module != 'system') {
         $links = $this->createLinkHierarchy($module);
         menu_link_delete($links['child-1']['mlid']);
         $expected_hierarchy = array('parent' => FALSE, 'child-1-1' => 'parent', 'child-1-2' => 'parent', 'child-2' => 'parent');
         $this->assertMenuLinkParents($links, $expected_hierarchy);
     }
     // Start over, forcefully delete child-1 from the database, simulating a
     // database crash. Check that the children of child-1 have been reassigned
     // to the parent, going up on the old path hierarchy stored in each of the
     // links.
     $links = $this->createLinkHierarchy($module);
     // Don't do that at home.
     entity_delete_multiple('menu_link', array($links['child-1']['mlid']));
     $expected_hierarchy = array('parent' => FALSE, 'child-1-1' => 'parent', 'child-1-2' => 'parent', 'child-2' => 'parent');
     $this->assertMenuLinkParents($links, $expected_hierarchy);
     // Start over, forcefully delete the parent from the database, simulating a
     // database crash. Check that the children of parent are now top-level.
     $links = $this->createLinkHierarchy($module);
     // Don't do that at home.
     db_delete('menu_links')->condition('mlid', $links['parent']['mlid'])->execute();
     $expected_hierarchy = array('child-1-1' => 'child-1', 'child-1-2' => 'child-1', 'child-2' => FALSE);
     $this->assertMenuLinkParents($links, $expected_hierarchy);
 }
Пример #19
0
 /**
  * Tests the access for deleting top-level book nodes.
  */
 function testBookDelete()
 {
     $nodes = $this->createBook();
     $this->drupalLogin($this->admin_user);
     $edit = array();
     // Test access to delete top-level and child book nodes.
     $this->drupalGet('node/' . $this->book->id() . '/outline/remove');
     $this->assertResponse('403', 'Deleting top-level book node properly forbidden.');
     $this->drupalPostForm('node/' . $nodes[4]->id() . '/outline/remove', $edit, t('Remove'));
     $node4 = node_load($nodes[4]->id(), TRUE);
     $this->assertTrue(empty($node4->book), 'Deleting child book node properly allowed.');
     // Delete all child book nodes and retest top-level node deletion.
     foreach ($nodes as $node) {
         $nids[] = $node->id();
     }
     entity_delete_multiple('node', $nids);
     $this->drupalPostForm('node/' . $this->book->id() . '/outline/remove', $edit, t('Remove'));
     $node = node_load($this->book->id(), TRUE);
     $this->assertTrue(empty($node->book), 'Deleting childless top-level book node properly allowed.');
 }
Пример #20
0
 /**
  * Tests that a fixed set of modules can be installed and uninstalled.
  */
 public function testInstallUninstall()
 {
     // Get a list of modules to enable.
     $all_modules = system_rebuild_module_data();
     $all_modules = array_filter($all_modules, function ($module) {
         // Filter contrib, hidden, already enabled modules and modules in the
         // Testing package.
         if ($module->origin !== 'core' || !empty($module->info['hidden']) || $module->status == TRUE || $module->info['package'] == 'Testing') {
             return FALSE;
         }
         return TRUE;
     });
     // Install every module possible.
     \Drupal::service('module_installer')->install(array_keys($all_modules));
     $this->assertModules(array_keys($all_modules), TRUE);
     foreach ($all_modules as $module => $info) {
         $this->assertModuleConfig($module);
         $this->assertModuleTablesExist($module);
     }
     // Export active config to sync.
     $this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
     system_list_reset();
     $this->resetAll();
     // Delete every field on the site so all modules can be uninstalled. For
     // example, if a comment field exists then module becomes required and can
     // not be uninstalled.
     $field_storages = \Drupal::entityManager()->getStorage('field_storage_config')->loadMultiple();
     \Drupal::entityManager()->getStorage('field_storage_config')->delete($field_storages);
     // Purge the data.
     field_purge_batch(1000);
     // Delete all terms.
     $terms = Term::loadMultiple();
     entity_delete_multiple('taxonomy_term', array_keys($terms));
     // Delete all filter formats.
     $filters = FilterFormat::loadMultiple();
     entity_delete_multiple('filter_format', array_keys($filters));
     // Delete any shortcuts so the shortcut module can be uninstalled.
     $shortcuts = Shortcut::loadMultiple();
     entity_delete_multiple('shortcut', array_keys($shortcuts));
     system_list_reset();
     $all_modules = system_rebuild_module_data();
     // Ensure that only core required modules and the install profile can not be uninstalled.
     $validation_reasons = \Drupal::service('module_installer')->validateUninstall(array_keys($all_modules));
     $this->assertEqual(['standard', 'system', 'user'], array_keys($validation_reasons));
     $modules_to_uninstall = array_filter($all_modules, function ($module) use($validation_reasons) {
         // Filter required and not enabled modules.
         if (!empty($module->info['required']) || $module->status == FALSE) {
             return FALSE;
         }
         return TRUE;
     });
     // Can not uninstall config and use admin/config/development/configuration!
     unset($modules_to_uninstall['config']);
     $this->assertTrue(isset($modules_to_uninstall['comment']), 'The comment module will be disabled');
     $this->assertTrue(isset($modules_to_uninstall['file']), 'The File module will be disabled');
     $this->assertTrue(isset($modules_to_uninstall['editor']), 'The Editor module will be disabled');
     // Uninstall all modules that can be uninstalled.
     \Drupal::service('module_installer')->uninstall(array_keys($modules_to_uninstall));
     $this->assertModules(array_keys($modules_to_uninstall), FALSE);
     foreach ($modules_to_uninstall as $module => $info) {
         $this->assertNoModuleConfig($module);
         $this->assertModuleTablesDoNotExist($module);
     }
     // Import the configuration thereby re-installing all the modules.
     $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all'));
     // Modules have been installed that have services.
     $this->rebuildContainer();
     // Check that there are no errors.
     $this->assertIdentical($this->configImporter()->getErrors(), array());
     // Check that all modules that were uninstalled are now reinstalled.
     $this->assertModules(array_keys($modules_to_uninstall), TRUE);
     foreach ($modules_to_uninstall as $module => $info) {
         $this->assertModuleConfig($module);
         $this->assertModuleTablesExist($module);
     }
     // Ensure that we have no configuration changes to import.
     $storage_comparer = new StorageComparer($this->container->get('config.storage.sync'), $this->container->get('config.storage'), $this->container->get('config.manager'));
     $this->assertIdentical($storage_comparer->createChangelist()->getChangelist(), $storage_comparer->getEmptyChangelist());
     // Now we have all configuration imported, test all of them for schema
     // conformance. Ensures all imported default configuration is valid when
     // all modules are enabled.
     $names = $this->container->get('config.storage')->listAll();
     /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
     $typed_config = $this->container->get('config.typed');
     foreach ($names as $name) {
         $config = $this->config($name);
         $this->assertConfigSchema($typed_config, $name, $config->get());
     }
 }
 /**
  * Removes all cache purge rules.
  *
  * @AfterScenario
  */
 public function purgeAllCacheRules()
 {
     if (module_exists('nexteuropa_varnish')) {
         $rules = entity_load('nexteuropa_varnish_cache_purge_rule');
         $rule_ids = array_keys($rules);
         entity_delete_multiple('nexteuropa_varnish_cache_purge_rule', $rule_ids);
     }
 }
 /**
  * @AfterScenario
  */
 public function cleanDB($event)
 {
     if ($this->entities) {
         foreach ($this->entities as $type => $ids) {
             entity_delete_multiple($type, $ids);
         }
     }
 }
Пример #23
0
 /**
  * Test that cache tags are properly set and bubbled up to the page cache.
  *
  * Verify that invalidation of these cache tags works:
  * - "block:<block ID>"
  * - "block_plugin:<block plugin ID>"
  */
 public function testBlockCacheTags()
 {
     // The page cache only works for anonymous users.
     $this->drupalLogout();
     // Enable page caching.
     $config = $this->config('system.performance');
     $config->set('cache.page.max_age', 300);
     $config->save();
     // Place the "Powered by Drupal" block.
     $block = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered'));
     // Prime the page cache.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Verify a cache hit, but also the presence of the correct cache tags in
     // both the page and block caches.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $cid_parts = array(\Drupal::url('<front>', array(), array('absolute' => TRUE)), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     $expected_cache_tags = array('config:block_list', 'block_view', 'config:block.block.powered', 'config:user.role.anonymous', 'rendered');
     sort($expected_cache_tags);
     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
     $expected_cache_tags = array('block_view', 'config:block.block.powered', 'rendered');
     sort($expected_cache_tags);
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     // The "Powered by Drupal" block is modified; verify a cache miss.
     $block->setRegion('content');
     $block->save();
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Now we should have a cache hit again.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     // Place the "Powered by Drupal" block another time; verify a cache miss.
     $block_2 = $this->drupalPlaceBlock('system_powered_by_block', array('id' => 'powered-2'));
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
     // Verify a cache hit, but also the presence of the correct cache tags.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     $cid_parts = array(\Drupal::url('<front>', array(), array('absolute' => TRUE)), 'html');
     $cid = implode(':', $cid_parts);
     $cache_entry = \Drupal::cache('render')->get($cid);
     $expected_cache_tags = array('config:block_list', 'block_view', 'config:block.block.powered', 'config:block.block.powered-2', 'config:user.role.anonymous', 'rendered');
     sort($expected_cache_tags);
     $this->assertEqual($cache_entry->tags, $expected_cache_tags);
     $expected_cache_tags = array('block_view', 'config:block.block.powered', 'rendered');
     sort($expected_cache_tags);
     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered:' . implode(':', $keys));
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     $expected_cache_tags = array('block_view', 'config:block.block.powered-2', 'rendered');
     sort($expected_cache_tags);
     $keys = \Drupal::service('cache_contexts_manager')->convertTokensToKeys(['languages:language_interface', 'theme', 'user.permissions'])->getKeys();
     $cache_entry = \Drupal::cache('render')->get('entity_view:block:powered-2:' . implode(':', $keys));
     $this->assertIdentical($cache_entry->tags, $expected_cache_tags);
     // Now we should have a cache hit again.
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT');
     // Delete the "Powered by Drupal" blocks; verify a cache miss.
     entity_delete_multiple('block', array('powered', 'powered-2'));
     $this->drupalGet('<front>');
     $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS');
 }
Пример #24
0
 /**
  * {@inheritdoc}
  */
 public static function postDelete(EntityStorageInterface $storage, array $entities)
 {
     parent::postDelete($storage, $entities);
     // Since we are deleting one or multiple job items here we also need to
     // delete the attached messages.
     $mids = \Drupal::entityQuery('tmgmt_message')->condition('tjiid', array_keys($entities), 'IN')->execute();
     if (!empty($mids)) {
         entity_delete_multiple('tmgmt_message', $mids);
     }
     $trids = \Drupal::entityQuery('tmgmt_remote')->condition('tjiid', array_keys($entities), 'IN')->execute();
     if (!empty($trids)) {
         entity_delete_multiple('tmgmt_remote', $trids);
     }
 }
Пример #25
0
 /**
  * Run after every scenario.
  *
  * @AfterScenario @api
  */
 public function cleanupEntities($event)
 {
     // Identifiers for entities are tracked from the "I intend to create" step.
     // @see iIntendToCreateATitled()
     if (empty($this->created)) {
         return;
     }
     $properties = array('node' => 'title', 'taxonomy_term' => 'name', 'user' => 'mail');
     foreach ($this->created as $entity_type => $identifiers) {
         $query = new EntityFieldQuery();
         $result = $query->entityCondition('entity_type', $entity_type)->propertyCondition($properties[$entity_type], $identifiers, 'IN')->execute();
         if ($result) {
             $entity_ids = array_keys($result[$entity_type]);
             entity_delete_multiple($entity_type, $entity_ids);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function delete($ids, $context)
 {
     entity_delete_multiple($this->entityTypeId(), $ids);
 }
 protected function contentKill($values)
 {
     $results = db_select('node', 'n')->fields('n', array('nid'))->condition('type', $values['node_types'], 'IN')->execute();
     foreach ($results as $result) {
         $nids[] = $result->nid;
     }
     if (!empty($nids)) {
         entity_delete_multiple('node', $nids);
         $this->setMessage($this->t('Deleted %count nodes.', array('%count' => count($nids))));
     }
 }
Пример #28
0
 /**
  * Tests the access for deleting top-level book nodes.
  */
 function testBookDelete()
 {
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     $nodes = $this->createBook();
     $this->drupalLogin($this->adminUser);
     $edit = array();
     // Test access to delete top-level and child book nodes.
     $this->drupalGet('node/' . $this->book->id() . '/outline/remove');
     $this->assertResponse('403', 'Deleting top-level book node properly forbidden.');
     $this->drupalPostForm('node/' . $nodes[4]->id() . '/outline/remove', $edit, t('Remove'));
     $node_storage->resetCache(array($nodes[4]->id()));
     $node4 = $node_storage->load($nodes[4]->id());
     $this->assertTrue(empty($node4->book), 'Deleting child book node properly allowed.');
     // Delete all child book nodes and retest top-level node deletion.
     foreach ($nodes as $node) {
         $nids[] = $node->id();
     }
     entity_delete_multiple('node', $nids);
     $this->drupalPostForm('node/' . $this->book->id() . '/outline/remove', $edit, t('Remove'));
     $node_storage->resetCache(array($this->book->id()));
     $node = $node_storage->load($this->book->id());
     $this->assertTrue(empty($node->book), 'Deleting childless top-level book node properly allowed.');
     // Tests directly deleting a book parent.
     $nodes = $this->createBook();
     $this->drupalLogin($this->adminUser);
     $this->drupalGet($this->book->urlInfo('delete-form'));
     $this->assertRaw(t('%title is part of a book outline, and has associated child pages. If you proceed with deletion, the child pages will be relocated automatically.', ['%title' => $this->book->label()]));
     // Delete parent, and visit a child page.
     $this->drupalPostForm($this->book->urlInfo('delete-form'), [], t('Delete'));
     $this->drupalGet($nodes[0]->urlInfo());
     $this->assertResponse(200);
     $this->assertText($nodes[0]->label());
     // The book parents should be updated.
     $node_storage = \Drupal::entityTypeManager()->getStorage('node');
     $node_storage->resetCache();
     $child = $node_storage->load($nodes[0]->id());
     $this->assertEqual($child->id(), $child->book['bid'], 'Child node book ID updated when parent is deleted.');
     // 3rd-level children should now be 2nd-level.
     $second = $node_storage->load($nodes[1]->id());
     $this->assertEqual($child->id(), $second->book['bid'], '3rd-level child node is now second level when top-level node is deleted.');
 }
Пример #29
0
 /**
  * Tests deleting a shortcut link.
  */
 public function testShortcutLinkDelete()
 {
     $set = $this->set;
     $shortcuts = $set->getShortcuts();
     $shortcut = reset($shortcuts);
     $this->drupalPostForm('admin/config/user-interface/shortcut/link/' . $shortcut->id() . '/delete', array(), 'Delete');
     $saved_set = ShortcutSet::load($set->id());
     $ids = $this->getShortcutInformation($saved_set, 'id');
     $this->assertFalse(in_array($shortcut->id(), $ids), 'Successfully deleted a shortcut.');
     // Delete all the remaining shortcut links.
     entity_delete_multiple('shortcut', array_filter($ids));
     // Get the front page to check that no exceptions occur.
     $this->drupalGet('');
 }
Пример #30
0
 /**
  * {@inheritdoc}
  */
 public static function postDelete(EntityStorageInterface $storage, array $entities)
 {
     parent::postDelete($storage, $entities);
     $child_cids = $storage->getChildCids($entities);
     entity_delete_multiple('comment', $child_cids);
     foreach ($entities as $id => $entity) {
         \Drupal::service('comment.statistics')->update($entity);
     }
 }