Completed
Pull Request — master (#114)
by
unknown
01:43
created

EntityReferenceHandler::expand()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 30
rs 5.3846
cc 8
eloc 19
nc 20
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
    $label_key = $entity_definition->getKey('label');
18
19
    if (!$label_key && $entity_type_id == 'user') {
20
      $label_key = 'name';
21
    }
22
23
    // Determine target bundle restrictions.
24
    $target_bundle_key = NULL;
25
    if (!$target_bundles = $this->getTargetBundles()) {
26
      $target_bundle_key = $entity_definition->getKey('bundle');
27
    }
28
29
    foreach ((array) $values as $value) {
30
      $query = \Drupal::entityQuery($entity_type_id)->condition($label_key, $value);
31
      if ($target_bundles && $target_bundle_key) {
32
        $query->condition($target_bundle_key, $target_bundles, 'IN');
33
      }
34
      if ($entities = $query->execute()) {
35
        $return[] = array_shift($entities);
36
      }
37
      else {
38
        throw new \Exception(sprintf("No entity '%s' of type '%s' exists.", $value, $entity_type_id));
39
      }
40
    }
41
    return $return;
42
  }
43
44
  /**
45
   * Retrieves bundles for which the field is configured to reference.
46
   *
47
   * @return mixed
48
   *   Array of bundle names, or NULL if not able to determine bundles.
49
   */
50
  protected function getTargetBundles() {
51
    $settings = $this->fieldConfig->getSettings();
52
    if (!empty($settings['handler_settings']['target_bundles'])) {
53
      return $settings['handler_settings']['target_bundles'];
54
    }
55
  }
56
57
}
58