Chris@0: randomMachineName(). Chris@0: * @param $reset Chris@0: * (optional) Whether to reset the entity cache. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface Chris@0: * A node entity matching $title. Chris@0: */ Chris@0: public function getNodeByTitle($title, $reset = FALSE) { Chris@0: if ($reset) { Chris@0: \Drupal::entityTypeManager()->getStorage('node')->resetCache(); Chris@0: } Chris@0: // Cast MarkupInterface objects to string. Chris@0: $title = (string) $title; Chris@0: $nodes = \Drupal::entityTypeManager() Chris@0: ->getStorage('node') Chris@0: ->loadByProperties(['title' => $title]); Chris@0: // Load the first node returned from the database. Chris@0: $returned_node = reset($nodes); Chris@0: return $returned_node; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Creates a node based on default settings. Chris@0: * Chris@0: * @param array $settings Chris@0: * (optional) An associative array of settings for the node, as used in Chris@0: * entity_create(). Override the defaults by specifying the key and value Chris@0: * in the array, for example: Chris@0: * @code Chris@0: * $this->drupalCreateNode(array( Chris@0: * 'title' => t('Hello, world!'), Chris@0: * 'type' => 'article', Chris@0: * )); Chris@0: * @endcode Chris@0: * The following defaults are provided: Chris@0: * - body: Random string using the default filter format: Chris@0: * @code Chris@0: * $settings['body'][0] = array( Chris@0: * 'value' => $this->randomMachineName(32), Chris@0: * 'format' => filter_default_format(), Chris@0: * ); Chris@0: * @endcode Chris@0: * - title: Random string. Chris@0: * - type: 'page'. Chris@0: * - uid: The currently logged in user, or anonymous. Chris@0: * Chris@0: * @return \Drupal\node\NodeInterface Chris@0: * The created node entity. Chris@0: */ Chris@0: protected function createNode(array $settings = []) { Chris@0: // Populate defaults array. Chris@0: $settings += [ Chris@0: 'body' => [ Chris@0: [ Chris@0: 'value' => $this->randomMachineName(32), Chris@0: 'format' => filter_default_format(), Chris@0: ], Chris@0: ], Chris@0: 'title' => $this->randomMachineName(8), Chris@0: 'type' => 'page', Chris@0: ]; Chris@18: Chris@18: if (!array_key_exists('uid', $settings)) { Chris@18: $user = User::load(\Drupal::currentUser()->id()); Chris@18: if ($user) { Chris@18: $settings['uid'] = $user->id(); Chris@18: } Chris@18: elseif (method_exists($this, 'setUpCurrentUser')) { Chris@18: /** @var \Drupal\user\UserInterface $user */ Chris@18: $user = $this->setUpCurrentUser(); Chris@18: $settings['uid'] = $user->id(); Chris@18: } Chris@18: else { Chris@18: $settings['uid'] = 0; Chris@18: } Chris@18: } Chris@18: Chris@0: $node = Node::create($settings); Chris@0: $node->save(); Chris@0: Chris@0: return $node; Chris@0: } Chris@0: Chris@0: }