Unverified Commit cb6abd75 authored by Mateu Aguiló Bosch's avatar Mateu Aguiló Bosch
Browse files

feat: allow a default consumer without negotiation

parent 877113e0
Loading
Loading
Loading
Loading
+46 −1
Original line number Diff line number Diff line
@@ -9,6 +9,17 @@ use Drupal\consumers\Entity\Consumer;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Implements hook_install().
 */
function consumers_install() {
  Consumer::create([
    'label' => 'Default Consumer',
    'description' => 'This is the default consumer. This was created programmatically when the Consumers module was first installed. Feel free to edit, or delete this.',
    'is_default' => TRUE,
  ])->save();
}

/**
 * Add field 'third_party' when not exist.
 */
@@ -47,7 +58,6 @@ function consumers_update_8102() {
 * Make consumers translatable.
 */
function consumers_update_8103() {

  $entity_definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  $entity_type = $entity_definition_update_manager->getEntityType('consumer');
  $last_installed_field_storage_definitions = \Drupal::service('entity.last_installed_schema.repository')->getLastInstalledFieldStorageDefinitions('consumer');
@@ -116,3 +126,38 @@ function consumers_update_8103() {
  }

}

/**
 * Add field 'is_default'.
 */
function consumers_update_8104() {
  $field_definition = BaseFieldDefinition::create('boolean')
    ->setLabel(new TranslatableMarkup('Is this the default consumer?'))
    ->setDescription(new TranslatableMarkup('There can only be one default consumer. Mark this to use this consumer when none other applies.'))
    ->setDisplayOptions('view', [
      'label' => 'inline',
      'type' => 'boolean',
      'weight' => 4,
    ])
    ->setDisplayOptions('form', [
      'weight' => 4,
    ])
    ->setRevisionable(TRUE)
    ->setTranslatable(TRUE)
    ->setDefaultValue(FALSE)
    ->setInitialValue(FALSE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('is_default', 'consumer', 'consumers', $field_definition);
}

/**
 * Create a default consumer.
 */
function consumers_update_8105() {
  Consumer::create([
    'label' => 'Default Consumer',
    'description' => 'This is the default consumer. This was created programmatically when the Consumers module was first installed. Feel free to edit, or delete this.',
    'is_default' => TRUE,
  ])->save();
}
+1 −0
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ services:
    arguments: ['@request_stack', '@entity.repository']
    calls:
      - [setLogger, ['@logger.channel.consumers']]
      - [setEntityStorage, ['@entity_type.manager']]

  logger.channel.consumers:
    parent: logger.channel_base
+35 −0
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace Drupal\consumers;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityListBuilder;
use Drupal\Core\Url;

/**
 * Defines a class to build a listing of Access Token entities.
@@ -16,6 +17,7 @@ class ConsumerListBuilder extends EntityListBuilder {
  public function buildHeader() {
    $header['uuid'] = $this->t('UUID');
    $header['label'] = $this->t('Label');
    $header['is_default'] = $this->t('Is Default?');
    $context = ['type' => 'header'];
    $this->moduleHandler()->alter('consumers_list', $header, $context);
    $header = $header + parent::buildHeader();
@@ -29,6 +31,20 @@ class ConsumerListBuilder extends EntityListBuilder {
    /* @var $entity \Drupal\consumers\Entity\Consumer */
    $row['uuid'] = $entity->uuid();
    $row['label'] = $entity->toLink();
    $ops = [
      '#type' => 'operations',
      '#links' => [
        [
          'title' => $this->t('Make Default'),
          'url' => $entity->toUrl('make-default-form', [
            'query' => $this->getDestinationArray(),
          ]),
        ],
      ],
    ];
    $row['is_default'] = $entity->get('is_default')->value
      ? ['data' => $this->t('Default')]
      : ['data' => $ops];

    $context = ['type' => 'row', 'entity' => $entity];
    $this->moduleHandler()->alter('consumers_list', $row, $context);
@@ -36,4 +52,23 @@ class ConsumerListBuilder extends EntityListBuilder {
    return $row;
  }

  /**
   * {@inheritdoc}
   */
  public function getOperations(EntityInterface $entity) {
    $operations = parent::getOperations($entity);
    if (
      $entity->access('update') &&
      $entity->hasLinkTemplate('make-default-form') &&
      !$entity->get('is_default')->value
    ) {
      $operations['make-default'] = [
        'title' => $this->t('Make Default'),
        'weight' => 10,
        'url' => $this->ensureDestination($entity->toUrl('make-default-form')),
      ];
    }
    return $operations;
  }

}
+68 −26
Original line number Diff line number Diff line
@@ -8,6 +8,8 @@ use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\user\EntityOwnerInterface;
use Drupal\user\EntityOwnerTrait;

/**
 * Defines the Consumer entity.
@@ -22,9 +24,10 @@ use Drupal\Core\StringTranslation\TranslatableMarkup;
 *       "add" = "Drupal\consumers\Entity\Form\ConsumerForm",
 *       "edit" = "Drupal\consumers\Entity\Form\ConsumerForm",
 *       "delete" = "Drupal\Core\Entity\ContentEntityDeleteForm",
 *       "make-default" = "Drupal\consumers\Entity\Form\MakeDefaultForm",
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider",
 *       "html" = "Drupal\consumers\Entity\Routing\HtmlRouteProvider",
 *     },
 *     "views_data" = "\Drupal\views\EntityViewsData",
 *     "access" = "Drupal\consumers\AccessControlHandler",
@@ -38,25 +41,34 @@ use Drupal\Core\StringTranslation\TranslatableMarkup;
 *     "label" = "label",
 *     "uuid" = "uuid",
 *     "langcode" = "langcode",
 *     "owner" = "owner_id",
 *   },
 *   links = {
 *     "canonical" = "/admin/config/services/consumer/{consumer}",
 *     "collection" = "/admin/config/services/consumer",
 *     "add-form" = "/admin/config/services/consumer/add",
 *     "edit-form" = "/admin/config/services/consumer/{consumer}/edit",
 *     "delete-form" = "/admin/config/services/consumer/{consumer}/delete"
 *     "delete-form" = "/admin/config/services/consumer/{consumer}/delete",
 *     "make-default-form" = "/admin/config/services/consumer/{consumer}/make-default",
 *   }
 * )
 */
class Consumer extends ContentEntityBase {
class Consumer extends ContentEntityBase implements EntityOwnerInterface {

  use EntityChangedTrait;
  use EntityOwnerTrait;

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);
    $was_not_default = is_null($this->original)
      || !$this->original->get('is_default')->value;
    if ($this->get('is_default')->value && $was_not_default) {
      // If we are making this the new default consumer.
      $this->removeDefaultConsumerFlags();
    }

    foreach (array_keys($this->getTranslationLanguages()) as $langcode) {
      $translation = $this->getTranslation($langcode);
@@ -73,23 +85,7 @@ class Consumer extends ContentEntityBase {
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['owner_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(new TranslatableMarkup('Authored by'))
      ->setDescription(new TranslatableMarkup('The username of the consumer author.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback('Drupal\consumers\Entity\Consumer::getCurrentUserId')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ])
      ->setDisplayOptions('form', [
        'type' => 'hidden',
      ])
      ->setDisplayConfigurable('form', TRUE);
    $fields += static::ownerBaseFieldDefinitions($entity_type);

    $fields['label'] = BaseFieldDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Label'))
@@ -160,19 +156,65 @@ class Consumer extends ContentEntityBase {
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE);

    $fields['is_default'] = BaseFieldDefinition::create('boolean')
      ->setLabel(new TranslatableMarkup('Is this the default consumer?'))
      ->setDescription(new TranslatableMarkup('There can only be one default consumer. Mark this to use this consumer when none other applies.'))
      ->setDisplayOptions('view', [
        'label' => 'inline',
        'type' => 'boolean',
        'weight' => 4,
      ])
      ->setDisplayOptions('form', [
        'weight' => 4,
      ])
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDefaultValue(FALSE);

    return $fields;
  }

  /**
   * Default value callback for 'uid' base field definition.
   * Removes the is_default flag from other consumers.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  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
      );
    }
    array_map([$entity_storage, 'save'], $default_entities);
  }

  /**
   * Gets closure that will set is_default to the selected value for an entity.
   *
   * @see ::baseFieldDefinitions()
   * @param boolean $value
   *   The final value of the "is_default" field.
   *
   * @return array
   *   An array of default values.
   * @return \Closure
   */
  public static function getCurrentUserId() {
    return [\Drupal::currentUser()->id()];
  protected static function setDefaultTo($value) {
    return function (Consumer $consumer) use ($value) {
      $consumer->set('is_default', $value);
      return $consumer;
    };
  }

}
+10 −0
Original line number Diff line number Diff line
@@ -10,6 +10,16 @@ use Drupal\Core\Form\FormStateInterface;
 */
class ConsumerForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $form['is_default']['#access'] = FALSE;
    return $form;
  }


  /**
   * {@inheritdoc}
   */
Loading