本文整理汇总了PHP中Drupal\Core\Database\Connection类的典型用法代码示例。如果您正苦于以下问题:PHP Connection类的具体用法?PHP Connection怎么用?PHP Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Connection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Remove any backtraces since they may contain an unserializable variable.
unset($context['backtrace']);
// Convert PSR3-style messages to SafeMarkup::format() style, so they can be
// translated too in runtime.
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
try {
$this->connection->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => Unicode::substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => $context['link'], 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => Unicode::substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
} catch (\Exception $e) {
// When running Drupal on MySQL or MariaDB you can run into several errors
// that corrupt the database connection. Some examples for these kind of
// errors on the database layer are "1100 - Table 'xyz' was not locked
// with LOCK TABLES" and "1153 - Got a packet bigger than
// 'max_allowed_packet' bytes". If such an error happens, the MySQL server
// invalidates the connection and answers all further requests in this
// connection with "2006 - MySQL server had gone away". In that case the
// insert statement above results in a database exception. To ensure that
// the causal error is written to the log we try once to open a dedicated
// connection and write again.
if (($e instanceof DatabaseException || $e instanceof \PDOException) && $this->connection->getTarget() != self::DEDICATED_DBLOG_CONNECTION_TARGET) {
// Open a dedicated connection for logging.
$key = $this->connection->getKey();
$info = Database::getConnectionInfo($key);
Database::addConnectionInfo($key, self::DEDICATED_DBLOG_CONNECTION_TARGET, $info['default']);
$this->connection = Database::getConnection(self::DEDICATED_DBLOG_CONNECTION_TARGET, $key);
// Now try once to log the error again.
$this->log($level, $message, $context);
} else {
throw $e;
}
}
}
开发者ID:ddrozdik,项目名称:dmaps,代码行数:36,代码来源:DbLog.php
示例2: collect
/**
* {@inheritdoc}
*/
public function collect(Request $request, Response $response, \Exception $exception = NULL)
{
$connections = [];
foreach (Database::getAllConnectionInfo() as $key => $info) {
$database = Database::getConnection('default', $key);
$connections[$key] = $database->getLogger()->get('webprofiler');
}
$this->data['connections'] = array_keys($connections);
$data = [];
foreach ($connections as $key => $queries) {
foreach ($queries as $query) {
// Remove caller args.
unset($query['caller']['args']);
// Remove query args element if empty.
if (empty($query['args'])) {
unset($query['args']);
}
// Save time in milliseconds.
$query['time'] = $query['time'] * 1000;
$query['database'] = $key;
$data[] = $query;
}
}
$querySort = $this->configFactory->get('webprofiler.config')->get('query_sort');
if ('duration' === $querySort) {
usort($data, ["Drupal\\webprofiler\\DataCollector\\DatabaseDataCollector", "orderQueryByTime"]);
}
$this->data['queries'] = $data;
$options = $this->database->getConnectionOptions();
// Remove password for security.
unset($options['password']);
$this->data['database'] = $options;
}
开发者ID:sgtsaughter,项目名称:d8portfolio,代码行数:36,代码来源:DatabaseDataCollector.php
示例3: dropTables
/**
* Drop the tables used for the sample data.
*
* @param \Drupal\Core\Database\Connection $connection
* The connection to use to drop the tables.
*/
public function dropTables(Connection $connection)
{
$tables = $this->routingTableDefinition();
$schema = $connection->schema();
foreach ($tables as $name => $table) {
$schema->dropTable($name);
}
}
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:14,代码来源:RoutingFixtures.php
示例4: __construct
/**
* Constructs a Query object.
*
* @param \Drupal\Core\Database\Connection $connection
* Database connection object.
* @param array $options
* Array of query options.
*/
public function __construct(Connection $connection, $options)
{
$this->uniqueIdentifier = uniqid('', TRUE);
$this->connection = $connection;
$this->connectionKey = $this->connection->getKey();
$this->connectionTarget = $this->connection->getTarget();
$this->queryOptions = $options;
}
开发者ID:papillon-cendre,项目名称:d8,代码行数:16,代码来源:Query.php
示例5: doTestEntry
/**
* Checks whether the expected logging entry got written.
*
* @param \Drupal\Core\Database\Connection $connection
* The database collection.
*/
protected function doTestEntry(Connection $connection)
{
$result = $connection->select('watchdog')->fields('watchdog')->execute()->fetchAll();
$this->assertEqual(1, count($result));
$this->assertEqual(WATCHDOG_INFO, $result[0]->severity);
$this->assertEqual('system', $result[0]->type);
$this->assertEqual('Hello world @key', $result[0]->message);
$this->assertEqual(array('@key' => 'value'), unserialize($result[0]->variables));
}
开发者ID:EarthTeam,项目名称:earthteam.net,代码行数:15,代码来源:LoggerIntegrationTest.php
示例6: setUp
/**
* Sets up required mocks and the CommentStatistics service under test.
*/
protected function setUp()
{
$this->statement = $this->getMockBuilder('Drupal\\Core\\Database\\Driver\\sqlite\\Statement')->disableOriginalConstructor()->getMock();
$this->statement->expects($this->any())->method('fetchObject')->will($this->returnCallback(array($this, 'fetchObjectCallback')));
$this->select = $this->getMockBuilder('Drupal\\Core\\Database\\Query\\Select')->disableOriginalConstructor()->getMock();
$this->select->expects($this->any())->method('fields')->will($this->returnSelf());
$this->select->expects($this->any())->method('condition')->will($this->returnSelf());
$this->select->expects($this->any())->method('execute')->will($this->returnValue($this->statement));
$this->database = $this->getMockBuilder('Drupal\\Core\\Database\\Connection')->disableOriginalConstructor()->getMock();
$this->database->expects($this->once())->method('select')->will($this->returnValue($this->select));
$this->commentStatistics = new CommentStatistics($this->database, $this->getMock('Drupal\\Core\\Session\\AccountInterface'), $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'), $this->getMock('Drupal\\Core\\State\\StateInterface'));
}
开发者ID:sarahwillem,项目名称:OD8,代码行数:15,代码来源:CommentStatisticsUnitTest.php
示例7: runScript
/**
* Run the database script.
*
* @param \Drupal\Core\Database\Connection $connection
* Connection used by the script when included.
* @param string $script
* Path to dump script.
*/
protected function runScript(Connection $connection, $script)
{
$old_key = Database::setActiveConnection($connection->getKey());
if (substr($script, -3) == '.gz') {
$script = "compress.zlib://{$script}";
}
try {
require $script;
} catch (SchemaObjectExistsException $e) {
throw new \RuntimeException('An existing Drupal installation exists at this location. Try removing all tables or changing the database prefix in your settings.php file.');
}
Database::setActiveConnection($old_key);
}
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:21,代码来源:DbImportCommand.php
示例8: testEntitySchemaUpdate
/**
* Tests that entity schema responds to changes in the entity type definition.
*/
public function testEntitySchemaUpdate()
{
$this->installModule('entity_schema_test');
$storage_definitions = $this->entityManager->getFieldStorageDefinitions('entity_test');
$this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_base_field']);
$this->entityManager->onFieldStorageDefinitionCreate($storage_definitions['custom_bundle_field']);
$schema_handler = $this->database->schema();
$tables = array('entity_test', 'entity_test_revision', 'entity_test_field_data', 'entity_test_field_revision');
$dedicated_tables = array('entity_test__custom_bundle_field', 'entity_test_revision__custom_bundle_field');
// Initially only the base table and the dedicated field data table should
// exist.
foreach ($tables as $index => $table) {
$this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
$this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
// Update the entity type definition and check that the entity schema now
// supports translations and revisions.
$this->updateEntityType(TRUE);
foreach ($tables as $table) {
$this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
foreach ($dedicated_tables as $table) {
$this->assertTrue($schema_handler->tableExists($table), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
}
// Revert changes and check that the entity schema now does not support
// neither translations nor revisions.
$this->updateEntityType(FALSE);
foreach ($tables as $index => $table) {
$this->assertEqual($schema_handler->tableExists($table), !$index, SafeMarkup::format('Entity schema correct for the @table table.', array('@table' => $table)));
}
$this->assertTrue($schema_handler->tableExists($dedicated_tables[0]), SafeMarkup::format('Field schema correct for the @table table.', array('@table' => $table)));
}
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:35,代码来源:EntitySchemaTest.php
示例9: findMatchingRedirect
/**
* Gets a redirect for given path, query and language.
*
* @param string $source_path
* The redirect source path.
* @param array $query
* The redirect source path query.
* @param $language
* The language for which is the redirect.
*
* @return \Drupal\redirect\Entity\Redirect
* The matched redirect entity.
*
* @throws \Drupal\redirect\Exception\RedirectLoopException
*/
public function findMatchingRedirect($source_path, array $query = [], $language = Language::LANGCODE_NOT_SPECIFIED)
{
$hashes = [Redirect::generateHash($source_path, $query, $language)];
if ($language != Language::LANGCODE_NOT_SPECIFIED) {
$hashes[] = Redirect::generateHash($source_path, $query, Language::LANGCODE_NOT_SPECIFIED);
}
// Add a hash without the query string if using passthrough querystrings.
if (!empty($query) && $this->config->get('passthrough_querystring')) {
$hashes[] = Redirect::generateHash($source_path, [], $language);
if ($language != Language::LANGCODE_NOT_SPECIFIED) {
$hashes[] = Redirect::generateHash($source_path, [], Language::LANGCODE_NOT_SPECIFIED);
}
}
// Load redirects by hash. A direct query is used to improve performance.
$rid = $this->connection->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [':hashes[]' => $hashes])->fetchField();
if (!empty($rid)) {
// Check if this is a loop.
if (in_array($rid, $this->foundRedirects)) {
throw new RedirectLoopException('/' . $source_path, $rid);
}
$this->foundRedirects[] = $rid;
$redirect = $this->load($rid);
// Find chained redirects.
if ($recursive = $this->findByRedirect($redirect, $language)) {
// Reset found redirects.
$this->foundRedirects = [];
return $recursive;
}
return $redirect;
}
return NULL;
}
开发者ID:isramv,项目名称:camp-gdl,代码行数:47,代码来源:RedirectRepository.php
示例10: preRender
public function preRender(&$values)
{
$uids = array();
$this->items = array();
foreach ($values as $result) {
$uids[] = $this->getValue($result);
}
if ($uids) {
$roles = user_roles();
$result = $this->database->query('SELECT u.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles)));
foreach ($result as $role) {
$this->items[$role->uid][$role->rid]['role'] = $roles[$role->rid]->label();
$this->items[$role->uid][$role->rid]['rid'] = $role->rid;
}
// Sort the roles for each user by role weight.
$ordered_roles = array_flip(array_keys($roles));
foreach ($this->items as &$user_roles) {
// Create an array of rids that the user has in the role weight order.
$sorted_keys = array_intersect_key($ordered_roles, $user_roles);
// Merge with the unsorted array of role information which has the
// effect of sorting it.
$user_roles = array_merge($sorted_keys, $user_roles);
}
}
}
开发者ID:neetumorwani,项目名称:blogging,代码行数:25,代码来源:Roles.php
示例11: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$_SESSION['dblog_overview_filter'] = array();
$this->connection->delete('watchdog')->execute();
drupal_set_message($this->t('Database log cleared.'));
$form_state->setRedirectUrl($this->getCancelUrl());
}
开发者ID:aWEBoLabs,项目名称:taxi,代码行数:10,代码来源:DblogClearLogConfirmForm.php
示例12: overview
/**
* Displays a listing of migration messages.
*
* Messages are truncated at 56 chars.
*
* @return array
* A render array as expected by drupal_render().
*/
public function overview($migration_group, $migration)
{
$rows = [];
$classes = static::getLogLevelClassMap();
/** @var MigrationInterface $migration */
$migration = Migration::load($migration);
$source_id_field_names = array_keys($migration->getSourcePlugin()->getIds());
$column_number = 1;
foreach ($source_id_field_names as $source_id_field_name) {
$header[] = ['data' => $source_id_field_name, 'field' => 'sourceid' . $column_number++, 'class' => [RESPONSIVE_PRIORITY_MEDIUM]];
}
$header[] = ['data' => $this->t('Severity level'), 'field' => 'level', 'class' => [RESPONSIVE_PRIORITY_LOW]];
$header[] = ['data' => $this->t('Message'), 'field' => 'message'];
$message_table = $migration->getIdMap()->messageTableName();
$query = $this->database->select($message_table, 'm')->extend('\\Drupal\\Core\\Database\\Query\\PagerSelectExtender')->extend('\\Drupal\\Core\\Database\\Query\\TableSortExtender');
$query->fields('m');
$result = $query->limit(50)->orderByHeader($header)->execute();
foreach ($result as $message_row) {
$column_number = 1;
foreach ($source_id_field_names as $source_id_field_name) {
$column_name = 'sourceid' . $column_number++;
$row[$column_name] = $message_row->{$column_name};
}
$row['level'] = $message_row->level;
$row['message'] = $message_row->message;
$row['class'] = [Html::getClass('migrate-message-' . $message_row->level), $classes[$message_row->level]];
$rows[] = $row;
}
$build['message_table'] = ['#type' => 'table', '#header' => $header, '#rows' => $rows, '#attributes' => ['id' => $message_table, 'class' => [$message_table]], '#empty' => $this->t('No messages for this migration.')];
$build['message_pager'] = ['#type' => 'pager'];
return $build;
}
开发者ID:sheldonrampton,项目名称:drupal8-drops,代码行数:40,代码来源:MessageController.php
示例13: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, array &$form_state)
{
$_SESSION['dblog_overview_filter'] = array();
$this->connection->delete('watchdog')->execute();
drupal_set_message($this->t('Database log cleared.'));
$form_state['redirect_route'] = $this->getCancelRoute();
}
开发者ID:alnutile,项目名称:drunatra,代码行数:10,代码来源:DblogClearLogConfirmForm.php
示例14: clearEvents
/**
* @param DrupalStyle $io
* @param $eventType
* @param $eventSeverity
* @param $userId
* @return bool
*/
protected function clearEvents(DrupalStyle $io, $eventType, $eventSeverity, $userId)
{
$severity = RfcLogLevel::getLevels();
$query = $this->database->delete('watchdog');
if ($eventType) {
$query->condition('type', $eventType);
}
if ($eventSeverity) {
if (!in_array($eventSeverity, $severity)) {
$io->error(sprintf($this->trans('commands.database.log.clear.messages.invalid-severity'), $eventSeverity));
return false;
}
$query->condition('severity', array_search($eventSeverity, $severity));
}
if ($userId) {
$query->condition('uid', $userId);
}
$result = $query->execute();
if (!$result) {
$io->error($this->trans('commands.database.log.clear.messages.clear-error'));
return false;
}
$io->success($this->trans('commands.database.log.clear.messages.clear-sucess'));
return true;
}
开发者ID:ibonelli,项目名称:DrupalConsole,代码行数:32,代码来源:LogClearCommand.php
示例15: execute
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new DrupalStyle($input, $output);
$uid = $input->getArgument('user');
$user = User::load($uid);
if (!$user) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.invalid-user'), $uid));
return 1;
}
$password = $input->getArgument('password');
if (!$password) {
$io->error(sprintf($this->trans('commands.user.password.reset.errors.empty-password'), $uid));
return 1;
}
try {
$user->setPassword($password);
$user->save();
$schema = $this->database->schema();
$flood = $schema->findTables('flood');
if ($flood) {
$this - $this->chainQueue->addCommand('user:login:clear:attempts', ['uid' => $uid]);
}
} catch (\Exception $e) {
$io->error($e->getMessage());
return 1;
}
$io->success(sprintf($this->trans('commands.user.password.reset.messages.reset-successful'), $uid));
}
开发者ID:ibonelli,项目名称:DrupalConsole,代码行数:31,代码来源:PasswordResetCommand.php
示例16: createTable
/**
* Create a new table from a Drupal table definition if it doesn't exist.
*
* @param string $name
* The name of the table to create.
* @param array $table
* A Schema API table definition array.
*/
protected function createTable($name, array $table)
{
// This must be on the database connection to be shared among classes.
if (empty($this->database->migrateTables[$name])) {
$this->database->migrateTables[$name] = TRUE;
$this->database->schema()->createTable($name, $table);
}
}
开发者ID:dev981,项目名称:gaptest,代码行数:16,代码来源:DrupalDumpBase.php
示例17: listUsage
/**
* Implements Drupal\file\FileUsage\FileUsageInterface::listUsage().
*/
public function listUsage(FileInterface $file)
{
$result = $this->connection->select($this->tableName, 'f')->fields('f', array('module', 'type', 'id', 'count'))->condition('fid', $file->id())->condition('count', 0, '>')->execute();
$references = array();
foreach ($result as $usage) {
$references[$usage->module][$usage->type][$usage->id] = $usage->count;
}
return $references;
}
开发者ID:HakS,项目名称:drupal8_training,代码行数:12,代码来源:DatabaseFileUsageBackend.php
示例18: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Remove any backtraces since they may contain an unserializable variable.
unset($context['backtrace']);
// Convert PSR3-style messages to String::format() style, so they can be
// translated too in runtime.
$message_placeholders = $this->parser->parseMessagePlaceholders($message, $context);
$this->database->insert('watchdog')->fields(array('uid' => $context['uid'], 'type' => substr($context['channel'], 0, 64), 'message' => $message, 'variables' => serialize($message_placeholders), 'severity' => $level, 'link' => substr($context['link'], 0, 255), 'location' => $context['request_uri'], 'referer' => $context['referer'], 'hostname' => substr($context['ip'], 0, 128), 'timestamp' => $context['timestamp']))->execute();
}
开发者ID:davidsoloman,项目名称:drupalconsole.com,代码行数:12,代码来源:DbLog.php
示例19: loadMultiple
/**
* {@inheritdoc}
*/
public function loadMultiple($nids, $access = TRUE)
{
$query = $this->connection->select('node', 'n', array('fetch' => \PDO::FETCH_ASSOC));
$query->fields('n');
$query->condition('n.nid', $nids, 'IN');
if ($access) {
$query->addTag('node_access');
}
return $query->execute();
}
开发者ID:joesb,项目名称:wunderhub,代码行数:13,代码来源:WkHubPrincipleStorage.php
示例20: buildForm
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state)
{
$num_nodes = $this->database->query("SELECT COUNT(*) FROM {node} WHERE type = :type", array(':type' => $this->entity->id()))->fetchField();
if ($num_nodes) {
$caption = '<p>' . format_plural($num_nodes, '%type is used by 1 piece of content on your site. You can not remove this content type until you have removed all of the %type content.', '%type is used by @count pieces of content on your site. You may not remove %type until you have removed all of the %type content.', array('%type' => $this->entity->label())) . '</p>';
$form['#title'] = $this->getQuestion();
$form['description'] = array('#markup' => $caption);
return $form;
}
return parent::buildForm($form, $form_state);
}
开发者ID:anatalsceo,项目名称:en-classe,代码行数:14,代码来源:NodeTypeDeleteConfirm.php
注:本文中的Drupal\Core\Database\Connection类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论