EntityAutocompleteMatcher.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace Drupal\materio_commerce;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Utility\Tags;
  5. class EntityAutocompleteMatcher extends \Drupal\Core\Entity\EntityAutocompleteMatcher {
  6. /**
  7. * Gets matched labels based on a given search string.
  8. */
  9. public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {
  10. $matches = [];
  11. $options = [
  12. 'target_type' => $target_type,
  13. 'handler' => $selection_handler,
  14. 'handler_settings' => $selection_settings,
  15. ];
  16. $handler = $this->selectionManager->getInstance($options);
  17. if (isset($string)) {
  18. // Get an array of matching entities.
  19. $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
  20. $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 10);
  21. // Loop through the entities and convert them into autocomplete output.
  22. foreach ($entity_labels as $values) {
  23. foreach ($values as $entity_id => $label) {
  24. $entity = \Drupal::entityTypeManager()->getStorage($target_type)->load($entity_id);
  25. $entity = \Drupal::entityManager()->getTranslationFromContext($entity);
  26. $key = $label . ' (' . $entity_id . ')';
  27. // Strip things like starting/trailing white spaces, line breaks and tags.
  28. $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
  29. // Names containing commas or quotes must be wrapped in quotes.
  30. $key = Tags::encode($key);
  31. switch ($entity->getEntityType()->id()) {
  32. case 'node':
  33. $type = !empty($entity->type->entity) ? $entity->type->entity->label() : $entity->bundle();
  34. $status = ($entity->isPublished()) ? ", Published" : ", Unpublished";
  35. break;
  36. case 'user':
  37. $email = $entity->getEmail();
  38. $label = $label . ' (' . $entity_id . ') [' . $email . ']';
  39. break;
  40. }
  41. $matches[] = ['value' => $key, 'label' => $label];
  42. }
  43. }
  44. }
  45. return $matches;
  46. }
  47. }