You are here

public function BlocksController::exportBlocks in Structure Sync 8

Same name and namespace in other branches
  1. 2.x src/Controller/BlocksController.php \Drupal\structure_sync\Controller\BlocksController::exportBlocks()

Function to export custom blocks.

File

src/Controller/BlocksController.php, line 37

Class

BlocksController
Controller for syncing custom blocks.

Namespace

Drupal\structure_sync\Controller

Code

public function exportBlocks(array $form = NULL, FormStateInterface $form_state = NULL) {
  StructureSyncHelper::logMessage('Custom blocks export started');
  if (is_object($form_state) && $form_state
    ->hasValue('export_block_list')) {
    $blockList = $form_state
      ->getValue('export_block_list');
    $blockList = array_filter($blockList, 'is_string');
  }
  $this->config
    ->clear('blocks')
    ->save();
  if (isset($blockList)) {
    $blocks = [];
    foreach ($blockList as $blockUuid) {
      $blocks = array_merge($this->entityTypeManager
        ->getStorage('block_content')
        ->loadByProperties([
        'uuid' => $blockUuid,
      ]), $blocks);
    }
  }
  else {
    $blocks = $this->entityTypeManager
      ->getStorage('block_content')
      ->loadMultiple();
  }
  $customBlocks = [];
  foreach ($blocks as $block) {
    $customBlock = [
      'info' => $block->info
        ->getValue()[0]['value'],
      'langcode' => $block->langcode
        ->getValue()[0]['value'],
      'uuid' => $block
        ->uuid(),
      'bundle' => $block
        ->bundle(),
      'revision_id' => null,
      'rev_id_current' => null,
    ];
    $entityFieldManager = StructureSyncHelper::getEntityFieldManager();
    $fields = $entityFieldManager
      ->getFieldDefinitions('block_content', $block
      ->bundle());
    foreach ($fields as $key => $field) {
      if ($field
        ->getFieldStorageDefinition()
        ->isBaseField()) {
        unset($fields[$key]);
      }
    }
    foreach ($fields as $field) {
      $fieldName = $field
        ->getName();
      $customBlock['fields'][$fieldName] = $block->{$fieldName}
        ->getValue()[0];
    }
    $customBlocks[] = $customBlock;
  }
  $this->config
    ->set('blocks', $customBlocks)
    ->save();
  foreach ($customBlocks as $customBlock) {
    if (array_key_exists('drush', $form) && $form['drush'] === TRUE) {
      drush_log('Exported "' . $customBlock['info'] . '"', 'ok');
    }
    StructureSyncHelper::logMessage('Exported "' . $customBlock['info'] . '"');
  }
  drupal_set_message($this
    ->t('The custom blocks have been successfully exported.'));
  StructureSyncHelper::logMessage('Custom blocks exported');
}