/**
  * Asserts that field schema data to be purged is found.
  *
  * @param bool $found
  *   Whether field schema data is expected to be found or not.
  * @param string $message
  *   The assert message.
  *
  * @return bool
  *   TRUE if the assertion succeeded, FALSE otherwise.
  */
 protected function assertFieldSchemaData($found, $message)
 {
     $query = \Drupal::database()->select('key_value', 'kv')->fields('kv');
     $query->condition('kv.collection', 'entity.storage_schema.sql')->condition('kv.name', 'block_content.field_schema_data.%', 'LIKE');
     $items = $query->execute()->fetchAll();
     return $this->assertEqual((bool) $items, $found, $message);
 }
 /**
  * Ensures that the system_update_8001() runs as expected.
  */
 public function testUpdate()
 {
     $this->runUpdates();
     // Ensure that some fields got dropped.
     $database = \Drupal::database();
     $schema = $database->schema();
     if (!$schema->tableExists('menu_tree')) {
         return;
     }
     $this->assertFalse($schema->fieldExists('menu_tree', 'title_arguments'));
     $this->assertFalse($schema->fieldExists('menu_tree', 'title_contexts'));
     // Ensure that all titles and description values can be unserialized.
     $select = $database->select('menu_tree');
     $result = $select->fields('menu_tree', ['id', 'title', 'description'])->execute()->fetchAllAssoc('id');
     // The test coverage relies upon the fact that unserialize() would emit a
     // warning if the value is not a valid serialized value.
     foreach ($result as $link) {
         $title = unserialize($link->title);
         $description = unserialize($link->description);
         // Verify that all the links from system module have a been updated with
         // a TranslationWrapper as title and description due to the rebuild.
         if (strpos($link->id, 'system.') === 0) {
             $this->assertTrue($title instanceof TranslationWrapper, get_class($title));
             if ($description) {
                 $this->assertTrue($description instanceof TranslationWrapper, get_class($description));
             }
         }
     }
 }
Example #3
0
/**
 * Perform a single batch operation.
 *
 * Callback for batch_set().
 *
 * @param $MULTIPLE_PARAMS
 *   Additional parameters specific to the batch. These are specified in the
 *   array passed to batch_set().
 * @param array|\ArrayAccess $context.
 *   The batch context array, passed by reference. This contains the following
 *   properties:
 *   - 'finished': A float number between 0 and 1 informing the processing
 *     engine of the completion level for the operation. 1 (or no value
 *     explicitly set) means the operation is finished: the operation will not
 *     be called again, and execution passes to the next operation or the
 *     callback_batch_finished() implementation. Any other value causes this
 *     operation to be called again; however it should be noted that the value
 *     set here does not persist between executions of this callback: each time
 *     it is set to 1 by default by the batch system.
 *   - 'sandbox': This may be used by operations to persist data between
 *     successive calls to the current operation. Any values set in
 *     $context['sandbox'] will be there the next time this function is called
 *     for the current operation. For example, an operation may wish to store a
 *     pointer in a file or an offset for a large query. The 'sandbox' array key
 *     is not initially set when this callback is first called, which makes it
 *     useful for determining whether it is the first call of the callback or
 *     not:
 *     @code
 *       if (empty($context['sandbox'])) {
 *         // Perform set-up steps here.
 *       }
 *     @endcode
 *     The values in the sandbox are stored and updated in the database between
 *     http requests until the batch finishes processing. This avoids problems
 *     if the user navigates away from the page before the batch finishes.
 *   - 'message': A text message displayed in the progress page.
 *   - 'results': The array of results gathered so far by the batch processing.
 *     This array is highly useful for passing data between operations. After
 *     all operations have finished, this is passed to callback_batch_finished()
 *     where results may be referenced to display information to the end-user,
 *     such as how many total items were processed.
 *   It is discouraged to typehint this parameter as an array, to allow an
 *   object implement \ArrayAccess to be passed.
 */
function callback_batch_operation($MULTIPLE_PARAMS, &$context)
{
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $database = \Drupal::database();
    if (!isset($context['sandbox']['progress'])) {
        $context['sandbox']['progress'] = 0;
        $context['sandbox']['current_node'] = 0;
        $context['sandbox']['max'] = $database->query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField();
    }
    // For this example, we decide that we can safely process
    // 5 nodes at a time without a timeout.
    $limit = 5;
    // With each pass through the callback, retrieve the next group of nids.
    $result = $database->queryRange("SELECT nid FROM {node} WHERE nid > :nid ORDER BY nid ASC", 0, $limit, [':nid' => $context['sandbox']['current_node']]);
    foreach ($result as $row) {
        // Here we actually perform our processing on the current node.
        $node_storage->resetCache(array($row['nid']));
        $node = $node_storage->load($row['nid']);
        $node->value1 = $options1;
        $node->value2 = $options2;
        node_save($node);
        // Store some result for post-processing in the finished callback.
        $context['results'][] = $node->title;
        // Update our progress information.
        $context['sandbox']['progress']++;
        $context['sandbox']['current_node'] = $node->nid;
        $context['message'] = t('Now processing %node', array('%node' => $node->title));
    }
    // Inform the batch engine that we are not finished,
    // and provide an estimation of the completion level we reached.
    if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
        $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
    }
}
  /**
   * Tests the Drupal 6 menu to Drupal 8 migration.
   */
  public function testMenu() {
    $navigation_menu = Menu::load('navigation');
    $this->assertSame('navigation', $navigation_menu->id());
    $this->assertSame('Navigation', $navigation_menu->label());
    $expected = <<<EOT
The navigation menu is provided by Drupal and is the main interactive menu for any site. It is usually the only menu that contains personalized links for authenticated users, and is often not even visible to anonymous users.
EOT;
    $this->assertSame($expected, $navigation_menu->getDescription());

    // Test that we can re-import using the ConfigEntityBase destination.
    Database::getConnection('default', 'migrate')
      ->update('menu_custom')
      ->fields(array('title' => 'Home Navigation'))
      ->condition('menu_name', 'navigation')
      ->execute();

    $migration = $this->getMigration('d6_menu');
    \Drupal::database()
        ->truncate($migration->getIdMap()->mapTableName())
        ->execute();
    $this->executeMigration($migration);

    $navigation_menu = Menu::load('navigation');
    $this->assertSame('Home Navigation', $navigation_menu->label());
  }
 /**
  * Tests that the database was properly loaded.
  */
 public function testDatabaseLoaded()
 {
     foreach (['user', 'node', 'system', 'update_test_schema'] as $module) {
         $this->assertEqual(drupal_get_installed_schema_version($module), 8000, SafeMarkup::format('Module @module schema is 8000', ['@module' => $module]));
     }
     // Ensure that all {router} entries can be unserialized. If they cannot be
     // unserialized a notice will be thrown by PHP.
     $result = \Drupal::database()->query("SELECT name, route from {router}")->fetchAllKeyed(0, 1);
     // For the purpose of fetching the notices and displaying more helpful error
     // messages, let's override the error handler temporarily.
     set_error_handler(function ($severity, $message, $filename, $lineno) {
         throw new \ErrorException($message, 0, $severity, $filename, $lineno);
     });
     foreach ($result as $route_name => $route) {
         try {
             unserialize($route);
         } catch (\Exception $e) {
             $this->fail(sprintf('Error "%s" while unserializing route %s', $e->getMessage(), Html::escape($route_name)));
         }
     }
     restore_error_handler();
     // Before accessing the site we need to run updates first or the site might
     // be broken.
     $this->runUpdates();
     $this->assertEqual(\Drupal::config('system.site')->get('name'), 'Site-Install');
     $this->drupalGet('<front>');
     $this->assertText('Site-Install');
     // Ensure that the database tasks have been run during set up. Neither MySQL
     // nor SQLite make changes that are testable.
     $database = $this->container->get('database');
     if ($database->driver() == 'pgsql') {
         $this->assertEqual('on', $database->query("SHOW standard_conforming_strings")->fetchField());
         $this->assertEqual('escape', $database->query("SHOW bytea_output")->fetchField());
     }
 }
Example #6
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->executeMigrations(['d6_node:*']);
     // This is required for the second import below.
     \Drupal::database()->truncate(Migration::load('d6_node__story')->getIdMap()->mapTableName())->execute();
 }
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     $this->database = \Drupal::database();
     $this->paymentMethodManager = \Drupal::service('plugin.manager.payment.method');
     $this->paymentStatusManager = \Drupal::service('plugin.manager.payment.status');
     $queue_id = $this->randomMachineName();
     $this->queue = new DatabaseQueue($queue_id, $this->database, \Drupal::service('payment.event_dispatcher'), $this->paymentStatusManager);
 }
 /**
  * Verify that element is a valid username.
  */
 public static function validUser($element, FormStateInterface $form_state)
 {
     if ($element['#value'] !== '') {
         $count = \Drupal::database()->select('users_field_data', 'u')->condition('name', $element['#value'])->countQuery()->execute()->fetchField();
         if (intval($count) != 1) {
             $form_state->setError($element, t('The @field field should be a valid username.', array('@field' => $element['#title'])));
         }
     }
 }
 /**
  * Builds and returns the renderable array for this block plugin.
  *
  * If a block should not be rendered because it has no content, then this
  * method must also ensure to return no content: it must then only return an
  * empty array, or an empty array with #cache set (with cacheability metadata
  * indicating the circumstances for it being empty).
  *
  * @return array
  *   A renderable array representing the content of the block.
  *
  * @see \Drupal\block\BlockViewBuilder
  */
 public function build()
 {
     /**
      * aparently the explanation for this Drupal::database, call is to get around the fact that
      * db_query is deprecated:
      *      $herpderp = db_query()
      * the reason for the deprecation follows:
      * @deprecated as of Drupal 8.0.x, will be removed in Drupal 9.0.0. Instead, get
      *   a database connection injected into your service from the container and
      *   call query() on it. E.g.
      *   $injected_database->query($query, $args, $options);
      *
      *
      *
      * Okay, so i asked the question, http://drupal.stackexchange.com/questions/184042/regarding-term-clarification-in-the-database-api
      *
      * And further, the following mysql queries are "kind of wrong", should look at the drupal database docs, aparently
      * if we do write custom mysql we have to wrap table tables in angle brackets {} so that other things
      * can override them. And i think writeing mysql syntax ruins the whole "multiple databases feature" of drupal, so we should obviously
      * be useing their ORM/query language to do this sort of stuff anyway.
      */
     $connection = \Drupal::database();
     //list of the most recent articles
     $result = $connection->query("SELECT n.title, u.uid, n.created FROM node_field_data n, users u WHERE u.uid = n.uid AND n.type = :type ORDER BY n.created DESC LIMIT 5", array('type' => 'article'));
     $content = '<ul>';
     if ($result) {
         while ($row = $result->fetchAssoc()) {
             $content .= '<li>' . $row['title'] . '</li>';
         }
         $content .= '</ul>';
     } else {
         $content .= '<li>No blog posts to show </li> </ul>';
     }
     //single field queries
     $fetchSingleField = $connection->query("SELECT n.nid, n.title FROM node_field_data n WHERE n.title ='article3'")->fetchField();
     $singleFieldTitle = 'no single field result';
     if ($fetchSingleField) {
         $singleFieldTitle = '<div>Single field nid: ' . $fetchSingleField['title'] . '</div></br>';
     }
     //Distinct all users what have contributed to the website
     $distinctUsers = $connection->query("SELECT DISTINCT(uid) FROM node_field_data");
     $distinctUsersContent = '<div> All of the users that have contributed to the page:</div><ul> ';
     if ($distinctUsers) {
         while ($distinctUser = $distinctUsers->fetchAssoc()) {
             $distinctUsersContent .= '<li> User id:' . $distinctUser['uid'] . '</li>';
         }
     } else {
         $distinctUsersContent .= '<li>There was no user content to show</li>';
     }
     $distinctUsersContent .= '</ul></br>';
     //Other surgestions is to query for a specific users blog posts in a specific language etc.
     return array('#markup' => '
             <div>' . $singleFieldTitle . $content . $distinctUsersContent . '</div>');
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     // Each node type is imported separately. In this test, we're asserting
     // on story and test_planet nodes.
     $this->executeMigration('d6_node__test_planet');
     $this->executeMigration('d6_node__story');
     // This is required for the second import below.
     \Drupal::database()->truncate(Migration::load('d6_node__story')->getIdMap()->mapTableName())->execute();
     $this->standalone = TRUE;
 }
 /**
  * {@inheritdoc}
  */
 public function import(Row $row, array $old_destination_id_values = array())
 {
     $destination = $row->getDestination();
     $keys = array();
     foreach (array_keys($this->ids) as $id) {
         $keys[$id] = $destination[$id];
         unset($destination[$id]);
     }
     \Drupal::database()->merge($this->table_name)->keys($keys)->fields($destination)->execute();
     $return = array_map(function ($key) use($row) {
         return $row->getDestinationProperty($key);
     }, $keys);
     return $return;
 }
 /**
  * Tests the Drupal 6 date formats to Drupal 8 migration.
  */
 public function testDateFormats()
 {
     $short_date_format = DateFormat::load('short');
     $this->assertIdentical('\\S\\H\\O\\R\\T m/d/Y - H:i', $short_date_format->getPattern());
     $medium_date_format = DateFormat::load('medium');
     $this->assertIdentical('\\M\\E\\D\\I\\U\\M D, m/d/Y - H:i', $medium_date_format->getPattern());
     $long_date_format = DateFormat::load('long');
     $this->assertIdentical('\\L\\O\\N\\G l, F j, Y - H:i', $long_date_format->getPattern());
     // Test that we can re-import using the EntityDateFormat destination.
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('\\S\\H\\O\\R\\T d/m/Y - H:i')))->condition('name', 'date_format_short')->execute();
     $migration = $this->getMigration('d6_date_formats');
     \Drupal::database()->truncate($migration->getIdMap()->mapTableName())->execute();
     $this->executeMigration($migration);
     $short_date_format = DateFormat::load('short');
     $this->assertIdentical('\\S\\H\\O\\R\\T d/m/Y - H:i', $short_date_format->getPattern());
 }
Example #13
0
 /**
  * Execute the migration a second time.
  *
  * @param array $new_row
  *   An optional row to be inserted into the id map.
  *
  * @return string
  *   The new title in the source for vid 3.
  */
 protected function rerunMigration($new_row = [])
 {
     $title = $this->randomString();
     $migration = Migration::load('d6_node__story');
     $source_connection = Database::getConnection('default', 'migrate');
     $source_connection->update('node_revisions')->fields(array('title' => $title, 'format' => 2))->condition('vid', 3)->execute();
     $table_name = $migration->getIdMap()->mapTableName();
     $default_connection = \Drupal::database();
     $default_connection->truncate($table_name)->execute();
     if ($new_row) {
         $hash = $migration->getIdMap()->getSourceIDsHash(['nid' => $new_row['sourceid1']]);
         $new_row['source_ids_hash'] = $hash;
         $default_connection->insert($table_name)->fields($new_row)->execute();
     }
     $this->executeMigration($migration);
     return $title;
 }
Example #14
0
 /**
  * Tests the Drupal 6 files to Drupal 8 migration.
  */
 public function testFiles()
 {
     $this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
     $this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
     $this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
     $this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
     // Test that we can re-import and also test with file_directory_path set.
     \Drupal::database()->truncate($this->getMigration('d6_file')->getIdMap()->mapTableName())->execute();
     // Update the file_directory_path.
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize(file_directory_temp())))->condition('name', 'file_directory_temp')->execute();
     $this->executeMigration('d6_file');
     $file = File::load(2);
     $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
     // File 7, created in static::migrateDumpAlter(), shares a path with
     // file 5, which means it should be skipped entirely.
     $this->assertNull(File::load(7));
 }
Example #15
0
 /**
  * Test that updates are properly run.
  */
 public function testUpdateHookN()
 {
     // Increment the schema version.
     \Drupal::state()->set('update_test_schema_version', 8001);
     $this->runUpdates();
     $select = \Drupal::database()->select('watchdog');
     $select->orderBy('wid', 'DESC');
     $select->range(0, 5);
     $select->fields('watchdog', ['message']);
     $container_cannot_be_saved_messages = array_filter(iterator_to_array($select->execute()), function ($row) {
         return strpos($row->message, 'Container cannot be saved to cache.') !== FALSE;
     });
     $this->assertEqual([], $container_cannot_be_saved_messages);
     // Ensure schema has changed.
     $this->assertEqual(drupal_get_installed_schema_version('update_test_schema', TRUE), 8001);
     // Ensure the index was added for column a.
     $this->assertTrue(db_index_exists('update_test_schema_table', 'test'), 'Version 8001 of the update_test_schema module is installed.');
 }
Example #16
0
 /**
  * Tests various operations via the Facets' admin UI.
  */
 public function testFramework()
 {
     $facet_id = 'test_facet_name';
     $facet_name = 'Test Facet Name';
     // Check if the overview is empty.
     $this->checkEmptyOverview();
     // Add a new facet and edit it.
     $this->addFacet($facet_id, $facet_name);
     // Create and place a block for "Test Facet name" facet.
     $this->blocks[$facet_id] = $this->createBlock($facet_id);
     // Verify that the facet results are correct.
     $this->drupalGet('search/node', ['query' => ['keys' => 'test']]);
     $this->assertLink('page');
     $this->assertLink('article');
     // Verify that facet blocks appear as expected.
     $this->assertFacetBlocksAppear();
     $this->setShowAmountOfResults($facet_id, TRUE);
     // Verify that the number of results per item.
     $this->drupalGet('search/node', ['query' => ['keys' => 'test']]);
     $this->assertRaw('page <span class="facet-count">(19)</span>');
     $this->assertRaw('article <span class="facet-count">(10)</span>');
     // Verify that the label is correct for a clicked link.
     $this->clickLinkPartialName('page');
     $this->assertRaw('<span class="facet-deactivate">(-)</span> page <span class="facet-count">(19)</span>');
     // To make sure we have an empty result, we truncate the search_index table
     // because, for the moment, we don't have the possibility to clear the index
     // from the API.
     // @see https://www.drupal.org/node/326062
     \Drupal::database()->truncate('search_index')->execute();
     // Verify that no facet blocks appear. Empty behavior "None" is selected by
     // default.
     $this->drupalGet('search/node', ['query' => ['keys' => 'test']]);
     $this->assertNoFacetBlocksAppear();
     // Verify that the "empty_text" appears as expected.
     $this->setEmptyBehaviorFacetText($facet_name);
     $this->drupalGet('search/node', ['query' => ['keys' => 'test']]);
     $this->assertRaw('block-test-facet-name');
     $this->assertRaw('No results found for this block!');
     // Delete the block.
     $this->deleteBlock($facet_id);
     // Delete the facet and make sure the overview is empty again.
     $this->deleteUnusedFacet($facet_id, $facet_name);
     $this->checkEmptyOverview();
 }
 /**
  * Tests CRUD();
  */
 protected function testCRUD()
 {
     $database = \Drupal::database();
     $user = $this->drupalCreateUser();
     $payment_type_configuration = array($this->randomMachineName() => $this->randomMachineName());
     $payment_method = Payment::methodManager()->createInstance('payment_basic:no_payment_required');
     // Test creating a payment.
     $payment = Generate::createPayment($user->id(), $payment_method);
     $payment->getPaymentType()->setConfiguration($payment_type_configuration);
     $this->assertTrue($payment instanceof PaymentInterface);
     // @todo The ID should be an integer, but for some reason the entity field
     //   API returns a string.
     $this->assertTrue(is_numeric($payment->getOwnerId()));
     $this->assertEqual(count($payment->validate()), 0);
     $this->assertTrue($payment->getPaymentType() instanceof PaymentTypeInterface);
     // Test saving a payment.
     $this->assertFalse($payment->id());
     // Set an extra status, so we can test for status IDs later.
     $payment->setPaymentStatus(Payment::statusManager()->createInstance('payment_success'));
     $payment->save();
     // @todo The ID should be an integer, but for some reason the entity field
     //   API returns a string.
     $this->assertTrue(is_numeric($payment->id()));
     $this->assertTrue(strlen($payment->uuid()));
     // @todo The ID should be an integer, but for some reason the entity field
     //   API returns a string.
     $this->assertTrue(is_numeric($payment->getOwnerId()));
     // Check references to other tables.
     $payment_data = $database->select('payment', 'p')->fields('p', array('current_payment_status_delta'))->condition('id', $payment->id())->execute()->fetchAssoc();
     $this->assertEqual($payment_data['current_payment_status_delta'], 1);
     /** @var \Drupal\payment\Entity\PaymentInterface $payment_loaded */
     $payment_loaded = entity_load_unchanged('payment', $payment->id());
     $this->assertEqual(count($payment_loaded->getLineItems()), count($payment->getLineItems()));
     foreach ($payment_loaded->getLineItems() as $line_item) {
         $this->assertTrue($line_item instanceof PaymentLineItemInterface);
     }
     $this->assertEqual(count($payment_loaded->getPaymentStatuses()), count($payment->getPaymentStatuses()));
     foreach ($payment_loaded->getPaymentStatuses() as $status) {
         $this->assertTrue($status instanceof PaymentStatusInterface);
     }
     $this->assertEqual($payment_loaded->getPaymentMethod()->getConfiguration(), $payment->getPaymentMethod()->getConfiguration());
     $this->assertEqual($payment_loaded->getPaymentType()->getConfiguration(), $payment->getPaymentType()->getConfiguration());
 }
 /**
  * Test the url alias migration.
  */
 public function testUrlAlias()
 {
     $id_map = Migration::load('d6_url_alias')->getIdMap();
     // Test that the field exists.
     $conditions = array('source' => '/node/1', 'alias' => '/alias-one', 'langcode' => 'en');
     $path = \Drupal::service('path.alias_storage')->load($conditions);
     $this->assertNotNull($path, "Path alias for node/1 successfully loaded.");
     $this->assertIdentical($id_map->lookupDestinationID(array($path['pid'])), array('1'), "Test IdMap");
     $conditions = array('source' => '/node/2', 'alias' => '/alias-two', 'langcode' => 'en');
     $path = \Drupal::service('path.alias_storage')->load($conditions);
     $this->assertNotNull($path, "Path alias for node/2 successfully loaded.");
     // Test that we can re-import using the UrlAlias destination.
     Database::getConnection('default', 'migrate')->update('url_alias')->fields(array('dst' => 'new-url-alias'))->condition('src', 'node/2')->execute();
     \Drupal::database()->update($id_map->mapTableName())->fields(array('source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE))->execute();
     $migration = \Drupal::entityManager()->getStorage('migration')->loadUnchanged('d6_url_alias');
     $this->executeMigration($migration);
     $path = \Drupal::service('path.alias_storage')->load(array('pid' => $path['pid']));
     $this->assertIdentical('/new-url-alias', $path['alias']);
 }
 /**
  * Checks whether field languages are correctly stored for the given entity.
  *
  * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
  *   The entity fields are attached to.
  * @param string $message
  *   (optional) A message to display with the assertion.
  */
 protected function assertFieldStorageLangcode(FieldableEntityInterface $entity, $message = '')
 {
     $status = TRUE;
     $entity_type = $entity->getEntityTypeId();
     $id = $entity->id();
     $langcode = $entity->getUntranslated()->language()->getId();
     $fields = array($this->field_name, $this->untranslatable_field_name);
     /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
     $table_mapping = \Drupal::entityManager()->getStorage($entity_type)->getTableMapping();
     foreach ($fields as $field_name) {
         $field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);
         $table = $table_mapping->getDedicatedDataTableName($field_storage);
         $record = \Drupal::database()->select($table, 'f')->fields('f')->condition('f.entity_id', $id)->condition('f.revision_id', $id)->execute()->fetchObject();
         if ($record->langcode != $langcode) {
             $status = FALSE;
             break;
         }
     }
     return $this->assertTrue($status, $message);
 }
 /**
  * Checks whether field languages are correctly stored for the given entity.
  *
  * @param \Drupal\Core\Entity\ContentEntityInterface $entity
  *   The entity fields are attached to.
  * @param string $message
  *   (optional) A message to display with the assertion.
  */
 protected function assertFieldStorageLangcode(ContentEntityInterface $entity, $message = '')
 {
     $status = TRUE;
     $entity_type = $entity->getEntityTypeId();
     $id = $entity->id();
     $langcode = $entity->getUntranslated()->language()->id;
     $fields = array($this->field_name, $this->untranslatable_field_name);
     foreach ($fields as $field_name) {
         $field_storage = FieldStorageConfig::loadByName($entity_type, $field_name);
         $tables = array(ContentEntityDatabaseStorage::_fieldTableName($field_storage), ContentEntityDatabaseStorage::_fieldRevisionTableName($field_storage));
         foreach ($tables as $table) {
             $record = \Drupal::database()->select($table, 'f')->fields('f')->condition('f.entity_id', $id)->condition('f.revision_id', $id)->execute()->fetchObject();
             if ($record->langcode != $langcode) {
                 $status = FALSE;
                 break;
             }
         }
     }
     return $this->assertTrue($status, $message);
 }
 /**
  * Tests that individual updates applied sequentially work as expected.
  */
 public function testSingleUpdates()
 {
     // Create a test entity.
     $user_ids = [mt_rand(), mt_rand()];
     $entity = EntityTest::create(['name' => $this->randomString(), 'user_id' => $user_ids]);
     $entity->save();
     // Check that only a single value is stored for 'user_id'.
     $entity = $this->reloadEntity($entity);
     $this->assertEqual(count($entity->user_id), 1);
     $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
     // Make 'user_id' multiple by applying updates.
     $this->enableUpdates('entity_test', 'entity_definition_updates', 8001);
     $this->applyUpdates();
     // Ensure the 'entity_test__user_id' table got created.
     $this->assertTrue(\Drupal::database()->schema()->tableExists('entity_test__user_id'));
     // Check that data was correctly migrated.
     $entity = $this->reloadEntity($entity);
     $this->assertEqual(count($entity->user_id), 1);
     $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
     // Store multiple data and check it is correctly stored.
     $entity->user_id = $user_ids;
     $entity->save();
     $entity = $this->reloadEntity($entity);
     $this->assertEqual(count($entity->user_id), 2);
     $this->assertEqual($entity->user_id[0]->target_id, $user_ids[0]);
     $this->assertEqual($entity->user_id[1]->target_id, $user_ids[1]);
     // Make 'user_id' single again by applying updates.
     $this->enableUpdates('entity_test', 'entity_definition_updates', 8002);
     $this->applyUpdates();
     // Check that data was correctly migrated/dropped.
     $entity = $this->reloadEntity($entity);
     $this->assertEqual(count($entity->user_id), 1);
     $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
     // Check that only a single value is stored for 'user_id' again.
     $entity->user_id = $user_ids;
     $entity->save();
     $entity = $this->reloadEntity($entity);
     $this->assertEqual(count($entity->user_id), 1);
     $this->assertEqual($entity->user_id[0]->target_id, $user_ids[0]);
 }
Example #22
0
 /**
  * Tests that the status page returns.
  */
 public function testStatusPage()
 {
     // Go to Administration.
     $this->drupalGet('admin/reports/status');
     $this->assertResponse(200, 'The status page is reachable.');
     $phpversion = phpversion();
     $this->assertText($phpversion, 'Php version is shown on the page.');
     // Checks if the suggestion to update to php 5.5.21 or 5.6.5 for disabling
     // multiple statements is present when necessary.
     if (\Drupal::database()->driver() === 'mysql' && !SystemRequirements::phpVersionWithPdoDisallowMultipleStatements($phpversion)) {
         $this->assertText(t('PHP (multiple statement disabling)'));
     } else {
         $this->assertNoText(t('PHP (multiple statement disabling)'));
     }
     if (function_exists('phpinfo')) {
         $this->assertLinkByHref(Url::fromRoute('system.php')->toString());
     } else {
         $this->assertNoLinkByHref(Url::fromRoute('system.php')->toString());
     }
     $this->drupalGet('admin/reports/status/php');
     $this->assertResponse(200, 'The phpinfo page is reachable.');
 }
Example #23
0
 /**
  * Tests the Drupal 6 files to Drupal 8 migration.
  */
 public function testFiles()
 {
     /** @var \Drupal\file\FileInterface $file */
     $file = File::load(1);
     $this->assertIdentical('Image1.png', $file->getFilename());
     $this->assertIdentical('39325', $file->getSize());
     $this->assertIdentical('public://image-1.png', $file->getFileUri());
     $this->assertIdentical('image/png', $file->getMimeType());
     $this->assertIdentical("1", $file->getOwnerId());
     // Test that we can re-import and also test with file_directory_path set.
     \Drupal::database()->truncate(Migration::load('d6_file')->getIdMap()->mapTableName())->execute();
     // Update the file_directory_path.
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize('files/test')))->condition('name', 'file_directory_path')->execute();
     Database::getConnection('default', 'migrate')->update('variable')->fields(array('value' => serialize($this->getTempFilesDirectory())))->condition('name', 'file_directory_temp')->execute();
     $migration = \Drupal::entityManager()->getStorage('migration')->loadUnchanged('d6_file');
     $this->executeMigration($migration);
     $file = File::load(2);
     $this->assertIdentical('public://core/modules/simpletest/files/image-2.jpg', $file->getFileUri());
     // Ensure that a temporary file has been migrated.
     $file = File::load(6);
     $this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
 }
Example #24
0
 /**
  * Tests that the status page returns.
  */
 public function testStatusPage()
 {
     // Go to Administration.
     $this->drupalGet('admin/reports/status');
     $this->assertResponse(200, 'The status page is reachable.');
     $phpversion = phpversion();
     $this->assertText($phpversion, 'Php version is shown on the page.');
     // Checks if the suggestion to update to php 5.5.21 or 5.6.5 for disabling
     // multiple statements is present when necessary.
     if (\Drupal::database()->driver() === 'mysql' && !SystemRequirements::phpVersionWithPdoDisallowMultipleStatements($phpversion)) {
         $this->assertText(t('PHP (multiple statement disabling)'));
     } else {
         $this->assertNoText(t('PHP (multiple statement disabling)'));
     }
     if (function_exists('phpinfo')) {
         $this->assertLinkByHref(Url::fromRoute('system.php')->toString());
     } else {
         $this->assertNoLinkByHref(Url::fromRoute('system.php')->toString());
     }
     // If a module is fully installed no pending updates exists.
     $this->assertNoText(t('Out of date'));
     // The global $config_directories is not properly formed.
     $this->assertRaw(t('Your %file file must define the $config_directories variable as an array containing the names of directories in which configuration files can be found. It must contain a %sync_key key.', array('%file' => $this->siteDirectory . '/settings.php', '%sync_key' => CONFIG_SYNC_DIRECTORY)));
     // Set the schema version of update_test_postupdate to a lower version, so
     // update_test_postupdate_update_8001() needs to be executed.
     drupal_set_installed_schema_version('update_test_postupdate', 8000);
     $this->drupalGet('admin/reports/status');
     $this->assertText(t('Out of date'));
     // Now cleanup the executed post update functions.
     drupal_set_installed_schema_version('update_test_postupdate', 8001);
     /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
     $post_update_registry = \Drupal::service('update.post_update_registry');
     $post_update_registry->filterOutInvokedUpdatesByModule('update_test_postupdate');
     $this->drupalGet('admin/reports/status');
     $this->assertText(t('Out of date'));
     $this->drupalGet('admin/reports/status/php');
     $this->assertResponse(200, 'The phpinfo page is reachable.');
 }
Example #25
0
 /**
  * Test the url alias migration.
  */
 public function testUrlAlias()
 {
     $id_map = $this->getMigration('d6_url_alias')->getIdMap();
     // Test that the field exists.
     $conditions = array('source' => '/node/1', 'alias' => '/alias-one', 'langcode' => 'af');
     $path = \Drupal::service('path.alias_storage')->load($conditions);
     $this->assertPath('1', $conditions, $path);
     $this->assertIdentical($id_map->lookupDestinationID(array($path['pid'])), array('1'), "Test IdMap");
     $conditions = array('source' => '/node/2', 'alias' => '/alias-two', 'langcode' => 'en');
     $path = \Drupal::service('path.alias_storage')->load($conditions);
     $this->assertPath('2', $conditions, $path);
     // Test that we can re-import using the UrlAlias destination.
     Database::getConnection('default', 'migrate')->update('url_alias')->fields(array('dst' => 'new-url-alias'))->condition('src', 'node/2')->execute();
     \Drupal::database()->update($id_map->mapTableName())->fields(array('source_row_status' => MigrateIdMapInterface::STATUS_NEEDS_UPDATE))->execute();
     $migration = $this->getMigration('d6_url_alias');
     $this->executeMigration($migration);
     $path = \Drupal::service('path.alias_storage')->load(array('pid' => $path['pid']));
     $conditions['alias'] = '/new-url-alias';
     $this->assertPath('2', $conditions, $path);
     $conditions = array('source' => '/node/3', 'alias' => '/alias-three', 'langcode' => 'und');
     $path = \Drupal::service('path.alias_storage')->load($conditions);
     $this->assertPath('3', $conditions, $path);
 }
  /**
   * Tests the Drupal 7 menu to Drupal 8 migration.
   */
  public function testMenu() {
    $this->assertEntity('main', 'Main menu', 'The <em>Main</em> menu is used on many sites to show the major sections of the site, often in a top navigation bar.');
    $this->assertEntity('admin', 'Management', 'The <em>Management</em> menu contains links for administrative tasks.');
    $this->assertEntity('menu-test-menu', 'Test Menu', 'Test menu description.');
    $this->assertEntity('tools', 'Navigation', 'The <em>Navigation</em> menu contains links intended for site visitors. Links are added to the <em>Navigation</em> menu automatically by some modules.');
    $this->assertEntity('account', 'User menu', 'The <em>User</em> menu contains links related to the user\'s account, as well as the \'Log out\' link.');

    // Test that we can re-import using the ConfigEntityBase destination.
    Database::getConnection('default', 'migrate')
      ->update('menu_custom')
      ->fields(array('title' => 'Home Navigation'))
      ->condition('menu_name', 'navigation')
      ->execute();

    $migration = $this->getMigration('d7_menu');
    \Drupal::database()
        ->truncate($migration->getIdMap()->mapTableName())
        ->execute();
    $this->executeMigration($migration);

    $navigation_menu = Menu::load('tools');
    $this->assertSame('Home Navigation', $navigation_menu->label());
  }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function query()
 {
     $key = reset($this->value);
     $field = $this->field;
     $table = $this->table;
     switch ($key) {
         case 'needs_review':
             $table_alias = 'job_item';
             // Create a sub query to add the state of job item to the view.
             $sub_query = \Drupal::database()->select('tmgmt_job_item', $table_alias);
             $sub_query->addField($table_alias, 'tjid');
             // Add a where clause to check if there are job items with state 2.
             $sub_query->condition("{$table_alias}.state", 2, '=');
             // Select all job items that are in the sub query.
             $this->query->addWhere($this->options['group'], 'tjid', $sub_query, 'IN');
             $this->query->addWhere($this->options['group'], "{$table}.{$field}", '1', '=');
             break;
         case 'in_progress':
             $table_alias = 'job_item';
             // Create a sub query to add the state of job item to the view.
             $sub_query = \Drupal::database()->select('tmgmt_job_item', $table_alias);
             $sub_query->addField($table_alias, 'tjid');
             // Add a where clause to check if there are job items with state 2.
             $sub_query->condition("{$table_alias}.state", 2, '=');
             // Select all job items that are not in the sub query.
             $this->query->addWhere($this->options['group'], 'tjid', $sub_query, 'NOT IN');
             $this->query->addWhere($this->options['group'], "{$table}.{$field}", '1', '=');
             break;
         case 'open_jobs':
             $this->query->addWhere($this->options['group'], "{$table}.{$field}", array(0, 1, 2, 3, 6), 'IN');
             break;
         default:
             $this->query->addWhere($this->options['group'], "{$table}.{$field}", $key, '=');
             break;
     }
 }
Example #28
0
 /**
  * Tests that the status page returns.
  */
 public function testStatusPage()
 {
     // Go to Administration.
     $this->drupalGet('admin/reports/status');
     $this->assertResponse(200, 'The status page is reachable.');
     $phpversion = phpversion();
     $this->assertText($phpversion, 'Php version is shown on the page.');
     // Checks if the suggestion to update to php 5.5.21 or 5.6.5 for disabling
     // multiple statements is present when necessary.
     if (\Drupal::database()->driver() === 'mysql' && !SystemRequirements::phpVersionWithPdoDisallowMultipleStatements($phpversion)) {
         $this->assertText(t('PHP (multiple statement disabling)'));
     } else {
         $this->assertNoText(t('PHP (multiple statement disabling)'));
     }
     if (function_exists('phpinfo')) {
         $this->assertLinkByHref(Url::fromRoute('system.php')->toString());
     } else {
         $this->assertNoLinkByHref(Url::fromRoute('system.php')->toString());
     }
     // If a module is fully installed no pending updates exists.
     $this->assertNoText(t('Out of date'));
     // Set the schema version of update_test_postupdate to a lower version, so
     // update_test_postupdate_update_8001() needs to be executed.
     drupal_set_installed_schema_version('update_test_postupdate', 8000);
     $this->drupalGet('admin/reports/status');
     $this->assertText(t('Out of date'));
     // Now cleanup the executed post update functions.
     drupal_set_installed_schema_version('update_test_postupdate', 8001);
     /** @var \Drupal\Core\Update\UpdateRegistry $post_update_registry */
     $post_update_registry = \Drupal::service('update.post_update_registry');
     $post_update_registry->filterOutInvokedUpdatesByModule('update_test_postupdate');
     $this->drupalGet('admin/reports/status');
     $this->assertText(t('Out of date'));
     $this->drupalGet('admin/reports/status/php');
     $this->assertResponse(200, 'The phpinfo page is reachable.');
 }
 /**
  * Test creating a field with custom storage set.
  */
 public function testCreateFieldCustomStorage()
 {
     $field_name = Unicode::strtolower($this->randomMachineName());
     \Drupal::state()->set('field_test_custom_storage', $field_name);
     $field_storage = FieldStorageConfig::create(['field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'test_field', 'custom_storage' => TRUE]);
     $field_storage->save();
     $field = FieldConfig::create(['field_name' => $field_storage->getName(), 'entity_type' => 'entity_test', 'bundle' => 'entity_test']);
     $field->save();
     \Drupal::entityManager()->clearCachedFieldDefinitions();
     // Check that no table has been created for the field.
     $this->assertFalse(\Drupal::database()->schema()->tableExists('entity_test__' . $field_storage->getName()));
     // Save an entity with a value in the custom storage field and verify no
     // data is retrieved on load.
     $entity = EntityTest::create(['name' => $this->randomString(), $field_name => 'Test value']);
     $this->assertIdentical('Test value', $entity->{$field_name}->value, 'The test value is set on the field.');
     $entity->save();
     $entity = EntityTest::load($entity->id());
     $this->assertNull($entity->{$field_name}->value, 'The loaded entity field value is NULL.');
 }
 /**
  * Tests whether removing the configuration again works as it should.
  */
 protected function checkModuleUninstall()
 {
     // See whether clearing the server works.
     // Regression test for #2156151.
     $server = Server::load($this->serverId);
     $index = Index::load($this->indexId);
     $server->deleteAllIndexItems($index);
     $query = $this->buildSearch();
     $results = $query->execute();
     $this->assertEqual($results->getResultCount(), 0, 'Clearing the server worked correctly.');
     $table = 'search_api_db_' . $this->indexId;
     $this->assertTrue(db_table_exists($table), 'The index tables were left in place.');
     // Remove first the index and then the server.
     $index->setServer();
     $index->save();
     $server = Server::load($this->serverId);
     $this->assertEqual($server->getBackendConfig()['field_tables'], array(), 'The index was successfully removed from the server.');
     $this->assertFalse(db_table_exists($table), 'The index tables were deleted.');
     $server->delete();
     // Uninstall the module.
     \Drupal::service('module_installer')->uninstall(array('search_api_db'), FALSE);
     #\Drupal::moduleHandler()->uninstall(array('search_api_db'), FALSE);
     $this->assertFalse(\Drupal::moduleHandler()->moduleExists('search_api_db'), 'The Database Search module was successfully disabled.');
     $prefix = \Drupal::database()->prefixTables('{search_api_db_}') . '%';
     $this->assertEqual(\Drupal::database()->schema()->findTables($prefix), array(), 'The Database Search module was successfully uninstalled.');
 }