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