Completed
Pull Request — master (#114)
by
unknown
04:59
created

EntityReferenceHandler::expand()   D

Complexity

Conditions 9
Paths 40

Size

Total Lines 38
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 0
loc 38
rs 4.909
c 4
b 0
f 0
cc 9
eloc 22
nc 40
nop 1
1
<?php
2
3
namespace Drupal\Driver\Fields\Drupal8;
4
5
/**
6
 * Entity Reference field handler for Drupal 8.
7
 */
8
class EntityReferenceHandler extends AbstractHandler {
9
10
  /**
11
   * {@inheritdoc}
12
   */
13
  public function expand($values) {
14
    $return = array();
15
    $entity_type_id = $this->fieldInfo->getSetting('target_type');
16
    $entity_definition = \Drupal::entityManager()->getDefinition($entity_type_id);
17
18
    // Determine label field key.
19
    if ($entity_type_id !== 'user') {
20
      $label_key = $entity_definition->getKey('label');
21
    }
22
    else {
23
      // Entity Definition->getKey('label') returns false for users.
24
      $label_key = 'name';
25
    }
26
27
    if (!$label_key && $entity_type_id == 'user') {
28
      $label_key = 'name';
29
    }
30
31
    // Determine target bundle restrictions.
32
    $target_bundle_key = NULL;
33
    if ($target_bundles = $this->getTargetBundles()) {
34
      $target_bundle_key = $entity_definition->getKey('bundle');
35
    }
36
37
    foreach ((array) $values as $value) {
38
      $query = \Drupal::entityQuery($entity_type_id)->condition($label_key, $value);
39
      if ($target_bundles && $target_bundle_key) {
40
        $query->condition($target_bundle_key, $target_bundles, 'IN');
41
      }
42
      if ($entities = $query->execute()) {
43
        $return[] = array_shift($entities);
44
      }
45
      else {
46
        throw new \Exception(sprintf("No entity '%s' of type '%s' exists.", $value, $entity_type_id));
47
      }
48
    }
49
    return $return;
50
  }
51
52
  /**
53
   * Retrieves bundles for which the field is configured to reference.
54
   *
55
   * @return mixed
56
   *   Array of bundle names, or NULL if not able to determine bundles.
57
   */
58
  protected function getTargetBundles() {
59
    $settings = $this->fieldConfig->getSettings();
60
    if (!empty($settings['handler_settings']['target_bundles'])) {
61
      return $settings['handler_settings']['target_bundles'];
62
    }
63
  }
64
65
}
66