You are here

function domain_access_presave_generate in Domain Access 8

Handles presave operations for devel generate.

2 calls to domain_access_presave_generate()
domain_access_node_presave in domain_access/domain_access.module
Implements hook_ENTITY_TYPE_presave().
domain_access_user_presave in domain_access/domain_access.module
Implements hook_ENTITY_TYPE_presave().

File

domain_access/domain_access.module, line 159
Domain-based access control for content.

Code

function domain_access_presave_generate(EntityInterface $entity) {
  if (!$entity
    ->hasField(DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD)) {
    return;
  }

  // There is a core bug https://www.drupal.org/node/2609252 that causes a
  // fatal database errors if the boolean DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD is set when
  // a user cannot access the field. See domain_access_entity_field_access().
  // To overcome this issue, we cast the boolean to integer, which prevents the
  // failure.
  $value = (int) $entity
    ->get(DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD)->value;
  $entity
    ->set(DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD, $value);

  // Handle devel module settings.
  $exists = \Drupal::moduleHandler()
    ->moduleExists('devel_generate');
  $values = [];
  if ($exists && isset($entity->devel_generate)) {

    // If set by the form.
    if (isset($entity->devel_generate['domain_access'])) {
      $selection = array_filter($entity->devel_generate['domain_access']);
      if (isset($selection['random-selection'])) {
        $domains = \Drupal::entityTypeManager()
          ->getStorage('domain')
          ->loadMultiple();
        $values[DomainAccessManagerInterface::DOMAIN_ACCESS_FIELD] = array_rand($domains, ceil(rand(1, count($domains))));
      }
      else {
        $values[DomainAccessManagerInterface::DOMAIN_ACCESS_FIELD] = array_keys($selection);
      }
    }
    if (isset($entity->devel_generate['domain_all'])) {
      $selection = $entity->devel_generate['domain_all'];
      if ($selection == 'random-selection') {
        $values[DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD] = rand(0, 1);
      }
      else {
        $values[DomainAccessManagerInterface::DOMAIN_ACCESS_ALL_FIELD] = $selection = 'yes' ? 1 : 0;
      }
    }
    foreach ($values as $name => $value) {
      $entity
        ->set($name, $value);
    }
  }
}