Completed
Push — 139-update-coding-standards ( a80972...ee87f1 )
by Jonathan
01:23
created

AbstractHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 6
Bugs 1 Features 0
Metric Value
wmc 6
c 6
b 1
f 0
lcom 0
cbo 0
dl 0
loc 54
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 24 6
1
<?php
2
3
namespace Drupal\Driver\Fields\Drupal8;
4
5
use Drupal\Driver\Fields\FieldHandlerInterface;
6
7
/**
8
 * Base class for field handlers in Drupal 8.
9
 */
10
abstract class AbstractHandler implements FieldHandlerInterface {
11
  /**
12
   * Field storage definition.
13
   *
14
   * @var \Drupal\field\Entity\FieldStorageConfig
15
   */
16
  protected $fieldInfo = NULL;
17
18
  /**
19
   * Field configuration definition.
20
   *
21
   * @var \Drupal\field\Entity\FieldConfig
22
   */
23
  protected $fieldConfig = NULL;
24
25
  /**
26
   * Constructs an AbstractHandler object.
27
   *
28
   * @param \stdClass $entity
29
   *   The simulated entity object containing field information.
30
   * @param string $entity_type
31
   *   The entity type.
32
   * @param string $field_name
33
   *   The field name.
34
   *
35
   * @throws \Exception
36
   *   Thrown when the given field name does not exist on the entity.
37
   */
38
  public function __construct(\stdClass $entity, $entity_type, $field_name) {
39
    if (empty($entity_type)) {
40
      throw new \Exception("You must specify an entity type in order to parse entity fields.");
41
    }
42
    $entity_manager = \Drupal::entityManager();
43
    $fields = $entity_manager->getFieldStorageDefinitions($entity_type);
44
    $this->fieldInfo = $fields[$field_name];
45
46
    // The bundle may be stored either under "step_bundle" or under the name
47
    // of the entity's bundle key. If both are empty, assume this is a single
48
    // bundle entity, and therefore make the bundle name the entity type.
49
    $bundle_key = $entity_manager->getDefinition($entity_type)->getKey('bundle');
50
    $bundle = !empty($entity->$bundle_key) ? $entity->$bundle_key : (isset($entity->step_bundle) ? $entity->step_bundle : $entity_type);
51
52
    $fields = $entity_manager->getFieldDefinitions($entity_type, $bundle);
53
    $fieldsstring = '';
54
    foreach ($fields as $key => $value) {
55
      $fieldsstring = $fieldsstring . ", " . $key;
56
    }
57
    if (empty($fields[$field_name])) {
58
      throw new \Exception(sprintf('The field "%s" does not exist on entity type "%s" bundle "%s".', $field_name, $entity_type, $bundle));
59
    }
60
    $this->fieldConfig = $fields[$field_name];
61
  }
62
63
}
64