0f89b86e6a237149f01e523e09380461a839b56b
[yaffs-website] / web / core / modules / block_content / tests / src / Functional / BlockContentCreationTest.php
1 <?php
2
3 namespace Drupal\Tests\block_content\Functional;
4
5 use Drupal\block_content\Entity\BlockContent;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\Core\Database\Database;
8
9 /**
10  * Create a block and test saving it.
11  *
12  * @group block_content
13  */
14 class BlockContentCreationTest extends BlockContentTestBase {
15
16   /**
17    * Modules to enable.
18    *
19    * Enable dummy module that implements hook_block_insert() for exceptions and
20    * field_ui to edit display settings.
21    *
22    * @var array
23    */
24   public static $modules = ['block_content_test', 'dblog', 'field_ui'];
25
26   /**
27    * Permissions to grant admin user.
28    *
29    * @var array
30    */
31   protected $permissions = [
32     'administer blocks',
33     'administer block_content display'
34   ];
35
36   /**
37    * Sets the test up.
38    */
39   protected function setUp() {
40     parent::setUp();
41     $this->drupalLogin($this->adminUser);
42   }
43
44   /**
45    * Creates a "Basic page" block and verifies its consistency in the database.
46    */
47   public function testBlockContentCreation() {
48     $this->drupalLogin($this->adminUser);
49
50     // Create a block.
51     $edit = [];
52     $edit['info[0][value]'] = 'Test Block';
53     $edit['body[0][value]'] = $this->randomMachineName(16);
54     $this->drupalPostForm('block/add/basic', $edit, t('Save'));
55
56     // Check that the Basic block has been created.
57     $this->assertRaw(format_string('@block %name has been created.', [
58       '@block' => 'basic',
59       '%name' => $edit['info[0][value]']
60     ]), 'Basic block created.');
61
62     // Check that the view mode setting is hidden because only one exists.
63     $this->assertNoFieldByXPath('//select[@name="settings[view_mode]"]', NULL, 'View mode setting hidden because only one exists');
64
65     // Check that the block exists in the database.
66     $blocks = \Drupal::entityTypeManager()
67       ->getStorage('block_content')
68       ->loadByProperties(['info' => $edit['info[0][value]']]);
69     $block = reset($blocks);
70     $this->assertTrue($block, 'Custom Block found in database.');
71
72     // Check that attempting to create another block with the same value for
73     // 'info' returns an error.
74     $this->drupalPostForm('block/add/basic', $edit, t('Save'));
75
76     // Check that the Basic block has been created.
77     $this->assertRaw(format_string('A custom block with block description %value already exists.', [
78       '%value' => $edit['info[0][value]']
79     ]));
80     $this->assertResponse(200);
81   }
82
83   /**
84    * Creates a "Basic page" block with multiple view modes.
85    */
86   public function testBlockContentCreationMultipleViewModes() {
87     // Add a new view mode and verify if it is selected as expected.
88     $this->drupalLogin($this->drupalCreateUser(['administer display modes']));
89     $this->drupalGet('admin/structure/display-modes/view/add/block_content');
90     $edit = [
91       'id' => 'test_view_mode',
92       'label' => 'Test View Mode',
93     ];
94     $this->drupalPostForm(NULL, $edit, t('Save'));
95     $this->assertRaw(t('Saved the %label view mode.', ['%label' => $edit['label']]));
96
97     $this->drupalLogin($this->adminUser);
98
99     // Create a block.
100     $edit = [];
101     $edit['info[0][value]'] = 'Test Block';
102     $edit['body[0][value]'] = $this->randomMachineName(16);
103     $this->drupalPostForm('block/add/basic', $edit, t('Save'));
104
105     // Check that the Basic block has been created.
106     $this->assertRaw(format_string('@block %name has been created.', [
107       '@block' => 'basic',
108       '%name' => $edit['info[0][value]']
109     ]), 'Basic block created.');
110
111     // Save our block permanently
112     $this->drupalPostForm(NULL, ['region' => 'content'], t('Save block'));
113
114     // Set test_view_mode as a custom display to be available on the list.
115     $this->drupalGet('admin/structure/block/block-content');
116     $this->drupalGet('admin/structure/block/block-content/types');
117     $this->clickLink(t('Manage display'));
118     $this->drupalGet('admin/structure/block/block-content/manage/basic/display');
119     $custom_view_mode = [
120       'display_modes_custom[test_view_mode]' => 1,
121     ];
122     $this->drupalPostForm(NULL, $custom_view_mode, t('Save'));
123
124     // Go to the configure page and change the view mode.
125     $this->drupalGet('admin/structure/block/manage/testblock');
126
127     // Test the available view mode options.
128     $this->assertOption('edit-settings-view-mode', 'default', 'The default view mode is available.');
129     $this->assertOption('edit-settings-view-mode', 'test_view_mode', 'The test view mode is available.');
130
131     $view_mode['settings[view_mode]'] = 'test_view_mode';
132     $this->drupalPostForm(NULL, $view_mode, t('Save block'));
133
134     // Check that the view mode setting is shown because more than one exists.
135     $this->drupalGet('admin/structure/block/manage/testblock');
136     $this->assertFieldByXPath('//select[@name="settings[view_mode]"]', NULL, 'View mode setting shown because multiple exist');
137
138     // Change the view mode.
139     $view_mode['region'] = 'content';
140     $view_mode['settings[view_mode]'] = 'test_view_mode';
141     $this->drupalPostForm(NULL, $view_mode, t('Save block'));
142
143     // Go to the configure page and verify the view mode has changed.
144     $this->drupalGet('admin/structure/block/manage/testblock');
145     $this->assertFieldByXPath('//select[@name="settings[view_mode]"]/option[@selected="selected"]', 'test_view_mode', 'View mode changed to Test View Mode');
146
147     // Check that the block exists in the database.
148     $blocks = \Drupal::entityTypeManager()
149       ->getStorage('block_content')
150       ->loadByProperties(['info' => $edit['info[0][value]']]);
151     $block = reset($blocks);
152     $this->assertTrue($block, 'Custom Block found in database.');
153
154     // Check that attempting to create another block with the same value for
155     // 'info' returns an error.
156     $this->drupalPostForm('block/add/basic', $edit, t('Save'));
157
158     // Check that the Basic block has been created.
159     $this->assertRaw(format_string('A custom block with block description %value already exists.', [
160       '%value' => $edit['info[0][value]']
161     ]));
162     $this->assertResponse(200);
163   }
164
165   /**
166    * Create a default custom block.
167    *
168    * Creates a custom block from defaults and ensures that the 'basic block'
169    * type is being used.
170    */
171   public function testDefaultBlockContentCreation() {
172     $edit = [];
173     $edit['info[0][value]'] = $this->randomMachineName(8);
174     $edit['body[0][value]'] = $this->randomMachineName(16);
175     // Don't pass the custom block type in the url so the default is forced.
176     $this->drupalPostForm('block/add', $edit, t('Save'));
177
178     // Check that the block has been created and that it is a basic block.
179     $this->assertRaw(format_string('@block %name has been created.', [
180       '@block' => 'basic',
181       '%name' => $edit['info[0][value]'],
182     ]), 'Basic block created.');
183
184     // Check that the block exists in the database.
185     $blocks = \Drupal::entityTypeManager()
186       ->getStorage('block_content')
187       ->loadByProperties(['info' => $edit['info[0][value]']]);
188     $block = reset($blocks);
189     $this->assertTrue($block, 'Default Custom Block found in database.');
190   }
191
192   /**
193    * Verifies that a transaction rolls back the failed creation.
194    */
195   public function testFailedBlockCreation() {
196     // Create a block.
197     try {
198       $this->createBlockContent('fail_creation');
199       $this->fail('Expected exception has not been thrown.');
200     }
201     catch (\Exception $e) {
202       $this->pass('Expected exception has been thrown.');
203     }
204
205     if (Database::getConnection()->supportsTransactions()) {
206       // Check that the block does not exist in the database.
207       $id = db_select('block_content_field_data', 'b')
208         ->fields('b', ['id'])
209         ->condition('info', 'fail_creation')
210         ->execute()
211         ->fetchField();
212       $this->assertFalse($id, 'Transactions supported, and block not found in database.');
213     }
214     else {
215       // Check that the block exists in the database.
216       $id = db_select('block_content_field_data', 'b')
217         ->fields('b', ['id'])
218         ->condition('info', 'fail_creation')
219         ->execute()
220         ->fetchField();
221       $this->assertTrue($id, 'Transactions not supported, and block found in database.');
222
223       // Check that the failed rollback was logged.
224       $records = db_query("SELECT wid FROM {watchdog} WHERE message LIKE 'Explicit rollback failed%'")->fetchAll();
225       $this->assertTrue(count($records) > 0, 'Transactions not supported, and rollback error logged to watchdog.');
226     }
227   }
228
229   /**
230    * Test deleting a block.
231    */
232   public function testBlockDelete() {
233     // Create a block.
234     $edit = [];
235     $edit['info[0][value]'] = $this->randomMachineName(8);
236     $body = $this->randomMachineName(16);
237     $edit['body[0][value]'] = $body;
238     $this->drupalPostForm('block/add/basic', $edit, t('Save'));
239
240     // Place the block.
241     $instance = [
242       'id' => Unicode::strtolower($edit['info[0][value]']),
243       'settings[label]' => $edit['info[0][value]'],
244       'region' => 'sidebar_first',
245     ];
246     $block = BlockContent::load(1);
247     $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default');
248     $this->drupalPostForm($url, $instance, t('Save block'));
249
250     $block = BlockContent::load(1);
251
252     // Test getInstances method.
253     $this->assertEqual(1, count($block->getInstances()));
254
255     // Navigate to home page.
256     $this->drupalGet('');
257     $this->assertText($body);
258
259     // Delete the block.
260     $this->drupalGet('block/1/delete');
261     $this->assertText(\Drupal::translation()->formatPlural(1, 'This will also remove 1 placed block instance.', 'This will also remove @count placed block instance.'));
262
263     $this->drupalPostForm(NULL, [], 'Delete');
264     $this->assertRaw(t('The custom block %name has been deleted.', ['%name' => $edit['info[0][value]']]));
265
266     // Create another block and force the plugin cache to flush.
267     $edit2 = [];
268     $edit2['info[0][value]'] = $this->randomMachineName(8);
269     $body2 = $this->randomMachineName(16);
270     $edit2['body[0][value]'] = $body2;
271     $this->drupalPostForm('block/add/basic', $edit2, t('Save'));
272
273     $this->assertNoRaw('Error message');
274
275     // Create another block with no instances, and test we don't get a
276     // confirmation message about deleting instances.
277     $edit3 = [];
278     $edit3['info[0][value]'] = $this->randomMachineName(8);
279     $body = $this->randomMachineName(16);
280     $edit3['body[0][value]'] = $body;
281     $this->drupalPostForm('block/add/basic', $edit3, t('Save'));
282
283     // Show the delete confirm form.
284     $this->drupalGet('block/3/delete');
285     $this->assertNoText('This will also remove');
286   }
287
288   /**
289    * Test that placed content blocks create a dependency in the block placement.
290    */
291   public function testConfigDependencies() {
292     $block = $this->createBlockContent();
293     // Place the block.
294     $block_placement_id = Unicode::strtolower($block->label());
295     $instance = [
296       'id' => $block_placement_id,
297       'settings[label]' => $block->label(),
298       'region' => 'sidebar_first',
299     ];
300     $block = BlockContent::load(1);
301     $url = 'admin/structure/block/add/block_content:' . $block->uuid() . '/' . $this->config('system.theme')->get('default');
302     $this->drupalPostForm($url, $instance, t('Save block'));
303
304     $dependencies = \Drupal::service('config.manager')->findConfigEntityDependentsAsEntities('content', [$block->getConfigDependencyName()]);
305     $block_placement = reset($dependencies);
306     $this->assertEqual($block_placement_id, $block_placement->id(), "The block placement config entity has a dependency on the block content entity.");
307   }
308
309 }