Chris@0
|
1 <?php
|
Chris@0
|
2
|
Chris@0
|
3 namespace Drupal\Tests\block\Traits;
|
Chris@0
|
4
|
Chris@0
|
5 use Drupal\block\Entity\Block;
|
Chris@0
|
6
|
Chris@0
|
7 /**
|
Chris@0
|
8 * Provides methods to create and place block with default settings.
|
Chris@0
|
9 *
|
Chris@0
|
10 * This trait is meant to be used only by test classes.
|
Chris@0
|
11 */
|
Chris@0
|
12 trait BlockCreationTrait {
|
Chris@0
|
13
|
Chris@0
|
14 /**
|
Chris@0
|
15 * Creates a block instance based on default settings.
|
Chris@0
|
16 *
|
Chris@0
|
17 * @param string $plugin_id
|
Chris@0
|
18 * The plugin ID of the block type for this block instance.
|
Chris@0
|
19 * @param array $settings
|
Chris@0
|
20 * (optional) An associative array of settings for the block entity.
|
Chris@0
|
21 * Override the defaults by specifying the key and value in the array, for
|
Chris@0
|
22 * example:
|
Chris@0
|
23 * @code
|
Chris@0
|
24 * $this->drupalPlaceBlock('system_powered_by_block', array(
|
Chris@0
|
25 * 'label' => t('Hello, world!'),
|
Chris@0
|
26 * ));
|
Chris@0
|
27 * @endcode
|
Chris@0
|
28 * The following defaults are provided:
|
Chris@0
|
29 * - label: Random string.
|
Chris@0
|
30 * - ID: Random string.
|
Chris@0
|
31 * - region: 'sidebar_first'.
|
Chris@0
|
32 * - theme: The default theme.
|
Chris@0
|
33 * - visibility: Empty array.
|
Chris@0
|
34 *
|
Chris@0
|
35 * @return \Drupal\block\Entity\Block
|
Chris@0
|
36 * The block entity.
|
Chris@0
|
37 *
|
Chris@0
|
38 * @todo
|
Chris@0
|
39 * Add support for creating custom block instances.
|
Chris@0
|
40 */
|
Chris@0
|
41 protected function placeBlock($plugin_id, array $settings = []) {
|
Chris@0
|
42 $config = \Drupal::configFactory();
|
Chris@0
|
43 $settings += [
|
Chris@0
|
44 'plugin' => $plugin_id,
|
Chris@0
|
45 'region' => 'sidebar_first',
|
Chris@0
|
46 'id' => strtolower($this->randomMachineName(8)),
|
Chris@0
|
47 'theme' => $config->get('system.theme')->get('default'),
|
Chris@0
|
48 'label' => $this->randomMachineName(8),
|
Chris@0
|
49 'visibility' => [],
|
Chris@0
|
50 'weight' => 0,
|
Chris@0
|
51 ];
|
Chris@0
|
52 $values = [];
|
Chris@0
|
53 foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
|
Chris@0
|
54 $values[$key] = $settings[$key];
|
Chris@0
|
55 // Remove extra values that do not belong in the settings array.
|
Chris@0
|
56 unset($settings[$key]);
|
Chris@0
|
57 }
|
Chris@0
|
58 foreach ($values['visibility'] as $id => $visibility) {
|
Chris@0
|
59 $values['visibility'][$id]['id'] = $id;
|
Chris@0
|
60 }
|
Chris@0
|
61 $values['settings'] = $settings;
|
Chris@0
|
62 $block = Block::create($values);
|
Chris@0
|
63 $block->save();
|
Chris@0
|
64 return $block;
|
Chris@0
|
65 }
|
Chris@0
|
66
|
Chris@0
|
67 }
|