本文整理汇总了PHP中Drupal::service方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::service方法的具体用法?PHP Drupal::service怎么用?PHP Drupal::service使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::service方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getGlobalContextRepository
/**
* Gets the global context repository.
*
* @return \Drupal\Core\Plugin\Context\ContextRepositoryInterface
* The context repository.
*/
public function getGlobalContextRepository()
{
if (empty($this->contextRepository)) {
$this->contextRepository = \Drupal::service('context.repository');
}
return $this->contextRepository;
}
示例2: nextMail
/**
* {@inheritdoc}
*/
public function nextMail()
{
// Get the current mail spool row and update the internal pointer to the
// next row.
$return = each($this->mails);
// If we're done, return false.
if (!$return) {
return FALSE;
}
$spool_data = $return['value'];
// Store this spool row as processed.
$this->processed[$spool_data->msid] = $spool_data;
$entity = entity_load($spool_data->entity_type, $spool_data->entity_id);
if (!$entity) {
// If the entity load failed, set the processed status done and proceed with
// the next mail.
$this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
return $this->nextMail();
}
if ($spool_data->data) {
$subscriber = $spool_data->data;
} else {
$subscriber = simplenews_subscriber_load_by_mail($spool_data->mail);
}
if (!$subscriber) {
// If loading the subscriber failed, set the processed status done and
// proceed with the next mail.
$this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
return $this->nextMail();
}
$mail = new MailEntity($entity, $subscriber, \Drupal::service('simplenews.mail_cache'));
// Set the langcode langcode.
$this->processed[$spool_data->msid]->langcode = $mail->getEntity()->language()->getId();
return $mail;
}
示例3: testPopularContentBlock
/**
* Tests the "popular content" block.
*/
function testPopularContentBlock()
{
// Clear the block cache to load the Statistics module's block definitions.
$this->container->get('plugin.manager.block')->clearCachedDefinitions();
// Visit a node to have something show up in the block.
$node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $this->blockingUser->id()));
$this->drupalGet('node/' . $node->id());
// Manually calling statistics.php, simulating ajax behavior.
$nid = $node->id();
$post = http_build_query(array('nid' => $nid));
$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
global $base_url;
$stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php';
$client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]);
$client->post($stats_path, array('headers' => $headers, 'body' => $post));
// Configure and save the block.
$this->drupalPlaceBlock('statistics_popular_block', array('label' => 'Popular content', 'top_day_num' => 3, 'top_all_num' => 3, 'top_last_num' => 3));
// Get some page and check if the block is displayed.
$this->drupalGet('user');
$this->assertText('Popular content', 'Found the popular content block.');
$this->assertText("Today's", "Found today's popular content.");
$this->assertText('All time', 'Found the all time popular content.');
$this->assertText('Last viewed', 'Found the last viewed popular content.');
// statistics.module doesn't use node entities, prevent the node language
// from being added to the options.
$this->assertRaw(\Drupal::l($node->label(), $node->urlInfo('canonical', ['language' => NULL])), 'Found link to visited node.');
}
示例4: getLogger
/**
* Gets the logger for a specific channel.
*
* @param string $channel
* The name of the channel. Can be any string, but the general practice is
* to use the name of the subsystem calling this.
*
* @return \Psr\Log\LoggerInterface
* The logger for the given channel.
*
* @todo Require the use of injected services:
* https://www.drupal.org/node/2733703
*/
protected function getLogger($channel)
{
if (!$this->loggerFactory) {
$this->loggerFactory = \Drupal::service('logger.factory');
}
return $this->loggerFactory->get($channel);
}
示例5: testConfigTranslationsExist
/**
* Confirm the config defaults show on the translations page.
*/
public function testConfigTranslationsExist()
{
// Ensure the config shows on the admin form.
$this->drupalGet('admin/config/regional/config-translation');
$this->assertResponse(200);
$this->assertText(t('Metatag defaults'));
// Load the main metatag_defaults config translation page.
$this->drupalGet('admin/config/regional/config-translation/metatag_defaults');
$this->assertResponse(200);
// @todo Update this to confirm the H1 is loaded.
$this->assertRaw(t('Metatag defaults'));
// Load all of the Metatag defaults.
$defaults = \Drupal::configFactory()->listAll('metatag.metatag_defaults');
/** @var \Drupal\Core\Config\ConfigManagerInterface $config_manager */
$config_manager = \Drupal::service('config.manager');
// Confirm each of the configs is available on the translation form.
foreach ($defaults as $config_name) {
if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
$this->assertText($config_entity->label());
}
}
// Confirm that each config translation page can be loaded.
foreach ($defaults as $config_name) {
if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
$this->drupalGet('admin/config/search/metatag/' . $config_entity->id() . '/translate');
$this->assertResponse(200);
} else {
$this->error('Unable to load a Metatag default config: ' . $config_name);
}
}
}
示例6: testUpdateHookN
/**
* Tests that local actions/tasks are being converted into blocks.
*/
public function testUpdateHookN()
{
$this->runUpdates();
/** @var \Drupal\block\BlockInterface $block_storage */
$block_storage = \Drupal::entityManager()->getStorage('block');
/* @var \Drupal\block\BlockInterface[] $help_blocks */
$help_blocks = $block_storage->loadByProperties(['theme' => 'bartik', 'region' => 'help']);
$this->assertRaw('Because your site has custom theme(s) installed, we had to set local actions and tasks blocks into the content region. Please manually review the block configurations and remove the removed variables from your templates.');
// Disable maintenance mode.
// @todo Can be removed once maintenance mode is automatically turned off
// after updates in https://www.drupal.org/node/2435135.
\Drupal::state()->set('system.maintenance_mode', FALSE);
// We finished updating so we can log in the user now.
$this->drupalLogin($this->rootUser);
$page = Node::create(['type' => 'page', 'title' => 'Page node']);
$page->save();
// Ensures that blocks inside help region has been moved to content region.
foreach ($help_blocks as $block) {
$new_block = $block_storage->load($block->id());
$this->assertEqual($new_block->getRegion(), 'content');
}
// Local tasks are visible on the node page.
$this->drupalGet('node/' . $page->id());
$this->assertText(t('Edit'));
// Local actions are visible on the content listing page.
$this->drupalGet('admin/content');
$action_link = $this->cssSelect('.action-links');
$this->assertTrue($action_link);
$this->drupalGet('admin/structure/block/list/seven');
/** @var \Drupal\Core\Config\StorageInterface $config_storage */
$config_storage = \Drupal::service('config.storage');
$this->assertTrue($config_storage->exists('block.block.test_theme_local_tasks'), 'Local task block has been created for the custom theme.');
$this->assertTrue($config_storage->exists('block.block.test_theme_local_actions'), 'Local action block has been created for the custom theme.');
}
示例7: getPluginCollection
/**
* Encapsulates the creation of the action's LazyPluginCollection.
*
* @return \Drupal\Component\Plugin\LazyPluginCollection
* The action's plugin collection.
*/
protected function getPluginCollection()
{
if (!$this->pluginCollection) {
$this->pluginCollection = new ActionPluginCollection(\Drupal::service('plugin.manager.action'), $this->plugin, $this->configuration);
}
return $this->pluginCollection;
}
示例8: testPluginSelection
/**
* Tests that the correct MigrateCckField plugins are used.
*/
public function testPluginSelection()
{
$plugin_manager = \Drupal::service('plugin.manager.migrate.cckfield');
$this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d6\\FileField', get_class($plugin_manager->createInstance('filefield', ['core' => 6])));
try {
// If this test passes, createInstance will raise a
// PluginNotFoundException and we'll never reach fail().
$plugin_manager->createInstance('filefield', ['core' => 7]);
$this->fail('Expected Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException.');
} catch (PluginNotFoundException $e) {
$this->assertIdentical($e->getMessage(), "Plugin ID 'filefield' was not found.");
}
$this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d7\\ImageField', get_class($plugin_manager->createInstance('image', ['core' => 7])));
$this->assertIdentical('Drupal\\file\\Plugin\\migrate\\cckfield\\d7\\FileField', get_class($plugin_manager->createInstance('file', ['core' => 7])));
$this->assertIdentical('Drupal\\migrate_cckfield_plugin_manager_test\\Plugin\\migrate\\cckfield\\D6FileField', get_class($plugin_manager->createInstance('file', ['core' => 6])));
$this->assertIdentical('Drupal\\text\\Plugin\\migrate\\cckfield\\TextField', get_class($plugin_manager->createInstance('text', ['core' => 6])));
$this->assertIdentical('Drupal\\text\\Plugin\\migrate\\cckfield\\TextField', get_class($plugin_manager->createInstance('text', ['core' => 7])));
// Test fallback when no core version is specified.
$this->assertIdentical('Drupal\\migrate_cckfield_plugin_manager_test\\Plugin\\migrate\\cckfield\\D6NoCoreVersionSpecified', get_class($plugin_manager->createInstance('d6_no_core_version_specified', ['core' => 6])));
try {
// If this test passes, createInstance will raise a
// PluginNotFoundException and we'll never reach fail().
$plugin_manager->createInstance('d6_no_core_version_specified', ['core' => 7]);
$this->fail('Expected Drupal\\Component\\Plugin\\Exception\\PluginNotFoundException.');
} catch (PluginNotFoundException $e) {
$this->assertIdentical($e->getMessage(), "Plugin ID 'd6_no_core_version_specified' was not found.");
}
}
示例9: testNodeTokenReplacement
/**
* Creates a node, then tests the tokens generated from it.
*/
function testNodeTokenReplacement()
{
$url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage);
// Create a user and a node.
$account = $this->createUser();
/* @var $node \Drupal\node\NodeInterface */
$node = entity_create('node', array('type' => 'article', 'tnid' => 0, 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'summary' => $this->randomMachineName(16), 'format' => 'plain_text'))));
$node->save();
// Generate and test sanitized tokens.
$tests = array();
$tests['[node:nid]'] = $node->id();
$tests['[node:vid]'] = $node->getRevisionId();
$tests['[node:type]'] = 'article';
$tests['[node:type-name]'] = 'Article';
$tests['[node:title]'] = SafeMarkup::checkPlain($node->getTitle());
$tests['[node:body]'] = $node->body->processed;
$tests['[node:summary]'] = $node->body->summary_processed;
$tests['[node:langcode]'] = SafeMarkup::checkPlain($node->language()->getId());
$tests['[node:url]'] = $node->url('canonical', $url_options);
$tests['[node:edit-url]'] = $node->url('edit-form', $url_options);
$tests['[node:author]'] = SafeMarkup::checkPlain($account->getUsername());
$tests['[node:author:uid]'] = $node->getOwnerId();
$tests['[node:author:name]'] = SafeMarkup::checkPlain($account->getUsername());
$tests['[node:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getCreatedTime(), array('langcode' => $this->interfaceLanguage->getId()));
$tests['[node:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime(), array('langcode' => $this->interfaceLanguage->getId()));
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.');
foreach ($tests as $input => $expected) {
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId()));
$this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[node:title]'] = $node->getTitle();
$tests['[node:body]'] = $node->body->value;
$tests['[node:summary]'] = $node->body->summary;
$tests['[node:langcode]'] = $node->language()->getId();
$tests['[node:author:name]'] = $account->getUsername();
foreach ($tests as $input => $expected) {
$output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId(), 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input)));
}
// Repeat for a node without a summary.
$node = entity_create('node', array('type' => 'article', 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomMachineName(32), 'format' => 'plain_text'))));
$node->save();
// Generate and test sanitized token - use full body as expected value.
$tests = array();
$tests['[node:summary]'] = $node->body->processed;
// Test to make sure that we generated something for each token.
$this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.');
foreach ($tests as $input => $expected) {
$output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage));
$this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input)));
}
// Generate and test unsanitized tokens.
$tests['[node:summary]'] = $node->body->value;
foreach ($tests as $input => $expected) {
$output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage, 'sanitize' => FALSE));
$this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input)));
}
}
示例10: mergeInfoFile
/**
* Merges an info file into a package's info file.
*
* @param string $package_info
* The Yaml encoded package info.
* @param string $info_file_uri
* The info file's URI.
*/
protected function mergeInfoFile($package_info, $info_file_uri)
{
$package_info = Yaml::decode($package_info);
/** @var \Drupal\Core\Extension\InfoParserInterface $existing_info */
$existing_info = \Drupal::service('info_parser')->parse($info_file_uri);
return Yaml::encode($this->featuresManager->mergeInfoArray($existing_info, $package_info));
}
示例11: render
/**
* {@inheritdoc}
*/
public function render(ResultRow $values)
{
$value = parent::render($values);
switch ($value) {
case LocalTaskItemInterface::STATUS_PENDING:
$label = t('Untranslated');
$icon = drupal_get_path('module', 'tmgmt') . '/icons/ready.svg';
break;
case LocalTaskItemInterface::STATUS_COMPLETED:
$label = t('Translated');
$icon = drupal_get_path('module', 'tmgmt') . '/icons/gray-check.svg';
break;
case LocalTaskItemInterface::STATUS_REJECTED:
$label = t('Rejected');
$icon = drupal_get_path('module', 'tmgmt') . '/icons/rejected.svg';
break;
case LocalTaskItemInterface::STATUS_CLOSED:
$label = t('Completed');
$icon = 'core/misc/icons/73b355/check.svg';
break;
default:
$label = t('Untranslated');
$icon = drupal_get_path('module', 'tmgmt') . '/icons/ready.svg';
}
$element = ['#type' => 'inline_template', '#template' => '<img src="{{ icon }}" title="{{ label }}"><span></span></img>', '#context' => array('icon' => file_create_url($icon), 'label' => $label)];
return \Drupal::service('renderer')->render($element);
}
示例12: testUserSelectionByRole
/**
* Tests user selection by roles.
*/
function testUserSelectionByRole()
{
$field_definition = FieldConfig::loadByName('user', 'user', 'user_reference');
$handler_settings = $field_definition->getSetting('handler_settings');
$handler_settings['filter']['role'] = array($this->role1->id() => $this->role1->id(), $this->role2->id() => 0);
$handler_settings['filter']['type'] = 'role';
$field_definition->setSetting('handler_settings', $handler_settings);
$field_definition->save();
$user1 = $this->createUser(array('name' => 'aabb'));
$user1->addRole($this->role1->id());
$user1->save();
$user2 = $this->createUser(array('name' => 'aabbb'));
$user2->addRole($this->role1->id());
$user2->save();
$user3 = $this->createUser(array('name' => 'aabbbb'));
$user3->addRole($this->role2->id());
$user3->save();
/** @var \Drupal\Core\Entity\EntityAutocompleteMatcher $autocomplete */
$autocomplete = \Drupal::service('entity.autocomplete_matcher');
$matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabb');
$this->assertEqual(count($matches), 2);
$users = array();
foreach ($matches as $match) {
$users[] = $match['label'];
}
$this->assertTrue(in_array($user1->label(), $users));
$this->assertTrue(in_array($user2->label(), $users));
$this->assertFalse(in_array($user3->label(), $users));
$matches = $autocomplete->getMatches('user', 'default', $field_definition->getSetting('handler_settings'), 'aabbbb');
$this->assertEqual(count($matches), 0, '');
}
示例13: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->typedConfig = \Drupal::service('config.typed');
$this->blockManager = \Drupal::service('plugin.manager.block');
$this->installEntitySchema('block_content');
}
示例14: assertFieldAccess
/**
* Checks views field access for a given entity type and field name.
*
* To use this method, set up an entity of type $entity_type_id, with field
* $field_name. Create an entity instance that contains content $field_content
* in that field.
*
* This method will check that a user with permission can see the content in a
* view, and a user without access permission on that field cannot.
*
* @param string $entity_type_id
* The entity type ID.
* @param string $field_name
* The field name.
* @param string $field_content
* The expected field content.
*/
protected function assertFieldAccess($entity_type_id, $field_name, $field_content)
{
\Drupal::state()->set('views_field_access_test-field', $field_name);
$entity_type = \Drupal::entityManager()->getDefinition($entity_type_id);
$view_id = $this->randomMachineName();
$data_table = $entity_type->getDataTable();
// Use the data table as long as the field is not 'uuid'. This is the only
// column that can only be obtained from the base table.
$base_table = $data_table && $field_name !== 'uuid' ? $data_table : $entity_type->getBaseTable();
$entity = View::create(['id' => $view_id, 'base_table' => $base_table, 'display' => ['default' => ['display_plugin' => 'default', 'id' => 'default', 'display_options' => ['fields' => [$field_name => ['table' => $base_table, 'field' => $field_name, 'id' => $field_name, 'plugin_id' => 'field']]]]]]);
$entity->save();
/** @var \Drupal\Core\Session\AccountSwitcherInterface $account_switcher */
$account_switcher = \Drupal::service('account_switcher');
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
$account_switcher->switchTo($this->userWithAccess);
$executable = Views::getView($view_id);
$build = $executable->preview();
$this->setRawContent($renderer->renderRoot($build));
$this->assertText($field_content);
$this->assertTrue(isset($executable->field[$field_name]));
$account_switcher->switchTo($this->userWithoutAccess);
$executable = Views::getView($view_id);
$build = $executable->preview();
$this->setRawContent($renderer->renderRoot($build));
$this->assertNoText($field_content);
$this->assertFalse(isset($executable->field[$field_name]));
\Drupal::state()->delete('views_field_access_test-field');
}
示例15: testFeedIconEscaping
/**
* Checks that special characters are correctly escaped.
*
* @see https://www.drupal.org/node/1211668
*/
function testFeedIconEscaping()
{
$variables = array('#theme' => 'feed_icon', '#url' => 'node', '#title' => '<>&"\'');
$text = \Drupal::service('renderer')->renderRoot($variables);
preg_match('/title="(.*?)"/', $text, $matches);
$this->assertEqual($matches[1], 'Subscribe to &"'', 'feed_icon template escapes reserved HTML characters.');
}