You are here

function entity_legal_update_8200 in Entity Legal 8.2

Same name and namespace in other branches
  1. 4.0.x entity_legal.install \entity_legal_update_8200()
  2. 3.0.x entity_legal.install \entity_legal_update_8200()

Move the published version field in the legal document version entity.

File

./entity_legal.install, line 73
Install, update and uninstall functions for the entity_legal module.

Code

function entity_legal_update_8200(array &$sandbox) {
  if (!isset($sandbox['published'])) {

    // Create the 'published' base field.
    $manger = \Drupal::entityDefinitionUpdateManager();
    $published = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Published'))
      ->setDescription(t('If this is the published version of the legal document.'))
      ->setRequired(TRUE)
      ->setDefaultValue(FALSE)
      ->setCardinality(1)
      ->setConstraints([
      'SingleLegalDocumentPublishedVersion' => [],
    ])
      ->setInitialValue(FALSE);
    $manger
      ->installFieldStorageDefinition('published', 'entity_legal_document_version', 'entity_legal', $published);

    // Remove the 'published_version' field from config entities but save the
    // values first. Operating on database level, to avoid using the API.
    $db = \Drupal::database();
    $items = $db
      ->select('config')
      ->fields('config')
      ->condition('name', 'entity_legal.document.%', 'LIKE')
      ->execute()
      ->fetchAll();
    $sandbox['published'] = [];
    foreach ($items as $item) {
      $data = unserialize($item->data);
      $sandbox['published'][] = $data['published_version'];
      unset($data['published_version']);
      $db
        ->update('config')
        ->fields([
        'data' => serialize($data),
      ])
        ->condition('collection', $item->collection)
        ->condition('name', $item->name)
        ->execute();
    }
  }
  $ids_to_process = array_splice($sandbox['published'], 0, 10);

  /** @var \Drupal\entity_legal\EntityLegalDocumentVersionInterface $entity */
  foreach (EntityLegalDocumentVersion::loadMultiple($ids_to_process) as $entity) {
    $entity
      ->publish()
      ->save();
  }
  $sandbox['#finished'] = (int) empty($sandbox['published']);
}