You are here

public function PhpSelection::getReferenceableEntities in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/PhpSelection.php \Drupal\Core\Entity\Plugin\EntityReferenceSelection\PhpSelection::getReferenceableEntities()

Gets the list of referenceable entities.

Parameters

string|null $match: (optional) Text to match the label against. Defaults to NULL.

string $match_operator: (optional) Operator to be used for string matching. Defaults to "CONTAINS".

int $limit: (optional) Limit the query to a given number of items. Defaults to 0, which indicates no limiting.

Return value

array A nested array of entities, the first level is keyed by the entity bundle, which contains an array of entity labels (escaped), keyed by the entity ID.

Overrides DefaultSelection::getReferenceableEntities

1 call to PhpSelection::getReferenceableEntities()
PhpSelection::countReferenceableEntities in core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/PhpSelection.php
Counts entities that are referenceable.

File

core/lib/Drupal/Core/Entity/Plugin/EntityReferenceSelection/PhpSelection.php, line 21

Class

PhpSelection
Defines an alternative to the default Entity Reference Selection plugin.

Namespace

Drupal\Core\Entity\Plugin\EntityReferenceSelection

Code

public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {

  // No input, return everything from the entity query.
  if ($match === NULL || $match === '') {
    return parent::getReferenceableEntities($match, $match_operator, $limit);
  }

  // Start with the selection results returned by the entity query. Don't use
  // any limit because we have to apply a limit after filtering the items.
  $options = parent::getReferenceableEntities($match, $match_operator);

  // Always use a case-insensitive, escaped match. Entity labels returned by
  // SelectionInterface::getReferenceableEntities() are already escaped, so
  // the incoming $match needs to be escaped as well, making the comparison
  // possible.
  // @see \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface::getReferenceableEntities()
  if (is_string($match)) {
    $match = Html::escape(mb_strtolower($match));
  }
  elseif (is_array($match)) {
    array_walk($match, function (&$item) {
      $item = Html::escape(mb_strtolower($item));
    });
  }
  $filtered = [];
  $count = 0;

  // Filter target entities by the output of their label() method.
  foreach ($options as $bundle => &$items) {
    foreach ($items as $entity_id => $label) {
      if ($this
        ->matchLabel($match, $match_operator, $label)) {
        $filtered[$bundle][$entity_id] = $label;
        $count++;
        if ($limit && $count >= $limit) {
          break 2;
        }
      }
    }
  }
  return $filtered;
}