Completed
Push — master ( 13addc...b67001 )
by Jonathan
01:36
created

AddressHandler   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 1
dl 0
loc 58
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B expand() 0 51 8
1
<?php
2
3
namespace Drupal\Driver\Fields\Drupal8;
4
5
/**
6
 * Address field handler for Drupal 8.
7
 */
8
class AddressHandler extends AbstractHandler {
9
10
  /**
11
   * {@inheritdoc}
12
   */
13
  public function expand($values) {
14
    $return = array();
15
    $overrides = $this->fieldConfig->getSettings()['field_overrides'];
16
    $addressFields = array(
17
      "given_name" => 1,
18
      "additional_name" => 1,
19
      "family_name" => 1,
20
      "organization" => 1,
21
      "address_line1" => 1,
22
      "address_line2" => 1,
23
      "postal_code" => 1,
24
      "sorting_code" => 1,
25
      "locality" => 1,
26
      "administrative_area" => 1,
27
    );
28
    // Any overrides that set field inputs to hidden will be skipped.
29
    foreach ($overrides as $key => $value) {
30
      preg_match('/[A-Z]/', $key, $matches, PREG_OFFSET_CAPTURE);
31
      if (count($matches) > 0) {
32
        $fieldName = strtolower(substr_replace($key, '_', $matches[0][1], 0));
33
      }
34
      else {
35
        $fieldName = $key;
36
      }
37
      if ($value['override'] == 'hidden') {
38
        unset($addressFields[$fieldName]);
39
      }
40
    }
41
    // The remaining field components will be populated in order, using
42
    // values as they are ordered in feature step.
43
    foreach ($values as $value) {
44
      $idx = 0;
45
      foreach ($addressFields as $k => $v) {
46
        // If the values array contains only one item, assign it to the first
47
        // field component and break.
48
        if (is_string($value)) {
49
          $return[$k] = $value;
50
          break;
51
        }
52
        if ($idx < count($value)) {
53
          // Gracefully handle users providing too few field component values.
54
          $return[$k] = $value[$idx];
55
          $idx++;
56
        }
57
      }
58
      // Set the country code to the first available as configured in this
59
      // instance of the field.
60
      $return['country_code'] = reset($this->fieldConfig->getSettings()['available_countries']);
61
    }
62
    return array($return);
63
  }
64
65
}
66