Drupal investigation

NodeCreationTrait.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace Drupal\simpletest;
  3. use Drupal\node\Entity\Node;
  4. /**
  5. * Provides methods to create node based on default settings.
  6. *
  7. * This trait is meant to be used only by test classes.
  8. */
  9. trait NodeCreationTrait {
  10. /**
  11. * Get a node from the database based on its title.
  12. *
  13. * @param string|\Drupal\Component\Render\MarkupInterface $title
  14. * A node title, usually generated by $this->randomMachineName().
  15. * @param $reset
  16. * (optional) Whether to reset the entity cache.
  17. *
  18. * @return \Drupal\node\NodeInterface
  19. * A node entity matching $title.
  20. */
  21. public function getNodeByTitle($title, $reset = FALSE) {
  22. if ($reset) {
  23. \Drupal::entityTypeManager()->getStorage('node')->resetCache();
  24. }
  25. // Cast MarkupInterface objects to string.
  26. $title = (string) $title;
  27. $nodes = \Drupal::entityTypeManager()
  28. ->getStorage('node')
  29. ->loadByProperties(['title' => $title]);
  30. // Load the first node returned from the database.
  31. $returned_node = reset($nodes);
  32. return $returned_node;
  33. }
  34. /**
  35. * Creates a node based on default settings.
  36. *
  37. * @param array $settings
  38. * (optional) An associative array of settings for the node, as used in
  39. * entity_create(). Override the defaults by specifying the key and value
  40. * in the array, for example:
  41. * @code
  42. * $this->drupalCreateNode(array(
  43. * 'title' => t('Hello, world!'),
  44. * 'type' => 'article',
  45. * ));
  46. * @endcode
  47. * The following defaults are provided:
  48. * - body: Random string using the default filter format:
  49. * @code
  50. * $settings['body'][0] = array(
  51. * 'value' => $this->randomMachineName(32),
  52. * 'format' => filter_default_format(),
  53. * );
  54. * @endcode
  55. * - title: Random string.
  56. * - type: 'page'.
  57. * - uid: The currently logged in user, or anonymous.
  58. *
  59. * @return \Drupal\node\NodeInterface
  60. * The created node entity.
  61. */
  62. protected function createNode(array $settings = []) {
  63. // Populate defaults array.
  64. $settings += [
  65. 'body' => [[
  66. 'value' => $this->randomMachineName(32),
  67. 'format' => filter_default_format(),
  68. ]],
  69. 'title' => $this->randomMachineName(8),
  70. 'type' => 'page',
  71. 'uid' => \Drupal::currentUser()->id(),
  72. ];
  73. $node = Node::create($settings);
  74. $node->save();
  75. return $node;
  76. }
  77. }