You are here

class TeamMembersSelection in Apigee Edge 8

Provides a team member entity selection plugin.

This user entity selection plugin excludes users from the list who do not have a developer account on Apigee Edge and who are already member of a given team.

Plugin annotation


@EntityReferenceSelection(
  id = "apigee_edge_teams:team_members",
  label = @Translation("Team member selection"),
  entity_types = {"user"},
  group = "apigee_edge_teams",
  weight = 1
)

Hierarchy

Expanded class hierarchy of TeamMembersSelection

File

modules/apigee_edge_teams/src/Plugin/EntityReferenceSelection/TeamMembersSelection.php, line 50

Namespace

Drupal\apigee_edge_teams\Plugin\EntityReferenceSelection
View source
class TeamMembersSelection extends UserSelection {

  /**
   * The team membership manager service.
   *
   * @var \Drupal\apigee_edge_teams\TeamMembershipManagerInterface
   */
  private $teamMembershipManager;

  /**
   * The developer controller service.
   *
   * @var \Drupal\apigee_edge\Entity\Controller\DeveloperControllerInterface
   */
  private $developerController;

  /**
   * The logger.
   *
   * @var \Psr\Log\LoggerInterface
   */
  private $logger;

  /**
   * TeamMembersSelection constructor.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   * @param \Drupal\apigee_edge_teams\TeamMembershipManagerInterface $team_membership_manager
   *   The team membership manager.
   * @param \Drupal\apigee_edge\Entity\Controller\DeveloperControllerInterface $developer_controller
   *   The developer controller service.
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, Connection $connection, TeamMembershipManagerInterface $team_membership_manager, DeveloperControllerInterface $developer_controller, LoggerInterface $logger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $module_handler, $current_user, $connection);
    $this->teamMembershipManager = $team_membership_manager;
    $this->developerController = $developer_controller;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('entity_type.manager'), $container
      ->get('module_handler'), $container
      ->get('current_user'), $container
      ->get('database'), $container
      ->get('apigee_edge_teams.team_membership_manager'), $container
      ->get('apigee_edge.controller.developer'), $container
      ->get('logger.channel.apigee_edge_teams'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $conf = parent::defaultConfiguration();
    $conf['filter']['team'] = NULL;
    return $conf;
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    $conf = parent::getConfiguration();

    // Anonymous user should never be displayed because it can not be assigned
    // to a team as member.
    $conf['include_anonymous'] = FALSE;
    return $conf;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->getConfiguration();
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['include_anonymous']['#access'] = FALSE;
    $team = $config['filter']['team'];
    if ($team !== NULL) {

      // Default value should be an entity object if team is set.
      // (If the team could not be loaded then the value remains null.)
      $team = $this->entityManager
        ->getStorage('team')
        ->load($team);
    }
    $form['filter']['team'] = [
      '#title' => $this
        ->t('Exclude members of this team'),
      '#type' => 'entity_autocomplete',
      '#target_type' => 'team',
      '#description' => $this
        ->t('Exclude users who are already member of the selected team.'),
      '#default_value' => $team,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {

    // Do not pass $match so that it does not add the "name" field to the query,
    // as we will search by email instead.
    $query = parent::buildEntityQuery(NULL, $match_operator);
    $match = trim($match);
    if ($match) {
      $query
        ->condition('mail', $match, $match_operator);
    }
    $config = $this
      ->getConfiguration();
    $team_name = $config['filter']['team'];

    // Exclude those users from the list who does not have a developer
    // account on Apigee Edge.
    // ("Add or Update Company Developers" API call would fail anyway if the
    // list of new members would contain any email address that does not
    // belong to an existing developer.)
    try {
      $existing_developers = $this->developerController
        ->getEntityIds();
    } catch (\Exception $exception) {

      // If list of existing developers (email addresses) could not be
      // retrieved then return an empty list.
      $query
        ->condition('mail', 0);
      $context = Error::decodeException($exception);
      $this->logger
        ->error("Unable to retrieve list of developer email addresses from Apigee Edge. @message %function (line %line of %file). <pre>@backtrace_string</pre>", $context);
      return $query;
    }
    if (empty($existing_developers)) {

      // If list of existing developers is empty then return an empty list
      // too. (Developers should be synced.)
      $query
        ->condition('mail', 0);
    }
    else {
      $query
        ->condition('mail', $existing_developers, 'IN');
    }

    // Do not display users who are already member of the team.
    if ($team_name) {
      try {
        $team_members = $this->teamMembershipManager
          ->getMembers($team_name);
        if (!empty($team_members)) {
          $query
            ->condition('mail', $team_members, 'NOT IN');
        }
      } catch (\Exception $exception) {

        // If team members could not be retrieved return an empty list.
        $query
          ->condition('mail', 0);
        $context = [
          '%team' => $team_name,
        ];
        $context += Error::decodeException($exception);
        $this->logger
          ->error("Unable to retrieve list of %team team from Apigee Edge. @message %function (line %line of %file). <pre>@backtrace_string</pre>", $context);
      }
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    $target_type = $this
      ->getConfiguration()['target_type'];
    $query = $this
      ->buildEntityQuery($match, $match_operator);
    if ($limit > 0) {
      $query
        ->range(0, $limit);
    }
    $result = $query
      ->execute();
    if (empty($result)) {
      return [];
    }
    $options = [];
    $entities = $this->entityTypeManager
      ->getStorage($target_type)
      ->loadMultiple($result);

    /* @var \Drupal\user\UserInterface $entity */
    foreach ($entities as $id => $entity) {
      $options[$target_type][$id] = $entity
        ->getEmail();
    }
    return $options;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DefaultSelection::$currentUser protected property The current user.
DefaultSelection::$deprecatedProperties protected property
DefaultSelection::$entityFieldManager protected property The entity field manager service.
DefaultSelection::$entityRepository protected property The entity repository.
DefaultSelection::$entityTypeBundleInfo public property Entity type bundle info service.
DefaultSelection::$entityTypeManager protected property The entity type manager service.
DefaultSelection::$moduleHandler protected property The module handler service.
DefaultSelection::countReferenceableEntities public function Counts entities that are referenceable. Overrides SelectionInterface::countReferenceableEntities 2
DefaultSelection::elementValidateFilter public static function Form element validation handler; Filters the #value property of an element.
DefaultSelection::reAlterQuery protected function Helper method: Passes a query to the alteration system again.
DefaultSelection::validateConfigurationForm public function Form validation handler. Overrides SelectionPluginBase::validateConfigurationForm
DefaultSelection::validateReferenceableEntities public function Validates which existing entities can be referenced. Overrides SelectionInterface::validateReferenceableEntities
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
SelectionPluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
SelectionPluginBase::ensureBackwardCompatibilityConfiguration protected function Ensures a backward compatibility level configuration.
SelectionPluginBase::resolveBackwardCompatibilityConfiguration protected function Moves the backward compatibility level configurations in the right place.
SelectionPluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
SelectionPluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TeamMembersSelection::$developerController private property The developer controller service.
TeamMembersSelection::$logger private property The logger.
TeamMembersSelection::$teamMembershipManager private property The team membership manager service.
TeamMembersSelection::buildConfigurationForm public function Form constructor. Overrides UserSelection::buildConfigurationForm
TeamMembersSelection::buildEntityQuery protected function Builds an EntityQuery to get referenceable entities. Overrides UserSelection::buildEntityQuery
TeamMembersSelection::create public static function Creates an instance of the plugin. Overrides UserSelection::create
TeamMembersSelection::defaultConfiguration public function Gets default configuration for this plugin. Overrides UserSelection::defaultConfiguration
TeamMembersSelection::getConfiguration public function Gets this plugin's configuration. Overrides SelectionPluginBase::getConfiguration
TeamMembersSelection::getReferenceableEntities public function Gets the list of referenceable entities. Overrides DefaultSelection::getReferenceableEntities
TeamMembersSelection::__construct public function TeamMembersSelection constructor. Overrides UserSelection::__construct
UserSelection::$connection protected property The database connection.
UserSelection::createNewEntity public function Creates a new entity object that can be used as a valid reference. Overrides DefaultSelection::createNewEntity
UserSelection::entityQueryAlter public function Allows the selection to alter the SelectQuery generated by EntityFieldQuery. Overrides SelectionPluginBase::entityQueryAlter
UserSelection::validateReferenceableNewEntities public function Validates which newly created entities can be referenced. Overrides DefaultSelection::validateReferenceableNewEntities