Skip to content

Commit

Permalink
Support single address fields in WrapperField.
Browse files Browse the repository at this point in the history
  • Loading branch information
torotil committed Feb 14, 2018
1 parent 17ef441 commit bd86af3
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 7 deletions.
22 changes: 15 additions & 7 deletions src/CRM/Export/WrapperField.php
Expand Up @@ -11,17 +11,25 @@ public function __construct($key) {
$this->key = $key;
}

/**
* Get value(s) for this field.
*
* @return mixed
* - NULL if the field doesn’t exist.
* - A single field value if $delta is given and not NULL.
* - All values as an array if $delta is NULL.
*/
public function value($delta = 0) {
$w = $this->exporter->getWrappedContact();
if ($w->__isset($this->key)) {
$value = $w->{$this->key}->value();
if (isset($delta) && is_array($value) && isset($value[$delta])) {
return $value[$delta];
}
return $value;
if (!$w->__isset($this->key)) {
return NULL;
}
$field = $w->{$this->key};
if ($field instanceof \EntityListWrapper) {
return is_null($delta) ? $field->value() : $field->get($delta)->value();
}
else {
return NULL;
return is_null($delta) ? [$field->value()] : $field->value();
}
}

Expand Down
52 changes: 52 additions & 0 deletions test/CRM/Export/WrapperFieldTest.php
@@ -0,0 +1,52 @@
<?php

namespace Drupal\campaignion\CRM\Export;

use Drupal\campaignion\CRM\ExporterBase;

/**
* Test the WrapperField exporter.
*/
class WrapperFieldTest extends \DrupalUnitTestCase {

/**
* Prepare a contact and exporter object for testing.
*
* We use the contact type provided by the campaignion_test module here.
*/
public function setUp() {
$this->contact = entity_create('redhen_contact', ['type' => 'contact']);
$w = $this->contact->wrap();
$w->field_address->set([[
'country' => 'GB',
]]);
$w->field_gender->set('o');
$this->exporter = new ExporterBase([]);
$this->exporter->setContact($this->contact);
}

/**
* Test getting values from a multi-value field.
*/
public function testMultiValueField() {
$w = new WrapperField('field_address');
$w->setExporter($this->exporter);
$this->assertEqual(['country' => 'GB'], $w->value());
$this->assertEqual(['country' => 'GB'], $w->value(0));
$this->assertEqual([['country' => 'GB']], $w->value(NULL));
$this->assertNull($w->value(1));
}

/**
* Test getting values from a single value field.
*/
public function testSingleValueField() {
$w = new WrapperField('field_gender');
$w->setExporter($this->exporter);
$this->assertEqual('o', $w->value());
$this->assertEqual('o', $w->value(0));
$this->assertEqual(['o'], $w->value(NULL));
$this->assertEqual('o', $w->value(1));
}

}

0 comments on commit bd86af3

Please sign in to comment.