当前位置: 首页>>代码示例>>PHP>>正文


PHP Drupal::database方法代码示例

本文整理汇总了PHP中Drupal::database方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::database方法的具体用法?PHP Drupal::database怎么用?PHP Drupal::database使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Drupal的用法示例。


在下文中一共展示了Drupal::database方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: assertFieldSchemaData

 /**
  * 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);
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:18,代码来源:FieldSchemaDataUninstallUpdateTest.php

示例2: testUpdate

 /**
  * 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));
             }
         }
     }
 }
开发者ID:nsp15,项目名称:Drupal8,代码行数:32,代码来源:MenuTreeSerializationTitleTest.php

示例3: callback_batch_operation

/**
 * 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'];
    }
}
开发者ID:sgtsaughter,项目名称:d8portfolio,代码行数:78,代码来源:form.api.php

示例4: testMenu

  /**
   * 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());
  }
开发者ID:Greg-Boggs,项目名称:electric-dev,代码行数:28,代码来源:MigrateMenuTest.php

示例5: testDatabaseLoaded

 /**
  * 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());
     }
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:38,代码来源:UpdatePathTestBaseTest.php

示例6: setUp

 /**
  * {@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();
 }
开发者ID:papillon-cendre,项目名称:d8,代码行数:10,代码来源:MigrateNodeTest.php

示例7: setUp

 /**
  * {@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);
 }
开发者ID:nishantkumar155,项目名称:drupal8.crackle,代码行数:12,代码来源:DatabaseQueueWebTest.php

示例8: validUser

 /**
  * 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'])));
         }
     }
 }
开发者ID:eric-shell,项目名称:eric-shell-d8,代码行数:12,代码来源:LoginSecurityAdminSettings.php

示例9: build

 /**
  * 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>');
 }
开发者ID:DenLilleMand,项目名称:christianssite,代码行数:67,代码来源:HelloWorldBlock2.php

示例10: setUp

 /**
  * {@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;
 }
开发者ID:ravindrasingh22,项目名称:Drupal-8-rc,代码行数:14,代码来源:MigrateNodeTest.php

示例11: import

 /**
  * {@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;
 }
开发者ID:penguinclub,项目名称:penguinweb_drupal8,代码行数:17,代码来源:AclTable.php

示例12: testDateFormats

 /**
  * 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());
 }
开发者ID:sojo,项目名称:d8_friendsofsilence,代码行数:19,代码来源:MigrateDateFormatTest.php

示例13: rerunMigration

 /**
  * 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;
 }
开发者ID:frankcr,项目名称:sftw8,代码行数:26,代码来源:MigrateNodeTest.php

示例14: testFiles

 /**
  * 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));
 }
开发者ID:eigentor,项目名称:tommiblog,代码行数:21,代码来源:MigrateFileTest.php

示例15: testUpdateHookN

 /**
  * 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.');
 }
开发者ID:frankcr,项目名称:sftw8,代码行数:21,代码来源:UpdatePathTestBaseTest.php


注:本文中的Drupal::database方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。