Completed
Pull Request — master (#191)
by
unknown
04:14
created

AddressHandler::expand()   C

Complexity

Conditions 8
Paths 20

Size

Total Lines 49
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

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