You are here

function commerce_promotion_update_8209 in Commerce Core 8.2

Add a 'uid' field to promotions.

File

modules/promotion/commerce_promotion.install, line 225
Install, update and uninstall functions for the commerce_promotion module.

Code

function commerce_promotion_update_8209() {
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();

  // Set the owner of the promotions to be first user which which has
  // the 'administrator' role. This way we avoid hard coding user ID 1 for sites
  // that prefer to not give it any special meaning.
  $admin_roles = \Drupal::entityTypeManager()
    ->getStorage('user_role')
    ->getQuery()
    ->condition('is_admin', TRUE)
    ->accessCheck(FALSE)
    ->execute();
  if (!empty($admin_roles)) {
    $query = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->getQuery()
      ->condition('roles', $admin_roles, 'IN')
      ->condition('status', 1)
      ->sort('uid', 'ASC')
      ->accessCheck(FALSE)
      ->range(0, 1);
    $result = $query
      ->execute();
  }

  // Defaults to user ID 1 if we could not find any other administrator users.
  $owner_id = !empty($result) ? reset($result) : 1;
  $entity_type = $definition_update_manager
    ->getEntityType('commerce_promotion');
  $keys = $entity_type
    ->getKeys();
  $keys['owner'] = 'uid';
  $entity_type
    ->set('entity_keys', $keys);
  $definition_update_manager
    ->updateEntityType($entity_type);
  $storage_definition = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Owner'))
    ->setDescription(t('The promotion owner.'))
    ->setSetting('target_type', 'user')
    ->setTranslatable(TRUE)
    ->setInitialValue($owner_id)
    ->setDefaultValueCallback(Promotion::class . '::getDefaultEntityOwner');
  $definition_update_manager
    ->installFieldStorageDefinition('uid', 'commerce_promotion', 'commerce_promotion', $storage_definition);

  /** @var \Drupal\user\RoleInterface $role */
  foreach (Role::loadMultiple() as $role) {
    if (!$role
      ->hasPermission('update commerce_promotion')) {
      continue;
    }
    $role
      ->grantPermission("update any commerce_promotion");
    $role
      ->save();
  }
}