Completed
Push — 1.3 ( a3940d )
by Jonathan
01:17
created

EntityReferenceHandler::expand()   C

Complexity

Conditions 7
Paths 20

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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