function BlockRepository::getUniqueMachineName

Same name in other branches
  1. 11.x core/modules/block/src/BlockRepository.php \Drupal\block\BlockRepository::getUniqueMachineName()

File

core/modules/block/src/BlockRepository.php, line 89

Class

BlockRepository
Provides a repository for Block config entities.

Namespace

Drupal\block

Code

public function getUniqueMachineName(string $suggestion, ?string $theme = NULL) : string {
    if ($theme) {
        $suggestion = $theme . '_' . $suggestion;
    }
    // Get all the block machine names that begin with the suggested string.
    $query = $this->blockStorage
        ->getQuery();
    $query->accessCheck(FALSE);
    $query->condition('id', $suggestion, 'CONTAINS');
    $block_ids = $query->execute();
    $block_ids = array_map(function ($block_id) {
        $parts = explode('.', $block_id);
        return end($parts);
    }, $block_ids);
    // Iterate through potential IDs until we get a new one. E.g.
    // For example, 'plugin', 'plugin_2', 'plugin_3', etc.
    $count = 1;
    $machine_default = $suggestion;
    while (in_array($machine_default, $block_ids)) {
        $machine_default = $suggestion . '_' . ++$count;
    }
    return $machine_default;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.