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