本文整理汇总了PHP中Drupal\node\Entity\Node::create方法的典型用法代码示例。如果您正苦于以下问题:PHP Node::create方法的具体用法?PHP Node::create怎么用?PHP Node::create使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Drupal\node\Entity\Node
的用法示例。
在下文中一共展示了Node::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testProgrammaticNewsletterMultiple
/**
* Creates and sends a node using the API to Multiple.
*/
public function testProgrammaticNewsletterMultiple()
{
// Create a new newsletter.
$this->drupalGet('admin/config/services/simplenews');
$this->clickLink(t('Add newsletter'));
$edit = array('name' => $this->randomString(10), 'id' => strtolower($this->randomMachineName(10)), 'description' => $this->randomString(20));
$this->drupalPostForm(NULL, $edit, t('Save'));
// Checking if node creating successful with correct name.
$this->assertText(t('Newsletter @name has been added', array('@name' => $edit['name'])));
// Subscription setupSimplenewsMultipleNewsletters.
$this->setUpSubscribersWithMultiNewsletters();
// Create a very basic node.
$node = Node::create(array('type' => 'simplenews_issue', 'title' => $this->randomString(10), 'uid' => 0, 'status' => 1));
$node->simplenews_issue = $this->getRandomNewsletters(2);
$node->simplenews_issue->handler = 'simplenews_all';
$node->save();
// Add the subscribers of the node to the spool storage queue.
\Drupal::service('simplenews.spool_storage')->addFromEntity($node);
$node->save();
// Subsciber Count check.
$this->assertEqual(3, count($this->subscribers), t('all subscribers have been received a mail'));
// Make sure that they have been added.
$this->assertEqual(\Drupal::service('simplenews.spool_storage')->countMails(), 3);
// Mark them as pending, fake a currently running send process.
$this->assertEqual(count(\Drupal::service('simplenews.spool_storage')->getMails(2)), 2);
// Those two should be excluded from the count now.
$this->assertEqual(\Drupal::service('simplenews.spool_storage')->countMails(), 1);
// Get one additional spool entry.
$this->assertEqual(count(\Drupal::service('simplenews.spool_storage')->getMails(1)), 1);
// Now only none should be returned by the count.
$this->assertEqual(\Drupal::service('simplenews.spool_storage')->countMails(), 0);
}
示例2: testGetEntity
/**
* Tests the getEntity method.
*/
public function testGetEntity()
{
// The view is a view of comments, their nodes and their authors, so there
// are three layers of entities.
$account = User::create(['name' => $this->randomMachineName(), 'bundle' => 'user']);
$account->save();
$node = Node::create(['uid' => $account->id(), 'type' => 'page', 'title' => $this->randomString()]);
$node->save();
$comment = Comment::create(array('uid' => $account->id(), 'entity_id' => $node->id(), 'entity_type' => 'node', 'field_name' => 'comment'));
$comment->save();
$user = $this->drupalCreateUser(['access comments']);
$this->drupalLogin($user);
$view = Views::getView('test_field_get_entity');
$this->executeView($view);
$row = $view->result[0];
// Tests entities on the base level.
$entity = $view->field['cid']->getEntity($row);
$this->assertEqual($entity->id(), $comment->id(), 'Make sure the right comment entity got loaded.');
// Tests entities as relationship on first level.
$entity = $view->field['nid']->getEntity($row);
$this->assertEqual($entity->id(), $node->id(), 'Make sure the right node entity got loaded.');
// Tests entities as relationships on second level.
$entity = $view->field['uid']->getEntity($row);
$this->assertEqual($entity->id(), $account->id(), 'Make sure the right user entity got loaded.');
}
示例3: prepareTranslationSuggestions
/**
* Prepare a node to get suggestions from.
*
* Creates a node with two file fields. The first one is not translatable,
* the second one is. Both fields got two files attached, where one has
* translatable content (title and atl-text) and the other one not.
*
* @return object
* The node which is prepared with all needed fields for the suggestions.
*/
protected function prepareTranslationSuggestions()
{
// Create a content type with fields.
// Only the first field is a translatable reference.
$type = NodeType::create(['type' => $this->randomMachineName()]);
$type->save();
$content_translation_manager = \Drupal::service('content_translation.manager');
$content_translation_manager->setEnabled('node', $type->id(), TRUE);
$field1 = FieldStorageConfig::create(array('field_name' => 'field1', 'entity_type' => 'node', 'type' => 'entity_reference', 'cardinality' => -1, 'settings' => array('target_type' => 'node')));
$field1->save();
$field2 = FieldStorageConfig::create(array('field_name' => 'field2', 'entity_type' => 'node', 'type' => 'entity_reference', 'cardinality' => -1, 'settings' => array('target_type' => 'node')));
$field2->save();
// Create field instances on the content type.
FieldConfig::create(array('field_storage' => $field1, 'bundle' => $type->id(), 'label' => 'Field 1', 'translatable' => FALSE, 'settings' => array()))->save();
FieldConfig::create(array('field_storage' => $field2, 'bundle' => $type->id(), 'label' => 'Field 2', 'translatable' => TRUE, 'settings' => array()))->save();
// Create a translatable body field.
node_add_body_field($type);
$field = FieldConfig::loadByName('node', $type->id(), 'body');
$field->setTranslatable(TRUE);
$field->save();
// Create 4 nodes to be referenced.
$references = array();
for ($i = 0; $i < 4; $i++) {
$references[$i] = Node::create(array('title' => $this->randomMachineName(), 'body' => $this->randomMachineName(), 'type' => $type->id()));
$references[$i]->save();
}
// Create a node with two translatable and two non-translatable references.
$node = Node::create(array('title' => $this->randomMachineName(), 'type' => $type->id(), 'language' => 'en', 'body' => $this->randomMachineName(), $field1->getName() => array(array('target_id' => $references[0]->id()), array('target_id' => $references[1]->id())), $field2->getName() => array(array('target_id' => $references[2]->id()), array('target_id' => $references[3]->id()))));
$node->save();
$link = MenuLinkContent::create(['link' => [['uri' => 'entity:node/' . $node->id()]], 'title' => 'Node menu link', 'menu_name' => 'main']);
$link->save();
$node->link = $link;
return $node;
}
示例4: testSort
/**
* Assert sorting by field and property.
*/
public function testSort()
{
// Add text field to entity, to sort by.
entity_create('field_storage_config', array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text', 'entity_types' => array('node')))->save();
entity_create('field_config', array('label' => 'Text Field', 'field_name' => 'field_text', 'entity_type' => 'node', 'bundle' => 'article', 'settings' => array(), 'required' => FALSE))->save();
// Build a set of test data.
$node_values = array('published1' => array('type' => 'article', 'status' => 1, 'title' => 'Node published1 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 1))), 'published2' => array('type' => 'article', 'status' => 1, 'title' => 'Node published2 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 2))));
$nodes = array();
$node_labels = array();
foreach ($node_values as $key => $values) {
$node = Node::create($values);
$node->save();
$nodes[$key] = $node;
$node_labels[$key] = SafeMarkup::checkPlain($node->label());
}
$selection_options = array('target_type' => 'node', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'sort' => array('field' => 'field_text.value', 'direction' => 'DESC')));
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
// Not only assert the result, but make sure the keys are sorted as
// expected.
$result = $handler->getReferenceableEntities();
$expected_result = array($nodes['published2']->id() => $node_labels['published2'], $nodes['published1']->id() => $node_labels['published1']);
$this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.');
// Assert sort by base field.
$selection_options['handler_settings']['sort'] = array('field' => 'nid', 'direction' => 'ASC');
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options);
$result = $handler->getReferenceableEntities();
$expected_result = array($nodes['published1']->id() => $node_labels['published1'], $nodes['published2']->id() => $node_labels['published2']);
$this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.');
}
示例5: testNodeTranslation
/**
* Tests the normalization of node translations.
*/
public function testNodeTranslation()
{
$node_type = NodeType::create(['type' => 'example_type']);
$node_type->save();
$this->container->get('content_translation.manager')->setEnabled('node', 'example_type', TRUE);
$user = User::create(['name' => $this->randomMachineName()]);
$user->save();
$node = Node::create(['title' => $this->randomMachineName(), 'uid' => $user->id(), 'type' => $node_type->id(), 'status' => NODE_PUBLISHED, 'langcode' => 'en', 'promote' => 1, 'sticky' => 0, 'body' => ['value' => $this->randomMachineName(), 'format' => $this->randomMachineName()], 'revision_log' => $this->randomString()]);
$node->addTranslation('de', ['title' => 'German title', 'body' => ['value' => $this->randomMachineName(), 'format' => $this->randomMachineName()]]);
$node->save();
$original_values = $node->toArray();
$translation = $node->getTranslation('de');
$original_translation_values = $node->getTranslation('en')->toArray();
$normalized = $this->serializer->normalize($node, $this->format);
$this->assertContains(['lang' => 'en', 'value' => $node->getTitle()], $normalized['title'], 'Original language title has been normalized.');
$this->assertContains(['lang' => 'de', 'value' => $translation->getTitle()], $normalized['title'], 'Translation language title has been normalized.');
/** @var \Drupal\node\NodeInterface $denormalized_node */
$denormalized_node = $this->serializer->denormalize($normalized, 'Drupal\\node\\Entity\\Node', $this->format);
$this->assertSame($denormalized_node->language()->getId(), $denormalized_node->getUntranslated()->language()->getId(), 'Untranslated object is returned from serializer.');
$this->assertSame('en', $denormalized_node->language()->getId());
$this->assertTrue($denormalized_node->hasTranslation('de'));
$this->assertSame($node->getTitle(), $denormalized_node->getTitle());
$this->assertSame($translation->getTitle(), $denormalized_node->getTranslation('de')->getTitle());
$this->assertEquals($original_values, $denormalized_node->toArray(), 'Node values are restored after normalizing and denormalizing.');
$this->assertEquals($original_translation_values, $denormalized_node->getTranslation('en')->toArray(), 'Node values are restored after normalizing and denormalizing.');
}
示例6: testViewShowsCorrectStates
/**
* Test the view operation access handler with the view permission.
*/
public function testViewShowsCorrectStates()
{
$node_type_id = 'test';
$this->createNodeType('Test', $node_type_id);
$permissions = ['access content', 'view all revisions', 'view moderation states'];
$editor1 = $this->drupalCreateUser($permissions);
$this->drupalLogin($editor1);
$node_1 = Node::create(['type' => $node_type_id, 'title' => 'Draft node', 'uid' => $editor1->id()]);
$node_1->moderation_state->target_id = 'draft';
$node_1->save();
$node_2 = Node::create(['type' => $node_type_id, 'title' => 'Published node', 'uid' => $editor1->id()]);
$node_2->moderation_state->target_id = 'published';
$node_2->save();
// Resave the node with a new state.
$node_2->setTitle('Archived node');
$node_2->moderation_state->target_id = 'archived';
$node_2->save();
// Now show the View, and confirm that the state labels are showing.
$this->drupalGet('/latest');
$page = $this->getSession()->getPage();
$this->assertTrue($page->hasLink('Draft'));
$this->assertTrue($page->hasLink('Archived'));
$this->assertFalse($page->hasLink('Published'));
// Now log in as an admin and test the same thing.
$permissions = ['access content', 'view all revisions', 'administer moderation states'];
$admin1 = $this->drupalCreateUser($permissions);
$this->drupalLogin($admin1);
$this->drupalGet('/latest');
$page = $this->getSession()->getPage();
$this->assertEquals(200, $this->getSession()->getStatusCode());
$this->assertTrue($page->hasLink('Draft'));
$this->assertTrue($page->hasLink('Archived'));
$this->assertFalse($page->hasLink('Published'));
}
示例7: saveExpo_new
public static function saveExpo_new($d)
{
$viewhash = self::_gen_hash('field_viewhash');
$edithash = self::_gen_hash('field_edithash');
//$node->field_image->setValue([
//'target_id' => $file->id(),
//]);
$node_values = array('type' => 'expo', 'title' => $d['title'], 'langcode' => 'und', 'uid' => '1', 'status' => 1, 'field_edithash' => ['value' => $edithash], 'field_viewhash' => ['value' => $viewhash], 'field_authoremail' => ['value' => $d['email']], 'field_author_plain' => ['value' => $d['author']], 'field_public' => ['value' => $d['public']], 'field_showinfront' => ['value' => $d['showinfront']], 'field_hide' => ['value' => $d['hide']], 'field_highlight' => ['value' => $d['highlight']], 'field_weight' => ['value' => $d['weight']], 'path' => '/p/' . $viewhash);
if (is_array($d['body'])) {
$node_values['field_body'] = $d['body'];
} else {
$node_values['field_body'] = ['format' => 'rich_html_base', 'value' => $d['body']];
}
if ($d['featuredimage']) {
if (is_array($d['featuredimage'])) {
$node_values['field_featuredimage'] = $d['featuredimage'];
}
}
$node = Node::create($node_values);
$node->save();
foreach ($d['collitems'] as $item) {
$collitem = ['field_name' => 'field_collitem'];
$collitem['field_target'] = array('value' => $item['target']);
if ($item['annotation']) {
$collitem['field_annotation'] = $item['annotation'];
}
$fcitem = FieldCollectionItem::create($collitem);
$fcitem->setHostEntity($node, false);
$node->{$fcitem->bundle()}[] = array('field_collection_item' => $fcitem);
$fcitem->save(true);
}
$node->save();
return $node;
}
示例8: testFailedPageCreation
/**
* Verifies that a transaction rolls back the failed creation.
*/
function testFailedPageCreation()
{
// Create a node.
$edit = array('uid' => $this->loggedInUser->id(), 'name' => $this->loggedInUser->name, 'type' => 'page', 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'title' => 'testing_transaction_exception');
try {
// An exception is generated by node_test_exception_node_insert() if the
// title is 'testing_transaction_exception'.
Node::create($edit)->save();
$this->fail(t('Expected exception has not been thrown.'));
} catch (\Exception $e) {
$this->pass(t('Expected exception has been thrown.'));
}
if (Database::getConnection()->supportsTransactions()) {
// Check that the node does not exist in the database.
$node = $this->drupalGetNodeByTitle($edit['title']);
$this->assertFalse($node, 'Transactions supported, and node not found in database.');
} else {
// Check that the node exists in the database.
$node = $this->drupalGetNodeByTitle($edit['title']);
$this->assertTrue($node, 'Transactions not supported, and node found in database.');
// Check that the failed rollback was logged.
$records = static::getWatchdogIdsForFailedExplicitRollback();
$this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
}
// Check that the rollback error was logged.
$records = static::getWatchdogIdsForTestExceptionRollback();
$this->assertTrue(count($records) > 0, 'Rollback explanatory error logged to watchdog.');
}
示例9: 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.');
}
示例10: submitForm
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state)
{
$html_raw = $this->curl_get($form_state->getValue('url'));
$pattern = '/<div\\s*?class="k-grid-content">.*?<tbody[^>]*>(.*?)<\\/tbody>/msi';
if (!preg_match($pattern, $html_raw, $matches)) {
return;
}
$pattern = '/<a\\s*href="\\/codigo-postal-([^"]*)">/msi';
if (!preg_match_all($pattern, $matches[1], $zipcodes_raw)) {
return;
}
$zipcodes = array();
foreach ($zipcodes_raw[1] as $zipcode_raw) {
$zipcodes[$zipcode_raw] = $zipcode_raw;
}
ksort($zipcodes);
// Build Pairs
$state = $form_state->getValue('state');
$city = $form_state->getValue('city');
$zipcodesb = $zipcodes;
$zipcodes_count = 0;
foreach ($zipcodes as $zipcode_start) {
foreach ($zipcodesb as $zipcode_end) {
// Validate we don't already have it.
if (\Drupal\zipcoderate\Controller\ZipCodeRateController::getRateNode(63175, 63175, false)) {
continue;
}
$zipcodes_count++;
$node = \Drupal\node\Entity\Node::create(['title' => "{$city} {$state} - [{$zipcode_start} - {$zipcode_end}]", 'type' => 'rate', 'field_zipcode_start' => $zipcode_start, 'field_zipcode_end' => $zipcode_end, 'field_state' => $state, 'field_city' => $city]);
$node->save();
}
}
drupal_set_message(t('@zipcodes_count ZipCodes were Imported', array('@zipcodes_count' => $zipcodes_count)), 'status');
}
示例11: testUpdateHookN
/**
* Tests that page title is being converted into a block.
*/
public function testUpdateHookN()
{
$this->runUpdates();
/** @var \Drupal\block\BlockInterface $block_storage */
$block_storage = \Drupal::entityManager()->getStorage('block');
$this->assertRaw('Because your site has custom theme(s) installed, we have placed the page title block in the content region. Please manually review the block configuration and remove the page title variables from your page 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();
// Page title is visible on the home page.
$this->drupalGet('/node');
$this->assertRaw('page-title');
// Page title is visible on a node page.
$this->drupalGet('node/' . $page->id());
$this->assertRaw('page-title');
$this->drupalGet('admin/structure/block/list/bartik');
/** @var \Drupal\Core\Config\StorageInterface $config_storage */
$config_storage = \Drupal::service('config.storage');
$this->assertTrue($config_storage->exists('block.block.test_theme_page_title'), 'Page title block has been created for the custom theme.');
}
示例12: testEntityReferenceDefaultValue
/**
* Tests that default values are correctly translated to UUIDs in config.
*/
function testEntityReferenceDefaultValue()
{
// Create a node to be referenced.
$referenced_node = $this->drupalCreateNode(array('type' => 'referenced_content'));
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array('field_name' => $field_name, 'entity_type' => 'node', 'type' => 'entity_reference', 'settings' => array('target_type' => 'node')));
$field_storage->save();
$field = FieldConfig::create(['field_storage' => $field_storage, 'bundle' => 'reference_content', 'settings' => array('handler' => 'default', 'handler_settings' => array('target_bundles' => array('referenced_content'), 'sort' => array('field' => '_none')))]);
$field->save();
// Set created node as default_value.
$field_edit = array('default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')');
$this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
// Check that default value is selected in default value form.
$this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name);
$this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page');
// Check if the ID has been converted to UUID in config entity.
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property');
$this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same');
// Ensure the configuration has the expected dependency on the entity that
// is being used a default value.
$this->assertEqual(array($referenced_node->getConfigDependencyName()), $config_entity['dependencies']['content']);
// Clear field definitions cache in order to avoid stale cache values.
\Drupal::entityManager()->clearCachedFieldDefinitions();
// Create a new node to check that UUID has been converted to numeric ID.
$new_node = Node::create(['type' => 'reference_content']);
$this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id());
// Ensure that the entity reference config schemas are correct.
$field_config = $this->config('field.field.node.reference_content.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_config->getName(), $field_config->get());
$field_storage_config = $this->config('field.storage.node.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_storage_config->getName(), $field_storage_config->get());
}
示例13: testWhiteListChaining
/**
* Tests white-listing of methods doesn't interfere with chaining.
*/
public function testWhiteListChaining()
{
$node = Node::create(['type' => 'page', 'title' => 'Some node mmk', 'status' => 1, 'field_term' => $this->term->id()]);
$node->save();
$this->setRawContent(twig_render_template(drupal_get_path('theme', 'test_theme') . '/templates/node.html.twig', ['node' => $node]));
$this->assertText('Sometimes people are just jerks');
}
示例14: testExportWithReferences
/**
* Tests exportContentWithReferences().
*/
public function testExportWithReferences()
{
\Drupal::service('module_installer')->install(['node', 'default_content']);
\Drupal::service('router.builder')->rebuild();
$this->defaultContentManager = \Drupal::service('default_content.manager');
$user = User::create(['name' => 'my username']);
$user->save();
// Reload the user to get the proper casted values from the DB.
$user = User::load($user->id());
$node_type = NodeType::create(['type' => 'test']);
$node_type->save();
$node = Node::create(['type' => $node_type->id(), 'title' => 'test node', 'uid' => $user->id()]);
$node->save();
// Reload the node to get the proper casted values from the DB.
$node = Node::load($node->id());
/** @var \Symfony\Component\Serializer\Serializer $serializer */
$serializer = \Drupal::service('serializer');
\Drupal::service('rest.link_manager')->setLinkDomain(DefaultContentManager::LINK_DOMAIN);
$expected_node = $serializer->serialize($node, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
$expected_user = $serializer->serialize($user, 'hal_json', ['json_encode_options' => JSON_PRETTY_PRINT]);
$exported_by_entity_type = $this->defaultContentManager->exportContentWithReferences('node', $node->id());
// Ensure that the node type is not tryed to be exported.
$this->assertEqual(array_keys($exported_by_entity_type), ['node', 'user']);
// Ensure the right UUIDs are exported.
$this->assertEqual([$node->uuid()], array_keys($exported_by_entity_type['node']));
$this->assertEqual([$user->uuid()], array_keys($exported_by_entity_type['user']));
// Compare the actual serialized data.
$this->assertEqual(reset($exported_by_entity_type['node']), $expected_node);
$this->assertEqual(reset($exported_by_entity_type['user']), $expected_user);
}
示例15: testValidation
/**
* Tests the node validation constraints.
*/
public function testValidation()
{
$this->createUser();
$node = Node::create(['type' => 'page', 'title' => 'test', 'uid' => 1]);
$violations = $node->validate();
$this->assertEqual(count($violations), 0, 'No violations when validating a default node.');
$node->set('title', $this->randomString(256));
$violations = $node->validate();
$this->assertEqual(count($violations), 1, 'Violation found when title is too long.');
$this->assertEqual($violations[0]->getPropertyPath(), 'title.0.value');
$this->assertEqual($violations[0]->getMessage(), '<em class="placeholder">Title</em>: may not be longer than 255 characters.');
$node->set('title', NULL);
$violations = $node->validate();
$this->assertEqual(count($violations), 1, 'Violation found when title is not set.');
$this->assertEqual($violations[0]->getPropertyPath(), 'title');
$this->assertEqual($violations[0]->getMessage(), 'This value should not be null.');
$node->set('title', '');
$violations = $node->validate();
$this->assertEqual(count($violations), 1, 'Violation found when title is set to an empty string.');
$this->assertEqual($violations[0]->getPropertyPath(), 'title');
// Make the title valid again.
$node->set('title', $this->randomString());
// Save the node so that it gets an ID and a changed date.
$node->save();
// Set the changed date to something in the far past.
$node->set('changed', 433918800);
$violations = $node->validate();
$this->assertEqual(count($violations), 1, 'Violation found when changed date is before the last changed date.');
$this->assertEqual($violations[0]->getPropertyPath(), '');
$this->assertEqual($violations[0]->getMessage(), 'The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.');
}