contacts_events-8.x-1.x-dev/modules/teams/src/Plugin/EntityReferenceSelection/TeamSelection.php
modules/teams/src/Plugin/EntityReferenceSelection/TeamSelection.php
<?php
namespace Drupal\contacts_events_teams\Plugin\EntityReferenceSelection;
use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
/**
* Ensures only active teams are available for selection.
*
* @EntityReferenceSelection(
* id = "active_teams:c_events_team",
* label = @Translation("Active Team selection"),
* entity_types = {"c_events_team"},
* group = "active_teams",
* weight = 1
* )
*/
class TeamSelection extends DefaultSelection {
/**
* {@inheritdoc}
*/
protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
/** @var \Drupal\contacts_events\Entity\Ticket $ticket */
$ticket = $this->configuration['entity'];
$q = parent::buildEntityQuery($match, $match_operator);
// Limit to teams that are for the same event.
$q->condition('event', $ticket->event->target_id);
// Limit to public teams unless the current user can manage all teams.
if (!$this->currentUser->hasPermission('manage contacts events teams')) {
$q->condition('public', TRUE);
}
$q->sort('name', 'ASC');
return $q;
}
/**
* {@inheritdoc}
*/
public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$ticket = $this->configuration['entity'];
$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);
foreach ($entities as $entity_id => $team) {
/** @var \Drupal\contacts_events_teams\Entity\Team $team */
$ticket_dob = strtotime($ticket->date_of_birth->value);
$event_date = strtotime($ticket->event->entity->date->value);
// Check the minimum age.
if ($team->age_min->value) {
$min_dob = strtotime("- {$team->age_min->value} years", $event_date);
if ($min_dob <= $ticket_dob) {
continue;
}
}
// Check the maximum age.
if ($team->age_max->value) {
$max_dob = strtotime("- {$team->age_max->value} years", $event_date);
if ($max_dob > $ticket_dob) {
continue;
}
}
$bundle = $team->bundle();
$options[$bundle][$entity_id] = Html::escape($this->entityRepository->getTranslationFromContext($team)->label());
}
return $options;
}
}
