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