Version 1
[yaffs-website] / web / core / modules / simpletest / src / ContentTypeCreationTrait.php
1 <?php
2
3 namespace Drupal\simpletest;
4
5 use Drupal\Component\Render\FormattableMarkup;
6 use Drupal\node\Entity\NodeType;
7
8 /**
9  * Provides methods to create content type from given values.
10  *
11  * This trait is meant to be used only by test classes.
12  */
13 trait ContentTypeCreationTrait {
14
15   /**
16    * Creates a custom content type based on default settings.
17    *
18    * @param array $values
19    *   An array of settings to change from the defaults.
20    *   Example: 'type' => 'foo'.
21    *
22    * @return \Drupal\node\Entity\NodeType
23    *   Created content type.
24    */
25   protected function createContentType(array $values = []) {
26     // Find a non-existent random type name.
27     if (!isset($values['type'])) {
28       do {
29         $id = strtolower($this->randomMachineName(8));
30       } while (NodeType::load($id));
31     }
32     else {
33       $id = $values['type'];
34     }
35     $values += [
36       'type' => $id,
37       'name' => $id,
38     ];
39     $type = NodeType::create($values);
40     $status = $type->save();
41     node_add_body_field($type);
42
43     if ($this instanceof \PHPUnit_Framework_TestCase) {
44       $this->assertSame($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', ['%type' => $type->id()]))->__toString());
45     }
46     else {
47       $this->assertEqual($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', ['%type' => $type->id()]))->__toString());
48     }
49
50     return $type;
51   }
52
53 }