You are here

protected function Consumer::removeDefaultConsumerFlags in Consumers 8

Removes the is_default flag from other consumers.

Throws

\Drupal\Component\Plugin\Exception\PluginException

\Drupal\Core\Access\AccessException

1 call to Consumer::removeDefaultConsumerFlags()
Consumer::preSave in src/Entity/Consumer.php
Acts on an entity before the presave hook is invoked.

File

src/Entity/Consumer.php, line 192

Class

Consumer
Defines the Consumer entity.

Namespace

Drupal\consumers\Entity

Code

protected function removeDefaultConsumerFlags() {

  // Find the old defaults.
  $entity_storage = $this
    ->entityTypeManager()
    ->getStorage($this
    ->getEntityTypeId());
  $entity_ids = $entity_storage
    ->getQuery()
    ->condition('is_default', TRUE)
    ->condition('id', $this
    ->id(), '!=')
    ->execute();
  $entity_ids = $entity_ids ? array_values($entity_ids) : [];
  if (empty($entity_ids)) {
    $default_entities = [];
  }
  else {
    $default_entities = $entity_storage
      ->loadMultiple($entity_ids);
    $default_entities = array_map(static::setDefaultTo(FALSE), $default_entities);
    $invalid_entities = array_filter($default_entities, function (Consumer $consumer) {
      return !$consumer
        ->access('update', NULL, TRUE)
        ->isAllowed();
    });
    if (count($invalid_entities)) {
      throw new AccessException('Unable to change the current default consumer. Permission denied.');
    }
  }
  array_map([
    $entity_storage,
    'save',
  ], $default_entities);
}