BlockCreationTrait.php 1.9 KB

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