EntityAutocompleteMatcher.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace Drupal\Core\Entity;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Utility\Tags;
  5. use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
  6. /**
  7. * Matcher class to get autocompletion results for entity reference.
  8. */
  9. class EntityAutocompleteMatcher implements EntityAutocompleteMatcherInterface {
  10. /**
  11. * The entity reference selection handler plugin manager.
  12. *
  13. * @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface
  14. */
  15. protected $selectionManager;
  16. /**
  17. * Constructs a EntityAutocompleteMatcher object.
  18. *
  19. * @param \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface $selection_manager
  20. * The entity reference selection handler plugin manager.
  21. */
  22. public function __construct(SelectionPluginManagerInterface $selection_manager) {
  23. $this->selectionManager = $selection_manager;
  24. }
  25. /**
  26. * {@inheritDoc}
  27. */
  28. public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {
  29. $matches = [];
  30. $options = $selection_settings + [
  31. 'target_type' => $target_type,
  32. 'handler' => $selection_handler,
  33. ];
  34. $handler = $this->selectionManager->getInstance($options);
  35. if (isset($string)) {
  36. // Get an array of matching entities.
  37. $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
  38. $match_limit = isset($selection_settings['match_limit']) ? (int) $selection_settings['match_limit'] : 10;
  39. $entity_labels = $handler->getReferenceableEntities($string, $match_operator, $match_limit);
  40. // Loop through the entities and convert them into autocomplete output.
  41. foreach ($entity_labels as $values) {
  42. foreach ($values as $entity_id => $label) {
  43. $key = "$label ($entity_id)";
  44. // Strip things like starting/trailing white spaces, line breaks and
  45. // tags.
  46. $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
  47. // Names containing commas or quotes must be wrapped in quotes.
  48. $key = Tags::encode($key);
  49. $matches[] = ['value' => $key, 'label' => $label];
  50. }
  51. }
  52. }
  53. return $matches;
  54. }
  55. }