public function testRecreateEntity() { $type_name = Unicode::strtolower($this->randomMachineName(16)); $content_type = entity_create('node_type', array('type' => $type_name, 'name' => 'Node type one')); $content_type->save(); node_add_body_field($content_type); /** @var \Drupal\Core\Config\StorageInterface $active */ $active = $this->container->get('config.storage'); /** @var \Drupal\Core\Config\StorageInterface $sync */ $sync = $this->container->get('config.storage.sync'); $config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id(); $this->copyConfig($active, $sync); // Delete the content type. This will also delete a field storage, a field, // an entity view display and an entity form display. $content_type->delete(); $this->assertFalse($active->exists($config_name), 'Content type\'s old name does not exist active store.'); // Recreate with the same type - this will have a different UUID. $content_type = entity_create('node_type', array('type' => $type_name, 'name' => 'Node type two')); $content_type->save(); node_add_body_field($content_type); $this->configImporter->reset(); // A node type, a field, an entity view display and an entity form display // will be recreated. $creates = $this->configImporter->getUnprocessedConfiguration('create'); $deletes = $this->configImporter->getUnprocessedConfiguration('delete'); $this->assertEqual(5, count($creates), 'There are 5 configuration items to create.'); $this->assertEqual(5, count($deletes), 'There are 5 configuration items to delete.'); $this->assertEqual(0, count($this->configImporter->getUnprocessedConfiguration('update')), 'There are no configuration items to update.'); $this->assertIdentical($creates, array_reverse($deletes), 'Deletes and creates contain the same configuration names in opposite orders due to dependencies.'); $this->configImporter->import(); // Verify that there is nothing more to import. $this->assertFalse($this->configImporter->reset()->hasUnprocessedConfigurationChanges()); $content_type = NodeType::load($type_name); $this->assertEqual('Node type one', $content_type->label()); }
/** * Tests configuration renaming. */ public function testConfigurationRename() { $content_type = entity_create('node_type', array('type' => Unicode::strtolower($this->randomName(16)), 'name' => $this->randomName())); $content_type->save(); $staged_type = $content_type->type; $active = $this->container->get('config.storage'); $staging = $this->container->get('config.storage.staging'); $config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id(); // Emulate a staging operation. $this->copyConfig($active, $staging); // Change the machine name of the content type. $content_type->type = Unicode::strtolower($this->randomName(8)); $content_type->save(); $active_type = $content_type->type; $renamed_config_name = $content_type->getEntityType()->getConfigPrefix() . '.' . $content_type->id(); $this->assertTrue($active->exists($renamed_config_name), 'The content type has the new name in the active store.'); $this->assertFalse($active->exists($config_name), "The content type's old name does not exist active store."); $this->configImporter()->reset(); $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('create')), 'There are no configuration items to create.'); $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('delete')), 'There are no configuration items to delete.'); $this->assertEqual(0, count($this->configImporter()->getUnprocessedConfiguration('update')), 'There are no configuration items to update.'); // We expect that changing the machine name of the content type will // rename five configuration entities: the node type, the body field // instance, two entity form displays, and the entity view display. // @see \Drupal\node\Entity\NodeType::postSave() $expected = array('node.type.' . $active_type . '::node.type.' . $staged_type, 'entity.form_display.node.' . $active_type . '.default::entity.form_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.default::entity.view_display.node.' . $staged_type . '.default', 'entity.view_display.node.' . $active_type . '.teaser::entity.view_display.node.' . $staged_type . '.teaser', 'field.instance.node.' . $active_type . '.body::field.instance.node.' . $staged_type . '.body'); $renames = $this->configImporter()->getUnprocessedConfiguration('rename'); $this->assertIdentical($expected, $renames); $this->drupalGet('admin/config/development/configuration'); foreach ($expected as $rename) { $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename); $this->assertText(String::format('!source_name to !target_name', array('!source_name' => $names['old_name'], '!target_name' => $names['new_name']))); // Test that the diff link is present for each renamed item. $href = \Drupal::urlGenerator()->getPathFromRoute('config.diff', array('source_name' => $names['old_name'], 'target_name' => $names['new_name'])); $this->assertLinkByHref($href); $hrefs[$rename] = $href; } // Ensure that the diff works for each renamed item. foreach ($hrefs as $rename => $href) { $this->drupalGet($href); $names = $this->configImporter()->getStorageComparer()->extractRenameNames($rename); $config_entity_type = \Drupal::service('config.manager')->getEntityTypeIdByName($names['old_name']); $entity_type = \Drupal::entityManager()->getDefinition($config_entity_type); $old_id = ConfigEntityStorage::getIDFromConfigName($names['old_name'], $entity_type->getConfigPrefix()); $new_id = ConfigEntityStorage::getIDFromConfigName($names['new_name'], $entity_type->getConfigPrefix()); // Because table columns can be on multiple lines, need to assert a regex // pattern rather than normal text. $id_key = $entity_type->getKey('id'); $text = "{$id_key}: {$old_id}"; $this->assertTextPattern('/\\-\\s+' . preg_quote($text, '/') . '/', "'-{$text}' found."); $text = "{$id_key}: {$new_id}"; $this->assertTextPattern('/\\+\\s+' . preg_quote($text, '/') . '/', "'+{$text}' found."); } // Run the import. $this->drupalPostForm('admin/config/development/configuration', array(), t('Import all')); $this->assertText(t('There are no configuration changes.')); $this->assertFalse(entity_load('node_type', $active_type), 'The content no longer exists with the old name.'); $content_type = entity_load('node_type', $staged_type); $this->assertIdentical($staged_type, $content_type->type); }
/** * Tests that date formats cannot be created with invalid machine names. */ public function testDateFormatsMachineNameAllowedValues() { // Try to create a date format with a not allowed character to test the date // format specific machine name replace pattern. $edit = array('label' => 'Something Not Allowed', 'id' => 'something.bad', 'date_format_pattern' => 'Y-m-d'); $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); $this->assertText(t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".'), 'It is not possible to create a date format with the machine name that has any character other than lowercase letters, digits or underscore.'); // Try to create a date format with the reserved machine name "custom". $edit = array('label' => 'Custom', 'id' => 'custom', 'date_format_pattern' => 'Y-m-d'); $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); $this->assertText(t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".'), 'It is not possible to create a date format with the machine name "custom".'); // Try to create a date format with a machine name, "fallback", that // already exists. $edit = array('label' => 'Fallback', 'id' => 'fallback', 'date_format_pattern' => 'j/m/Y'); $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); $this->assertText(t('The machine-readable name is already in use. It must be unique.'), 'It is not possible to create a date format with the machine name "fallback". It is a built-in format that already exists.'); // Create a date format with a machine name distinct from the previous two. $id = Unicode::strtolower($this->randomMachineName(16)); $edit = array('label' => $this->randomMachineName(16), 'id' => $id, 'date_format_pattern' => 'd/m/Y'); $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); $this->assertText(t('Custom date format added.'), 'It is possible to create a date format with a new machine name.'); // Try to create a date format with same machine name as the previous one. $edit = array('label' => $this->randomMachineName(16), 'id' => $id, 'date_format_pattern' => 'd-m-Y'); $this->drupalPostForm('admin/config/regional/date-time/formats/add', $edit, t('Add format')); $this->assertText(t('The machine-readable name is already in use. It must be unique.'), 'It is not possible to create a new date format with an existing machine name.'); }
/** * Tests configuration options and the site-wide contact form. */ public function testContactStorage() { // Create and login administrative user. $admin_user = $this->drupalCreateUser(array('access site-wide contact form', 'administer contact forms', 'administer users', 'administer account settings', 'administer contact_message fields')); $this->drupalLogin($admin_user); // Create first valid contact form. $mail = '*****@*****.**'; $this->addContactForm($id = Unicode::strtolower($this->randomMachineName(16)), $label = $this->randomMachineName(16), implode(',', array($mail)), '', TRUE, ['send_a_pony' => 1]); $this->assertRaw(t('Contact form %label has been added.', array('%label' => $label))); // Ensure that anonymous can submit site-wide contact form. user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array('access site-wide contact form')); $this->drupalLogout(); $this->drupalGet('contact'); $this->assertText(t('Your email address')); $this->assertNoText(t('Form')); $this->submitContact($name = $this->randomMachineName(16), $mail, $subject = $this->randomMachineName(16), $id, $message = $this->randomMachineName(64)); $this->assertText(t('Your message has been sent.')); $messages = Message::loadMultiple(); /** @var \Drupal\contact\Entity\Message $message */ $message = reset($messages); $this->assertEqual($message->getContactForm()->id(), $id); $this->assertTrue($message->getContactForm()->getThirdPartySetting('contact_storage_test', 'send_a_pony', FALSE)); $this->assertEqual($message->getSenderName(), $name); $this->assertEqual($message->getSubject(), $subject); $this->assertEqual($message->getSenderMail(), $mail); $config = $this->config("contact.form.{$id}"); $this->assertEqual($config->get('id'), $id); }
/** * Tests term language settings for vocabulary terms are saved and updated. */ function testVocabularyDefaultLanguageForTerms() { // Add a new vocabulary and check that the default language settings are for // the terms are saved. $edit = array('name' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'default_language[langcode]' => 'bb', 'default_language[language_alterable]' => TRUE); $vid = $edit['vid']; $this->drupalPostForm('admin/structure/taxonomy/add', $edit, t('Save')); // Check that the vocabulary was actually created. $this->drupalGet('admin/structure/taxonomy/manage/' . $edit['vid']); $this->assertResponse(200, 'The vocabulary has been created.'); // Check that the language settings were saved. $language_settings = ContentLanguageSettings::loadByEntityTypeBundle('taxonomy_term', $edit['vid']); $this->assertEqual($language_settings->getDefaultLangcode(), 'bb', 'The langcode was saved.'); $this->assertTrue($language_settings->isLanguageAlterable(), 'The visibility setting was saved.'); // Check that the correct options are selected in the interface. $this->assertOptionSelected('edit-default-language-langcode', 'bb', 'The correct default language for the terms of this vocabulary is selected.'); $this->assertFieldChecked('edit-default-language-language-alterable', 'Show language selection option is checked.'); // Edit the vocabulary and check that the new settings are updated. $edit = array('default_language[langcode]' => 'aa', 'default_language[language_alterable]' => FALSE); $this->drupalPostForm('admin/structure/taxonomy/manage/' . $vid, $edit, t('Save')); // And check again the settings and also the interface. $language_settings = ContentLanguageSettings::loadByEntityTypeBundle('taxonomy_term', $vid); $this->assertEqual($language_settings->getDefaultLangcode(), 'aa', 'The langcode was saved.'); $this->assertFalse($language_settings->isLanguageAlterable(), 'The visibility setting was saved.'); $this->drupalGet('admin/structure/taxonomy/manage/' . $vid); $this->assertOptionSelected('edit-default-language-langcode', 'aa', 'The correct default language for the terms of this vocabulary is selected.'); $this->assertNoFieldChecked('edit-default-language-language-alterable', 'Show language selection option is not checked.'); // Check that language settings are changed after editing vocabulary. $edit = array('name' => $this->randomMachineName(), 'default_language[langcode]' => 'authors_default', 'default_language[language_alterable]' => FALSE); $this->drupalPostForm('admin/structure/taxonomy/manage/' . $vid, $edit, t('Save')); // Check that we have the new settings. $new_settings = ContentLanguageSettings::loadByEntityTypeBundle('taxonomy_term', $vid); $this->assertEqual($new_settings->getDefaultLangcode(), 'authors_default', 'The langcode was saved.'); $this->assertFalse($new_settings->isLanguageAlterable(), 'The new visibility setting was saved.'); }
protected function setUp() { parent::setUp(); $this->installEntitySchema('taxonomy_term'); // We want an entity reference field. It needs a vocabulary, terms, a field // storage and a field. First, create the vocabulary. $vocabulary = entity_create('taxonomy_vocabulary', array('vid' => Unicode::strtolower($this->randomMachineName()))); $vocabulary->save(); // Second, create the field. entity_test_create_bundle('test_bundle'); $this->fieldName = strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('entity_test', 'test_bundle', $this->fieldName, NULL, 'taxonomy_term', 'default', $handler_settings); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'vid' => $vocabulary->id())); $term->save(); $this->terms[] = $term; $this->accounts[] = $this->createUser(); } // Create three entity_test entities, the 0th entity will point to the // 0th account and 0th term, the 1st and 2nd entity will point to the // 1st account and 1st term. for ($i = 0; $i <= 2; $i++) { $entity = entity_create('entity_test', array('type' => 'test_bundle')); $entity->name->value = $this->randomMachineName(); $index = $i ? 1 : 0; $entity->user_id->target_id = $this->accounts[$index]->id(); $entity->{$this->fieldName}->target_id = $this->terms[$index]->id(); $entity->save(); $this->entities[] = $entity; } $this->factory = \Drupal::service('entity.query'); }
/** * Tests the creation of a server and an index. */ public function testServerAndIndexCreation() { // Test whether a newly created server appears on the overview page. $server = $this->getTestServer(); $this->drupalGet($this->overviewPageUrl); $this->assertText($server->label(), 'Server present on overview page.'); $this->assertRaw($server->get('description'), 'Description is present'); $this->assertFieldByXPath('//tr[contains(@class,"' . Html::cleanCssIdentifier($server->getEntityTypeId() . '-' . $server->id()) . '") and contains(@class, "search-api-list-enabled")]', NULL, 'Server is in proper table'); // Test whether a newly created index appears on the overview page. $index = $this->getTestIndex(); $this->drupalGet($this->overviewPageUrl); $this->assertText($index->label(), 'Index present on overview page.'); $this->assertRaw($index->get('description'), 'Index description is present'); $this->assertFieldByXPath('//tr[contains(@class,"' . Html::cleanCssIdentifier($index->getEntityTypeId() . '-' . $index->id()) . '") and contains(@class, "search-api-list-enabled")]', NULL, 'Index is in proper table'); // Test that an entity without bundles can be used as data source. // @todo Why is this here? This hasn't got anything to do with the overview. $edit = array( 'name' => $this->randomMachineName(), 'id' => Unicode::strtolower($this->randomMachineName()), 'datasources[]' => 'entity:user', ); $this->drupalPostForm('admin/config/search/search-api/add-index', $edit, $this->t('Save')); $this->assertText($this->t('The index was successfully saved.')); $this->assertText($edit['name']); }
/** * Test Pathauto cleanup in File (Field) Paths. */ public function testPathauto() { // Create a File field. $field_name = Unicode::strtolower($this->randomMachineName()); $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]'; $third_party_settings['filefield_paths']['file_path']['options']['pathauto'] = TRUE; $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]'; $third_party_settings['filefield_paths']['file_name']['options']['pathauto'] = TRUE; $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings); // Create a node with a test file. /** @var \Drupal\file\Entity\File $test_file */ $test_file = $this->getTestFile('text'); $edit['title[0][value]'] = $this->randomString() . ' ' . $this->randomString(); $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system') ->realpath($test_file->getFileUri()); $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish')); // Ensure that file path/name have been processed correctly by Pathauto. /** @var \Drupal\node\Entity\Node $node */ $node = Node::load(1); $parts = explode('/', $node->getTitle()); foreach ($parts as &$part) { $part = \Drupal::service('pathauto.alias_cleaner')->cleanString($part); } $title = implode('/', $parts); $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/{$title}/{$title}.txt", $this->t('File path/name has been processed correctly by Pathauto')); }
/** * Test Transliteration cleanup in File (Field) Paths. */ public function testTransliteration() { // Create a File field. $field_name = Unicode::strtolower($this->randomMachineName()); $third_party_settings['filefield_paths']['file_path']['value'] = 'node/[node:title]'; $third_party_settings['filefield_paths']['file_path']['options']['transliterate'] = TRUE; $third_party_settings['filefield_paths']['file_name']['value'] = '[node:title].[file:ffp-extension-original]'; $third_party_settings['filefield_paths']['file_name']['options']['transliterate'] = TRUE; $this->createFileField($field_name, 'node', $this->contentType, [], [], $third_party_settings); // Create a node with a test file. /** @var \Drupal\file\Entity\File $test_file */ $test_file = $this->getTestFile('text'); $edit['title[0][value]'] = 'тест'; $edit['files[' . $field_name . '_0]'] = \Drupal::service('file_system') ->realpath($test_file->getFileUri()); $this->drupalPostForm("node/add/{$this->contentType}", $edit, $this->t('Save and publish')); // Get created Node ID. $matches = []; preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches); $nid = $matches[1]; // Ensure that file path/name have been processed correctly by // Transliteration. $node = Node::load($nid); $this->assertEqual($node->{$field_name}[0]->entity->getFileUri(), "public://node/test/test.txt", $this->t('File path/name has been processed correctly by Transliteration')); }
/** * Provides propose forms for various RDF entities. * * This is used for the propose form of collections and solutions. * * @param \Drupal\rdf_entity\RdfEntityTypeInterface $rdf_type * The RDF bundle entity for which to generate the propose form. * * @return array * A render array for the propose form. * * @throws \Exception * Thrown when an attempt is made to propose an rdf_entity that is not a * solution or a collection. */ public function proposeRdfEntity(RdfEntityTypeInterface $rdf_type) { $rdf_entity = $this->entityTypeManager()->getStorage('rdf_entity')->create(array('rid' => $rdf_type->id())); $form = $this->entityFormBuilder()->getForm($rdf_entity, 'propose'); $form['#title'] = $this->t('Propose @type', ['@type' => Unicode::strtolower($rdf_type->label())]); return $form; }
/** * {@inheritdoc} */ public function preprocessIndexValue($value, $type = 'text') { if ($type == 'text') { return $value; } return Unicode::strtolower($this->transliterator->transliterate($value)); }
/** * Test ID validation and the proper video display of a valid ID. */ public function testVideo() { $field_name = Unicode::strtolower($this->randomMachineName()); // Create a field. $field_storage = entity_create('field_storage_config', array('field_name' => $field_name, 'entity_type' => 'node', 'translatable' => FALSE, 'type' => 'youtube', 'cardinality' => '1')); $field_storage->save(); $field = entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => 'article', 'title' => DRUPAL_DISABLED)); $field->save(); entity_get_form_display('node', 'article', 'default')->setComponent($field_name, array('type' => 'youtube', 'settings' => array()))->save(); entity_get_display('node', 'article', 'full')->setComponent($field_name, array('type' => 'youtube_video'))->save(); // Display creation form. $this->drupalGet('node/add/article'); $this->assertFieldByName("{$field_name}[0][input]", '', t('Video input field is displayed')); // Verify that a valid URL can be submitted. $video_id = 'T5y3dJYHb_A'; $value = 'http://www.youtube.com/watch?v=' . $video_id; $embed_value = 'http://www.youtube.com/embed/' . $video_id; $edit = array("title[0][value]" => 'Test', "{$field_name}[0][input]" => $value); $this->drupalPostForm(NULL, $edit, t('Save and publish')); preg_match('|/node/(\\d+)|', $this->url, $match); $this->assertText(t('Article Test has been created.')); $this->assertRaw($embed_value); // Verify that the video is displayed. $pattern = '<iframe.*src="' . $embed_value; $pattern = str_replace('/', '\\/', $pattern); $pattern = '/' . $pattern . '/s'; $this->assertPattern($pattern); // Verify that invalid URLs cannot be submitted. $this->drupalGet('node/add/article'); $value = 'not-a-url'; $edit = array("title[0][value]" => 'Test1', "{$field_name}[0][input]" => $value); $this->drupalPostForm(NULL, $edit, t('Save and publish')); $this->assertText(t('Please provide a valid YouTube URL.')); }
/** * {@inheritdoc} */ protected function process(&$value) { // We don't touch integers, NULL values or the like. if (is_string($value)) { $value = Unicode::strtolower($value); } }
/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { $bundles = $constraint->bundles; if (!($item = $items->first())) { return; } $field_name = $items->getFieldDefinition()->getName(); /** @var \Drupal\Core\Entity\EntityInterface $entity */ $entity = $items->getEntity(); $bundle = $entity->bundle(); if (!in_array($bundle, $bundles)) { // The constraint does not apply to this bundle. return; } $bundle_key = $entity->getEntityType()->getKey('bundle'); $entity_type_id = $entity->getEntityTypeId(); $id_key = $entity->getEntityType()->getKey('id'); $query = \Drupal::entityQuery($entity_type_id)->condition($field_name, $item->value)->condition($bundle_key, $bundles, 'IN'); if (!empty($entity->id())) { $query->condition($id_key, $items->getEntity()->id(), '<>'); } $value_taken = (bool) $query->range(0, 1)->count()->execute(); if ($value_taken) { $this->context->addViolation($constraint->message, ['%value' => $item->value, '@entity_type' => $entity->getEntityType()->getLowercaseLabel(), '@field_name' => Unicode::strtolower($items->getFieldDefinition()->getLabel())]); } }
protected function setUp() { parent::setUp(); $this->installEntitySchema('taxonomy_term'); // We want a taxonomy term reference field. It needs a vocabulary, terms, // a field storage and a field. First, create the vocabulary. $vocabulary = entity_create('taxonomy_vocabulary', array('vid' => Unicode::strtolower($this->randomMachineName()))); $vocabulary->save(); // Second, create the field. $this->fieldName = strtolower($this->randomMachineName()); entity_create('field_storage_config', array('field_name' => $this->fieldName, 'entity_type' => 'entity_test', 'type' => 'taxonomy_term_reference', 'settings' => array('allowed_values' => array(array('vocabulary' => $vocabulary->id())))))->save(); entity_test_create_bundle('test_bundle'); // Third, create the instance. entity_create('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldName, 'bundle' => 'test_bundle'))->save(); // Create two terms and also two accounts. for ($i = 0; $i <= 1; $i++) { $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'vid' => $vocabulary->id())); $term->save(); $this->terms[] = $term; $this->accounts[] = $this->createUser(); } // Create three entity_test entities, the 0th entity will point to the // 0th account and 0th term, the 1st and 2nd entity will point to the // 1st account and 1st term. for ($i = 0; $i <= 2; $i++) { $entity = entity_create('entity_test', array('type' => 'test_bundle')); $entity->name->value = $this->randomMachineName(); $index = $i ? 1 : 0; $entity->user_id->target_id = $this->accounts[$index]->id(); $entity->{$this->fieldName}->target_id = $this->terms[$index]->id(); $entity->save(); $this->entities[] = $entity; } $this->factory = \Drupal::service('entity.query'); }
/** * {@inheritdoc} */ public function assignPackages($force = FALSE) { $current_bundle = $this->assigner->getBundle(); $settings = $current_bundle->getAssignmentSettings($this->getPluginId()); $config_base_types = $settings['types']['config']; $config_types = $this->featuresManager->listConfigTypes(); $config_collection = $this->featuresManager->getConfigCollection(); foreach ($config_collection as $item_name => $item) { if (in_array($item->getType(), $config_base_types)) { if (is_null($this->featuresManager->findPackage($item->getShortName())) && !$item->getPackage()) { $description = $this->t('Provides @label @type and related configuration.', array('@label' => $item->getLabel(), '@type' => Unicode::strtolower($config_types[$item->getType()]))); if (isset($item->getData()['description'])) { $description .= ' ' . $item->getData()['description']; } $this->featuresManager->initPackage($item->getShortName(), $item->getLabel(), $description, 'module', $current_bundle); // Update list with the package we just added. try { $this->featuresManager->assignConfigPackage($item->getShortName(), [$item_name]); } catch (\Exception $exception) { \Drupal::logger('features')->error($exception->getMessage()); } $this->featuresManager->assignConfigDependents([$item_name]); } } } $entity_types = $this->entityManager->getDefinitions(); $content_base_types = $settings['types']['content']; foreach ($content_base_types as $entity_type_id) { if (!isset($packages[$entity_type_id]) && isset($entity_types[$entity_type_id])) { $label = $entity_types[$entity_type_id]->getLabel(); $description = $this->t('Provide @label related configuration.', array('@label' => $label)); $this->featuresManager->initPackage($entity_type_id, $label, $description, 'module', $current_bundle); } } }
/** * Tests configuration renaming validation. */ public function testRenameValidation() { // Create a test entity. $test_entity_id = $this->randomMachineName(); $test_entity = entity_create('config_test', array('id' => $test_entity_id, 'label' => $this->randomMachineName())); $test_entity->save(); $uuid = $test_entity->uuid(); // Stage the test entity and then delete it from the active storage. $active = $this->container->get('config.storage'); $sync = $this->container->get('config.storage.sync'); $this->copyConfig($active, $sync); $test_entity->delete(); // Create a content type with a matching UUID in the active storage. $content_type = entity_create('node_type', array('type' => Unicode::strtolower($this->randomMachineName(16)), 'name' => $this->randomMachineName(), 'uuid' => $uuid)); $content_type->save(); // Confirm that the staged configuration is detected as a rename since the // UUIDs match. $this->configImporter->reset(); $expected = array('node.type.' . $content_type->id() . '::config_test.dynamic.' . $test_entity_id); $renames = $this->configImporter->getUnprocessedConfiguration('rename'); $this->assertIdentical($expected, $renames); // Try to import the configuration. We expect an exception to be thrown // because the staged entity is of a different type. try { $this->configImporter->import(); $this->fail('Expected ConfigImporterException thrown when a renamed configuration entity does not match the existing entity type.'); } catch (ConfigImporterException $e) { $this->pass('Expected ConfigImporterException thrown when a renamed configuration entity does not match the existing entity type.'); $expected = array(SafeMarkup::format('Entity type mismatch on rename. @old_type not equal to @new_type for existing configuration @old_name and staged configuration @new_name.', array('@old_type' => 'node_type', '@new_type' => 'config_test', '@old_name' => 'node.type.' . $content_type->id(), '@new_name' => 'config_test.dynamic.' . $test_entity_id))); $this->assertEqual($expected, $this->configImporter->getErrors()); } }
/** * Verifies that strings of CJK characters are tokenized. * * The search_simplify() function does special things with numbers, symbols, * and punctuation. So we only test that CJK characters that are not in these * character classes are tokenized properly. See PREG_CLASS_CKJ for more * information. */ function testTokenizer() { // Set the minimum word size to 1 (to split all CJK characters) and make // sure CJK tokenizing is turned on. $this->config('search.settings')->set('index.minimum_word_size', 1)->set('index.overlap_cjk', TRUE)->save(); $this->refreshVariables(); // Create a string of CJK characters from various character ranges in // the Unicode tables. // Beginnings of the character ranges. $starts = array('CJK unified' => 0x4e00, 'CJK Ext A' => 0x3400, 'CJK Compat' => 0xf900, 'Hangul Jamo' => 0x1100, 'Hangul Ext A' => 0xa960, 'Hangul Ext B' => 0xd7b0, 'Hangul Compat' => 0x3131, 'Half non-punct 1' => 0xff21, 'Half non-punct 2' => 0xff41, 'Half non-punct 3' => 0xff66, 'Hangul Syllables' => 0xac00, 'Hiragana' => 0x3040, 'Katakana' => 0x30a1, 'Katakana Ext' => 0x31f0, 'CJK Reserve 1' => 0x20000, 'CJK Reserve 2' => 0x30000, 'Bomofo' => 0x3100, 'Bomofo Ext' => 0x31a0, 'Lisu' => 0xa4d0, 'Yi' => 0xa000); // Ends of the character ranges. $ends = array('CJK unified' => 0x9fcf, 'CJK Ext A' => 0x4dbf, 'CJK Compat' => 0xfaff, 'Hangul Jamo' => 0x11ff, 'Hangul Ext A' => 0xa97f, 'Hangul Ext B' => 0xd7ff, 'Hangul Compat' => 0x318e, 'Half non-punct 1' => 0xff3a, 'Half non-punct 2' => 0xff5a, 'Half non-punct 3' => 0xffdc, 'Hangul Syllables' => 0xd7af, 'Hiragana' => 0x309f, 'Katakana' => 0x30ff, 'Katakana Ext' => 0x31ff, 'CJK Reserve 1' => 0x2fffd, 'CJK Reserve 2' => 0x3fffd, 'Bomofo' => 0x312f, 'Bomofo Ext' => 0x31b7, 'Lisu' => 0xa4fd, 'Yi' => 0xa48f); // Generate characters consisting of starts, midpoints, and ends. $chars = array(); $charcodes = array(); foreach ($starts as $key => $value) { $charcodes[] = $starts[$key]; $chars[] = $this->code2utf($starts[$key]); $mid = round(0.5 * ($starts[$key] + $ends[$key])); $charcodes[] = $mid; $chars[] = $this->code2utf($mid); $charcodes[] = $ends[$key]; $chars[] = $this->code2utf($ends[$key]); } // Merge into a string and tokenize. $string = implode('', $chars); $out = trim(search_simplify($string)); $expected = Unicode::strtolower(implode(' ', $chars)); // Verify that the output matches what we expect. $this->assertEqual($out, $expected, 'CJK tokenizer worked on all supplied CJK characters'); }
/** * Helper function for testTextfieldWidgets(). */ function _testTextfieldWidgets($field_type, $widget_type) { // Create a field. $field_name = Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => $field_type)); $field_storage->save(); FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'entity_test', 'label' => $this->randomMachineName() . '_label'])->save(); entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => $widget_type, 'settings' => array('placeholder' => 'A placeholder on ' . $widget_type)))->save(); entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name)->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed'); $this->assertNoFieldByName("{$field_name}[0][format]", '1', 'Format selector is not displayed'); $this->assertRaw(format_string('placeholder="A placeholder on @widget_type"', array('@widget_type' => $widget_type))); // Submit with some value. $value = $this->randomMachineName(); $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created'); // Display the entity. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent(\Drupal::service('renderer')->renderRoot($content)); $this->assertText($value, 'Filtered tags are not displayed'); }
protected function setUp() { parent::setUp(); $this->addDefaultCommentField('node', 'page'); $web_user = $this->drupalCreateUser(array('edit own page content', 'create page content')); $this->drupalLogin($web_user); // Add a vocabulary so we can test different view modes. $vocabulary = entity_create('taxonomy_vocabulary', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->randomMachineName(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'help' => '')); $vocabulary->save(); $this->vocabulary = $vocabulary; // Add a term to the vocabulary. $term = entity_create('taxonomy_term', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => $this->vocabulary->id(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED)); $term->save(); $this->term = $term; // Create an image field. FieldStorageConfig::create(['field_name' => 'field_image', 'entity_type' => 'node', 'type' => 'image', 'settings' => [], 'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED])->save(); $field_config = FieldConfig::create(['field_name' => 'field_image', 'label' => 'Images', 'entity_type' => 'node', 'bundle' => 'page', 'required' => FALSE, 'settings' => []]); $field_config->save(); // Create a field. $this->fieldName = Unicode::strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($this->vocabulary->id() => $this->vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('node', 'page', $this->fieldName, 'Tags', 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); entity_get_form_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_autocomplete_tags'))->save(); // Show on default display and teaser. entity_get_display('node', 'page', 'default')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_display('node', 'page', 'teaser')->setComponent($this->fieldName, array('type' => 'entity_reference_label'))->save(); entity_get_form_display('node', 'page', 'default')->setComponent('field_image', array('type' => 'image_image', 'settings' => []))->save(); entity_get_display('node', 'page', 'default')->setComponent('field_image')->save(); }
/** * Tests email field. */ function testEmailField() { // Create a field with settings to validate. $field_name = Unicode::strtolower($this->randomMachineName()); $this->fieldStorage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'entity_test', 'type' => 'email')); $this->fieldStorage->save(); $this->field = FieldConfig::create(['field_storage' => $this->fieldStorage, 'bundle' => 'entity_test']); $this->field->save(); // Create a form display for the default form mode. entity_get_form_display('entity_test', 'entity_test', 'default')->setComponent($field_name, array('type' => 'email_default', 'settings' => array('placeholder' => '*****@*****.**')))->save(); // Create a display for the full view mode. entity_get_display('entity_test', 'entity_test', 'full')->setComponent($field_name, array('type' => 'email_mailto'))->save(); // Display creation form. $this->drupalGet('entity_test/add'); $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget found.'); $this->assertRaw('placeholder="*****@*****.**"'); // Submit a valid email address and ensure it is accepted. $value = '*****@*****.**'; $edit = array("{$field_name}[0][value]" => $value); $this->drupalPostForm(NULL, $edit, t('Save')); preg_match('|entity_test/manage/(\\d+)|', $this->url, $match); $id = $match[1]; $this->assertText(t('entity_test @id has been created.', array('@id' => $id))); $this->assertRaw($value); // Verify that a mailto link is displayed. $entity = EntityTest::load($id); $display = entity_get_display($entity->getEntityTypeId(), $entity->bundle(), 'full'); $content = $display->build($entity); $this->setRawContent(\Drupal::service('renderer')->renderRoot($content)); $this->assertLinkByHref('mailto:test@example.com'); }
function addTerm($vocabulary, array $term = array()) { $term += array('name' => Unicode::strtolower($this->randomMachineName(5)), 'vid' => $vocabulary->id()); $term = entity_create('taxonomy_term', $term); $term->save(); return $term; }
/** * Autocomplete the label of an entity. * * @param \Symfony\Component\HttpFoundation\Request $request * The request object that contains the typed tags. * @param string $target_type * The ID of the target entity type. * @param string $selection_handler * The plugin ID of the entity reference selection handler. * @param string $selection_settings_key * The hashed key of the key/value entry that holds the selection handler * settings. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The matched entity labels as a JSON response. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * Thrown if the selection settings key is not found in the key/value store * or if it does not match the stored data. */ public function handleAutocomplete(Request $request, $target_type, $selection_handler, $selection_settings_key) { $matches = array(); // Get the typed string from the URL, if it exists. if ($input = $request->query->get('q')) { $typed_string = Tags::explode($input); $typed_string = Unicode::strtolower(array_pop($typed_string)); // Selection settings are passed in as a hashed key of a serialized array // stored in the key/value store. $selection_settings = $this->keyValue->get($selection_settings_key, FALSE); if ($selection_settings !== FALSE) { $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt()); if ($selection_settings_hash !== $selection_settings_key) { // Disallow access when the selection settings hash does not match the // passed-in key. throw new AccessDeniedHttpException('Invalid selection settings key.'); } } else { // Disallow access when the selection settings key is not found in the // key/value store. throw new AccessDeniedHttpException(); } $matches = $this->matcher->getMatches($target_type, $selection_handler, $selection_settings, $typed_string); } return new JsonResponse($matches); }
protected function setUp() { parent::setUp(); $this->drupalPlaceBlock('page_title_block'); $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); // Create a user who can administer text formats, but does not have // specific permission to use any of them. $this->filterAdminUser = $this->drupalCreateUser(array('administer filters', 'create page content', 'edit any page content')); // Create three text formats. Two text formats are created for all users so // that the drop-down list appears for all tests. $this->drupalLogin($this->filterAdminUser); $formats = array(); for ($i = 0; $i < 3; $i++) { $edit = array('format' => Unicode::strtolower($this->randomMachineName()), 'name' => $this->randomMachineName()); $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration')); $this->resetFilterCaches(); $formats[] = FilterFormat::load($edit['format']); } list($this->allowedFormat, $this->secondAllowedFormat, $this->disallowedFormat) = $formats; $this->drupalLogout(); // Create a regular user with access to two of the formats. $this->webUser = $this->drupalCreateUser(array('create page content', 'edit any page content', $this->allowedFormat->getPermissionName(), $this->secondAllowedFormat->getPermissionName())); // Create an administrative user who has access to use all three formats. $this->adminUser = $this->drupalCreateUser(array('administer filters', 'create page content', 'edit any page content', $this->allowedFormat->getPermissionName(), $this->secondAllowedFormat->getPermissionName(), $this->disallowedFormat->getPermissionName())); $this->drupalPlaceBlock('local_tasks_block'); }
/** * {@inheritdoc} */ public function assignPackages($force = FALSE) { $current_bundle = $this->assigner->getBundle(); $settings = $current_bundle->getAssignmentSettings(self::METHOD_ID); $config_base_types = $settings['types']['config']; $config_types = $this->featuresManager->listConfigTypes(); $config_collection = $this->featuresManager->getConfigCollection(); foreach ($config_collection as $item_name => $item) { if (in_array($item['type'], $config_base_types)) { if (!isset($packages[$item['name_short']]) && !isset($item['package'])) { $description = $this->t('Provide @label @type and related configuration.', array('@label' => $item['label'], '@type' => Unicode::strtolower($config_types[$item['type']]))); if (isset($item['data']['description'])) { $description .= ' ' . $item['data']['description']; } $this->featuresManager->initPackage($item['name_short'], $item['label'], $description); try { $this->featuresManager->assignConfigPackage($item['name_short'], [$item_name]); } catch (\Exception $exception) { \Drupal::logger('features')->error($exception->getMessage()); } $this->featuresManager->assignConfigDependents([$item_name]); } } } $entity_types = $this->entityManager->getDefinitions(); $content_base_types = $settings['types']['content']; foreach ($content_base_types as $entity_type_id) { if (!isset($packages[$entity_type_id]) && isset($entity_types[$entity_type_id])) { $label = $entity_types[$entity_type_id]->getLabel(); $description = $this->t('Provide @label related configuration.', array('@label' => $label)); $this->featuresManager->initPackage($entity_type_id, $label, $description); } } }
/** * Tests the calculateDependencies method. */ public function testCalculateDependencies() { $comment_type = entity_create('comment_type', array('id' => 'comment', 'label' => 'Comment settings', 'description' => 'Comment settings', 'target_entity_type_id' => 'node')); $comment_type->save(); $content_type = entity_create('node_type', array('type' => $this->randomMachineName(), 'name' => $this->randomString())); $content_type->save(); $field_storage = entity_create('field_storage_config', array('field_name' => Unicode::strtolower($this->randomMachineName()), 'entity_type' => 'node', 'type' => 'comment')); $field_storage->save(); entity_create('field_config', array('field_storage' => $field_storage, 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_label', 'description' => $this->randomMachineName() . '_description', 'settings' => array('comment_type' => $comment_type->id())))->save(); entity_create('field_config', array('field_storage' => FieldStorageConfig::loadByName('node', 'body'), 'bundle' => $content_type->id(), 'label' => $this->randomMachineName() . '_body', 'settings' => array('display_summary' => TRUE)))->save(); $expected = []; $expected['test_field_get_entity'] = ['module' => ['comment', 'node', 'user']]; // Tests dependencies of relationships. $expected['test_relationship_dependency'] = ['module' => ['comment', 'node', 'user']]; $expected['test_plugin_dependencies'] = ['module' => ['comment', 'views_test_data'], 'content' => ['RowTest', 'StaticTest', 'StyleTest']]; $expected['test_argument_dependency'] = ['config' => ['core.entity_view_mode.node.teaser', 'field.storage.node.body'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['node', 'search', 'text', 'user']]; foreach ($this::$testViews as $view_id) { $view = Views::getView($view_id); $dependencies = $view->calculateDependencies(); $this->assertEqual($expected[$view_id], $dependencies); $config = $this->config('views.view.' . $view_id); \Drupal::service('config.storage.staging')->write($view_id, $config->get()); } // Ensure that dependencies are calculated on the display level. $expected_display['default'] = ['config' => ['core.entity_view_mode.node.teaser'], 'content' => ['ArgumentDefaultTest', 'ArgumentValidatorTest'], 'module' => ['core', 'node', 'search', 'user', 'views']]; $expected_display['page'] = ['config' => ['field.storage.node.body'], 'module' => ['core', 'text', 'views']]; $view = Views::getView('test_argument_dependency'); $view->initDisplay(); foreach ($view->displayHandlers as $display) { // Calculate the dependencies each display has. $this->assertEqual($expected_display[$display->getPluginId()], $display->calculateDependencies()); } }
/** * Returns a new vocabulary with random properties. */ function createVocabulary() { // Create a vocabulary. $vocabulary = entity_create('taxonomy_vocabulary', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'weight' => mt_rand(0, 10))); $vocabulary->save(); return $vocabulary; }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->installConfig(['system']); $this->installConfig(['field']); $this->installConfig(['text']); $this->installConfig(['address']); $this->installEntitySchema('entity_test'); ConfigurableLanguage::createFromLangcode('zh-hant')->save(); // The address module is never installed, so the importer doesn't run // automatically. Instead, we manually import the address formats we need. $country_codes = ['AD', 'SV', 'TW', 'US', 'ZZ']; $importer = \Drupal::service('address.address_format_importer'); $importer->importEntities($country_codes); $importer->importTranslations(['zh-hant']); $this->entityType = 'entity_test'; $this->bundle = $this->entityType; $this->fieldName = Unicode::strtolower($this->randomMachineName()); $field_storage = FieldStorageConfig::create(['field_name' => $this->fieldName, 'entity_type' => $this->entityType, 'type' => 'address']); $field_storage->save(); $field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => $this->bundle, 'label' => $this->randomMachineName()]); $field->save(); $values = ['targetEntityType' => $this->entityType, 'bundle' => $this->bundle, 'mode' => 'default', 'status' => TRUE]; $this->display = \Drupal::entityTypeManager()->getStorage('entity_view_display')->create($values); $this->display->setComponent($this->fieldName, ['type' => 'address_default', 'settings' => []]); $this->display->save(); }
/** * {@inheritdoc} */ protected function validateEntityStrings(array &$form, array $values, FormStateInterface $form_state) { $uids = array(); $missing = array(); foreach ($values as $value) { if (Unicode::strtolower($value) === Unicode::strtolower(\Drupal::config('user.settings')->get('anonymous'))) { $uids[] = 0; } else { $missing[strtolower($value)] = $value; } } if (!$missing) { return $uids; } $result = Database::getConnection()->query("SELECT * FROM {users} WHERE name IN (:names)", array(':names' => array_values($missing))); foreach ($result as $account) { unset($missing[strtolower($account->name)]); $uids[] = $account->uid; } if ($missing) { $form_state->setError($form, $this->formatPlural(count($missing), 'Unable to find user: @users', 'Unable to find users: @users', array('@users' => implode(', ', $missing)))); } return $uids; }
protected function setUp() { parent::setUp(); // Create Basic page node type. $this->drupalCreateContentType(array('type' => 'page', 'name' => 'Basic page')); $vocabulary = entity_create('taxonomy_vocabulary', array('name' => $this->randomMachineName(), 'description' => $this->randomMachineName(), 'vid' => Unicode::strtolower($this->randomMachineName()), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'help' => '', 'nodes' => array('page' => 'page'), 'weight' => mt_rand(0, 10))); $vocabulary->save(); // Create a field. $field_name = Unicode::strtolower($this->randomMachineName()); $handler_settings = array('target_bundles' => array($vocabulary->id() => $vocabulary->id()), 'auto_create' => TRUE); $this->createEntityReferenceField('node', 'page', $field_name, NULL, 'taxonomy_term', 'default', $handler_settings, FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED); // Create a time in the past for the archive. $time = REQUEST_TIME - 3600; $this->addDefaultCommentField('node', 'page'); for ($i = 0; $i <= 10; $i++) { $user = $this->drupalCreateUser(); $term = $this->createTerm($vocabulary); $values = array('created' => $time, 'type' => 'page'); $values[$field_name][]['target_id'] = $term->id(); // Make every other node promoted. if ($i % 2) { $values['promote'] = TRUE; } $values['body'][]['value'] = \Drupal::l('Node ' . 1, new Url('entity.node.canonical', ['node' => 1])); $node = $this->drupalCreateNode($values); $comment = array('uid' => $user->id(), 'status' => CommentInterface::PUBLISHED, 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment'); entity_create('comment', $comment)->save(); } // Some views, such as the "Who's Online" view, only return results if at // least one user is logged in. $account = $this->drupalCreateUser(array()); $this->drupalLogin($account); }