本文整理汇总了PHP中Drupal::state方法的典型用法代码示例。如果您正苦于以下问题:PHP Drupal::state方法的具体用法?PHP Drupal::state怎么用?PHP Drupal::state使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal
的用法示例。
在下文中一共展示了Drupal::state方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getMigrationTemplates
/**
* Sets up the relevant migrations for import from a database connection.
*
* @param array|\Drupal\Core\Database\Database $database
* Database array representing the source Drupal database.
* @param string $source_base_path
* Address of the source Drupal site (e.g., http://example.com/).
*
* @return int[]
* An array of Migration entity IDs.
*
* @throws \Exception
*/
protected function getMigrationTemplates(array $database, $source_base_path)
{
// Set up the connection.
$connection = $this->getConnection($database);
if (!($drupal_version = $this->getLegacyDrupalVersion($connection))) {
throw new \Exception('Source database does not contain a recognizable Drupal version.');
}
$database_state['key'] = 'upgrade';
$database_state['database'] = $database;
$database_state_key = 'migrate_upgrade_' . $drupal_version;
\Drupal::state()->set($database_state_key, $database_state);
$version_tag = 'Drupal ' . $drupal_version;
$template_storage = \Drupal::service('migrate.template_storage');
$migration_templates = $template_storage->findTemplatesByTag($version_tag);
foreach ($migration_templates as $id => $template) {
$migration_templates[$id]['source']['database_state_key'] = $database_state_key;
// Configure file migrations so they can find the files.
if ($template['destination']['plugin'] == 'entity:file') {
if ($source_base_path) {
// Make sure we have a single trailing slash.
$source_base_path = rtrim($source_base_path, '/') . '/';
$migration_templates[$id]['destination']['source_base_path'] = $source_base_path;
}
}
}
return $migration_templates;
}
示例2: testMissingContent
/**
* Tests the missing content event is fired.
*
* @see \Drupal\Core\Config\ConfigImporter::processMissingContent()
* @see \Drupal\config_import_test\EventSubscriber
*/
function testMissingContent()
{
\Drupal::state()->set('config_import_test.config_import_missing_content', TRUE);
// Update a configuration entity in the sync directory to have a dependency
// on two content entities that do not exist.
$storage = $this->container->get('config.storage');
$sync = $this->container->get('config.storage.sync');
$entity_one = entity_create('entity_test', array('name' => 'one'));
$entity_two = entity_create('entity_test', array('name' => 'two'));
$entity_three = entity_create('entity_test', array('name' => 'three'));
$dynamic_name = 'config_test.dynamic.dotted.default';
$original_dynamic_data = $storage->read($dynamic_name);
// Entity one will be resolved by
// \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentOne().
$original_dynamic_data['dependencies']['content'][] = $entity_one->getConfigDependencyName();
// Entity two will be resolved by
// \Drupal\config_import_test\EventSubscriber::onConfigImporterMissingContentTwo().
$original_dynamic_data['dependencies']['content'][] = $entity_two->getConfigDependencyName();
// Entity three will be resolved by
// \Drupal\Core\Config\Importer\FinalMissingContentSubscriber.
$original_dynamic_data['dependencies']['content'][] = $entity_three->getConfigDependencyName();
$sync->write($dynamic_name, $original_dynamic_data);
// Import.
$this->configImporter->reset()->import();
$this->assertEqual([], $this->configImporter->getErrors(), 'There were no errors during the import.');
$this->assertEqual($entity_one->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_one'), 'The missing content event is fired during configuration import.');
$this->assertEqual($entity_two->uuid(), \Drupal::state()->get('config_import_test.config_import_missing_content_two'), 'The missing content event is fired during configuration import.');
$original_dynamic_data = $storage->read($dynamic_name);
$this->assertEqual([$entity_one->getConfigDependencyName(), $entity_two->getConfigDependencyName(), $entity_three->getConfigDependencyName()], $original_dynamic_data['dependencies']['content'], 'The imported configuration entity has the missing content entity dependency.');
}
示例3: setUp
function setUp()
{
parent::setUp();
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Create and login user.
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval'));
$this->drupalLogin($admin_user);
// Add language.
$edit = array('predefined_langcode' => 'fr');
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Set "Article" content type to use multilingual support.
$edit = array('language_configuration[language_show]' => TRUE);
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Enable content language negotiation UI.
\Drupal::state()->set('language_test.content_language_type', TRUE);
// Set interface language detection to user and content language detection
// to URL. Disable inheritance from interface language to ensure content
// language will fall back to the default language if no URL language can be
// detected.
$edit = array('language_interface[enabled][language-user]' => TRUE, 'language_content[enabled][language-url]' => TRUE, 'language_content[enabled][language-interface]' => FALSE);
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Change user language preference, this way interface language is always
// French no matter what path prefix the URLs have.
$edit = array('preferred_langcode' => 'fr');
$this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save'));
// Create comment field on article.
$this->container->get('comment.manager')->addDefaultField('node', 'article');
// Make comment body translatable.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$field_storage->translatable = TRUE;
$field_storage->save();
$this->assertTrue($field_storage->isTranslatable(), 'Comment body is translatable.');
}
示例4: testPostUpdate
/**
* Tests hook_post_update_NAME().
*/
public function testPostUpdate()
{
$this->runUpdates();
$this->assertRaw('<h3>Update first</h3>');
$this->assertRaw('First update');
$this->assertRaw('<h3>Update second</h3>');
$this->assertRaw('Second update');
$this->assertRaw('<h3>Update test1</h3>');
$this->assertRaw('Test1 update');
$this->assertRaw('<h3>Update test0</h3>');
$this->assertRaw('Test0 update');
$this->assertRaw('<h3>Update test_batch</h3>');
$this->assertRaw('Test post update batches');
// Test state value set by each post update.
$updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch-1', 'update_test_postupdate_post_update_test_batch-2', 'update_test_postupdate_post_update_test_batch-3'];
$this->assertIdentical($updates, \Drupal::state()->get('post_update_test_execution', []));
// Test post_update key value stores contains a list of the update functions
// that have run.
$existing_updates = array_count_values(\Drupal::keyValue('post_update')->get('existing_updates'));
$expected_updates = ['update_test_postupdate_post_update_first', 'update_test_postupdate_post_update_second', 'update_test_postupdate_post_update_test1', 'update_test_postupdate_post_update_test0', 'update_test_postupdate_post_update_test_batch'];
foreach ($expected_updates as $expected_update) {
$this->assertEqual($existing_updates[$expected_update], 1, new FormattableMarkup("@expected_update exists in 'existing_updates' key and only appears once.", ['@expected_update' => $expected_update]));
}
$this->drupalGet('update.php/selection');
$this->assertText('No pending updates.');
}
示例5: getSubscribedEvents
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
// Register this listener for every event that is used by a reaction rule.
$events = [];
$callback = ['onRulesEvent', 100];
// If there is no state service there is nothing we can do here. This static
// method could be called early when the container is built, so the state
// service might no always be available.
if (!\Drupal::hasService('state')) {
return [];
}
// Since we cannot access the reaction rule config storage here we have to
// use the state system to provide registered Rules events. The Reaction
// Rule storage is responsible for keeping the registered events up to date
// in the state system.
// @see \Drupal\rules\Entity\ReactionRuleStorage
$state = \Drupal::state();
$registered_event_names = $state->get('rules.registered_events');
if (!empty($registered_event_names)) {
foreach ($registered_event_names as $event_name) {
$events[$event_name][] = $callback;
}
}
return $events;
}
示例6: __construct
/**
* Overrides Mollom::__construct().
*
* This class accounts for multiple scenarios:
* - Straight low-level requests against the testing API from a custom script,
* caring for API keys on its own.
* - Whenever the testing mode is enabled (either through the module's
* settings page or by changing the testing_mode system variable),
* the client requires valid testing API keys to perform any calls. Testing
* API keys are different to production API keys, need to be created first,
* and may vanish at any time (whenever the testing API server is
* redeployed). Since they are different, the class stores them in different
* system variables. Since they can vanish at any time, the class verifies
* the keys upon every instantiation, and automatically creates new testing
* API keys if necessary.
* - Some automated unit tests attempt to verify that authentication errors
* are handled correctly by the class' error handling. The automatic
* creation and recovery of testing API keys would break those assertions,
* so said tests can disable the behavior by preemptively setting
* $createKeys or the 'mollom.testing_create_keys' state variable to FALSE,
* and manually create testing API keys (once).
*
* Constructor.
* @param ConfigFactory $config_factory
* @param ClientInterface $http_client
*
* @see Mollom::__construct().
*/
public function __construct(ConfigFactory $config_factory, ClientInterface $http_client)
{
$this->config = $config_factory->get('mollom.settings');
// Some tests are verifying the production behavior of e.g. setting up API
// keys, in which testing mode is NOT enabled and the test creates fake
// "production" API keys on the local fake server on its own. This special
// override must only be possible when executing tests.
// @todo Add global test_info as condition?
$testing_mode = $this->config->get('test_mode.enabled');
$module_exists = \Drupal::moduleHandler()->moduleExists('mollom_test_server');
if ($module_exists && !$testing_mode) {
// Disable authentication error auto-recovery.
$this->createKeys = FALSE;
} else {
// Do not destroy production variables when testing mode is enabled.
$this->configuration_map['publicKey'] = 'test_mode.keys.public';
$this->configuration_map['privateKey'] = 'test_mode.keys.private';
$this->configuration_map['server'] = 'test_mode.api_endpoint';
}
// Load and set publicKey and privateKey configuration values.
parent::__construct($config_factory, $http_client);
// Unless pre-set, determine whether API keys should be auto-created.
if (!isset($this->createKeys)) {
$this->createKeys = \Drupal::state()->get('mollom.testing_create_keys') ?: TRUE;
}
// Testing can require additional time.
$this->requestTimeout = $this->config->get('connection_timeout_seconds', 3) + 10;
}
示例7: takeSiteOnline
/**
* Take the site online if it was taken offline for this operation.
*/
protected function takeSiteOnline()
{
// Take the site online again.
if ($this->maintenance_mode) {
\Drupal::state()->set('system.maintenance_mode', FALSE);
}
}
示例8: setUp
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->moduleHandler = $this->container->get('module_handler');
$this->projectStorage = $this->container->get('locale.project');
\Drupal::state()->set('locale.remove_core_project', TRUE);
}
示例9: setUp
protected function setUp()
{
parent::setUp();
// Let there be T-rex.
\Drupal::state()->set('editor_test_give_me_a_trex_thanks', TRUE);
\Drupal::service('plugin.manager.editor')->clearCachedDefinitions();
// Add text formats.
$filtered_html_format = entity_create('filter_format', array('format' => 'filtered_html', 'name' => 'Filtered HTML', 'weight' => 0, 'filters' => array()));
$filtered_html_format->save();
$full_html_format = entity_create('filter_format', array('format' => 'full_html', 'name' => 'Full HTML', 'weight' => 1, 'filters' => array()));
$full_html_format->save();
// Create article node type.
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Create page node type, but remove the body.
$this->drupalCreateContentType(array('type' => 'page', 'name' => 'Page'));
$body = FieldConfig::loadByName('node', 'page', 'body');
$body->delete();
// Create a formatted text field, which uses an <input type="text">.
FieldStorageConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text'))->save();
FieldConfig::create(array('field_name' => 'field_text', 'entity_type' => 'node', 'label' => 'Textfield', 'bundle' => 'page'))->save();
entity_get_form_display('node', 'page', 'default')->setComponent('field_text')->save();
// Create 3 users, each with access to different text formats.
$this->untrustedUser = $this->drupalCreateUser(array('create article content', 'edit any article content'));
$this->normalUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'use text format filtered_html'));
$this->privilegedUser = $this->drupalCreateUser(array('create article content', 'edit any article content', 'create page content', 'edit any page content', 'use text format filtered_html', 'use text format full_html'));
}
示例10: testWithBrokenRouting
/**
* Tests running update.php with some form of broken routing.
*/
public function testWithBrokenRouting()
{
// Make sure we can get to the front page.
$this->drupalGet('<front>');
$this->assertResponse(200);
// Simulate a broken router, and make sure the front page is
// inaccessible.
\Drupal::state()->set('update_script_test_broken_inbound', TRUE);
\Drupal::service('cache_tags.invalidator')->invalidateTags(['route_match', 'rendered']);
$this->drupalGet('<front>');
$this->assertResponse(500);
// The exceptions are expected. Do not interpret them as a test failure.
// Not using File API; a potential error must trigger a PHP warning.
unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
foreach ($this->assertions as $key => $assertion) {
if (strpos($assertion['message'], 'core/modules/system/tests/modules/update_script_test/src/PathProcessor/BrokenInboundPathProcessor.php') !== FALSE) {
unset($this->assertions[$key]);
$this->deleteAssert($assertion['message_id']);
}
}
$this->runUpdates();
// Remove the simulation of the broken router, and make sure we can get to
// the front page again.
\Drupal::state()->set('update_script_test_broken_inbound', FALSE);
$this->drupalGet('<front>');
$this->assertResponse(200);
}
示例11: build
/**
* {@inheritdoc}
*/
public function build()
{
$is_admin = \Drupal::service('router.admin_context')->isAdminRoute();
if ($is_admin) {
return [];
}
global $base_url;
$output['#theme'] = "searchblox_frontend_view";
$output['#var1'] = "vars_set_from_module_file";
$output['#type'] = "markup";
$output['#attributes'] = ['class' => ['searchblox-div']];
// Prepare Vars For Setting them in Drupal.Settings
$search_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/SearchServlet' : '';
$auto_suggest_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/AutoSuggest' : '';
$report_servlet_url = searchblox_location() ? searchblox_location() . '/searchblox/servlet/ReportServlet' : '';
$full_plugin_url = searchblox_full_plugin_url();
$collection_ids = array();
$collection_ids = \Drupal::state()->get('searchblox_collection_ids') ? \Drupal::state()->get('searchblox_collection_ids') : '';
$output['#attached']['drupalSettings']["searchblox"]["base_url"] = $base_url;
$output['#attached']['drupalSettings']["searchblox"]["module_url"] = $base_url . "/modules/searchblox";
$output['#attached']['drupalSettings']["searchblox"]["search_url"] = $search_url;
$output['#attached']['drupalSettings']["searchblox"]["auto_suggest_url"] = $auto_suggest_url;
$output['#attached']['drupalSettings']["searchblox"]["report_servlet_url"] = $report_servlet_url;
$output['#attached']['drupalSettings']["searchblox"]["full_plugin_url"] = $full_plugin_url;
$output['#attached']['drupalSettings']["searchblox"]["collection_ids"] = $collection_ids;
// Attach Library
$output['#attached']['library'][] = 'searchblox/searchblox-frontpage';
$this->rendered_content = $output;
return $output;
}
示例12: testValidation
/**
* Test validation.
*/
function testValidation()
{
$state = \Drupal::state();
$path = 'currency_test-form-element-currency-sign';
// Test an empty sign.
$values = array('container[sign][sign]' => '');
$this->drupalPostForm($path, $values, t('Submit'));
$sign = $state->get('currency_test_currency_sign_element');
$this->assertEqual('', $sign);
// Test a suggested sign.
$values = array('container[sign][sign]' => '€');
$this->drupalPostForm($path . '/EUR', $values, t('Submit'));
$sign = $state->get('currency_test_currency_sign_element');
$this->assertEqual('€', $sign);
// Test a custom sign.
$values = array('container[sign][sign]' => CurrencySign::CUSTOM_VALUE, 'container[sign][sign_custom]' => 'foobar');
$this->drupalPostForm($path, $values, t('Submit'));
$sign = $state->get('currency_test_currency_sign_element');
$this->assertEqual('foobar', $sign);
$this->drupalGet($path . '/EUR/foobar');
$this->assertRaw('<option value="' . CurrencySign::CUSTOM_VALUE . '" selected="selected">');
// Check if the sign element is set to a custom value.
$this->assertFieldByXPath("//select[@name='container[sign][sign]']/option[@value='" . CurrencySign::CUSTOM_VALUE . "' and @selected='selected']");
// Check if the custom sign input element has the custom sign as its value.
$this->assertFieldByXPath("//input[@name='container[sign][sign_custom]' and @value='foobar']");
// Test a non-existing currency.
$values = array('container[sign][sign]' => '');
$this->drupalPostForm($path . '/ZZZ', $values, t('Submit'));
$sign = $state->get('currency_test_currency_sign_element');
$this->assertEqual('', $sign);
}
示例13: testFromAndReplyToHeader
/**
* Checks the From: and Reply-to: headers.
*/
public function testFromAndReplyToHeader()
{
$language = \Drupal::languageManager()->getCurrentLanguage();
// Use the state system collector mail backend.
\Drupal::config('system.mail')->set('interface.default', 'test_mail_collector')->save();
// Reset the state variable that holds sent messages.
\Drupal::state()->set('system.test_mail_collector', array());
// Send an email with a reply-to address specified.
$from_email = 'Drupal <simpletest@example.com>';
$reply_email = 'someone_else@example.com';
drupal_mail('simpletest', 'from_test', 'from_test@example.com', $language, array(), $reply_email);
// Test that the reply-to email is just the email and not the site name
// and default sender email.
$captured_emails = \Drupal::state()->get('system.test_mail_collector');
$sent_message = end($captured_emails);
$this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
$this->assertEqual($reply_email, $sent_message['headers']['Reply-to'], 'Message reply-to headers are set.');
$this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
// Send an email and check that the From-header contains the site name.
drupal_mail('simpletest', 'from_test', 'from_test@example.com', $language);
$captured_emails = \Drupal::state()->get('system.test_mail_collector');
$sent_message = end($captured_emails);
$this->assertEqual($from_email, $sent_message['headers']['From'], 'Message is sent from the site email account.');
$this->assertFalse(isset($sent_message['headers']['Reply-to']), 'Message reply-to is not set if not specified.');
$this->assertFalse(isset($sent_message['headers']['Errors-To']), 'Errors-to header must not be set, it is deprecated.');
}
示例14: testRediscover
/**
* Tests the rediscovering.
*/
public function testRediscover()
{
\Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_1' => new Route('/example-path')]);
\Drupal::service('router.builder')->rebuild();
// Set up a custom menu link pointing to a specific path.
MenuLinkContent::create(['title' => '<script>alert("Welcome to the discovered jungle!")</script>', 'link' => [['uri' => 'internal:/example-path']], 'menu_name' => 'tools'])->save();
$menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
$this->assertEqual(1, count($menu_tree));
/** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
$tree_element = reset($menu_tree);
$this->assertEqual('route_name_1', $tree_element->link->getRouteName());
// Change the underlying route and trigger the rediscovering.
\Drupal::state()->set('menu_link_content_dynamic_route.routes', ['route_name_2' => new Route('/example-path')]);
\Drupal::service('router.builder')->rebuild();
// Ensure that the new route name / parameters are captured by the tree.
$menu_tree = \Drupal::menuTree()->load('tools', new MenuTreeParameters());
$this->assertEqual(1, count($menu_tree));
/** @var \Drupal\Core\Menu\MenuLinkTreeElement $tree_element */
$tree_element = reset($menu_tree);
$this->assertEqual('route_name_2', $tree_element->link->getRouteName());
$title = $tree_element->link->getTitle();
$this->assertFalse($title instanceof TranslationWrapper);
$this->assertIdentical('<script>alert("Welcome to the discovered jungle!")</script>', $title);
$this->assertFalse(SafeMarkup::isSafe($title));
}
示例15: setUp
function setUp()
{
parent::setUp();
node_access_rebuild();
node_access_test_add_field(entity_load('node_type', 'forum'));
\Drupal::state()->set('node_access_test.private', TRUE);
}