devel_wizard-2.x-dev/tests/src/Traits/BlockContentCreationTrait.php

tests/src/Traits/BlockContentCreationTrait.php
<?php

namespace Drupal\Tests\devel_wizard\Traits;

use Drupal\block_content\Entity\BlockContentType;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Tests\RandomGeneratorTrait;

/**
 * Provides methods to create block contents with default settings.
 *
 * This trait is meant to be used only by test classes.
 */
trait BlockContentCreationTrait {

  use RandomGeneratorTrait;

  /**
   * @param array $settings
   *   (optional) An associative array of settings for the block content type
   *   entity.
   *   Override the defaults by specifying the key and value in the array, for
   *   example:
   *   @code
   *     $this->createBlockContentType('system_powered_by_block', [
   *       'label' => t('Hello, world!'),
   *     ]);
   *   @endcode
   *   The following defaults are provided:
   *   - id: Random string.
   *   - label: Random string.
   *   - description: Random string.
   *   - revision: The default revision.
   *
   * @return \Drupal\Core\Entity\EntityInterface|\Drupal\block_content\Entity\BlockContentType
   *   The block content type entity.
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createBlockContentType(array $settings = []): EntityInterface {
    // Find a non-existent random id.
    if (!isset($settings['id'])) {
      do {
        $id = strtolower($this->randomMachineName(8));
      } while (BlockContentType::load($id));
    }
    else {
      $id = $settings['id'];
    }

    $settings += [
      'id' => $id,
      'label' => $this->randomMachineName(8),
      'description' => $this->randomString(16),
      'revision' => FALSE,
    ];
    foreach (['id', 'label', 'description', 'revision'] as $key) {
      $values[$key] = $settings[$key];
      // Remove extra values that do not belong in the settings array.
      unset($settings[$key]);
    }

    $blockContentType = BlockContentType::create($values);
    $blockContentType->save();

    return $blockContentType;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc