|
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 = []; |
|
15
|
|
|
$entity_type_id = $this->fieldInfo->getSetting('target_type'); |
|
16
|
|
|
$entity_definition = \Drupal::entityTypeManager()->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
|
|
|
$query->accessCheck(FALSE); |
|
40
|
|
|
if ($target_bundles && $target_bundle_key) { |
|
41
|
|
|
$query->condition($target_bundle_key, $target_bundles, 'IN'); |
|
42
|
|
|
} |
|
43
|
|
|
if ($entities = $query->execute()) { |
|
44
|
|
|
$return[] = array_shift($entities); |
|
45
|
|
|
} |
|
46
|
|
|
else { |
|
47
|
|
|
throw new \Exception(sprintf("No entity '%s' of type '%s' exists.", $value, $entity_type_id)); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
return $return; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Retrieves bundles for which the field is configured to reference. |
|
55
|
|
|
* |
|
56
|
|
|
* @return mixed |
|
57
|
|
|
* Array of bundle names, or NULL if not able to determine bundles. |
|
58
|
|
|
*/ |
|
59
|
|
|
protected function getTargetBundles() { |
|
60
|
|
|
$settings = $this->fieldConfig->getSettings(); |
|
61
|
|
|
if (!empty($settings['handler_settings']['target_bundles'])) { |
|
62
|
|
|
return $settings['handler_settings']['target_bundles']; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
} |
|
67
|
|
|
|