Tests using typed data lists.
public function testTypedDataLists() {
// Test working with an existing list of strings.
$value = array(
'one',
'two',
'three',
);
$typed_data = $this
->createTypedData(array(
'type' => 'string',
'list' => TRUE,
), $value);
$this
->assertEqual($typed_data
->getValue(), $value, 'List value has been set.');
// Test iterating.
$count = 0;
foreach ($typed_data as $item) {
$this
->assertTrue($item instanceof \Drupal\Core\TypedData\TypedDataInterface);
$count++;
}
$this
->assertEqual($count, 3);
// Test getting the string representation.
$this
->assertEqual($typed_data
->getString(), 'one, two, three');
$typed_data[1] = '';
$this
->assertEqual($typed_data
->getString(), 'one, three');
// Test using array access.
$this
->assertEqual($typed_data[0]
->getValue(), 'one');
$typed_data[4] = 'four';
$this
->assertEqual($typed_data[4]
->getValue(), 'four');
$typed_data[] = 'five';
$this
->assertEqual($typed_data[5]
->getValue(), 'five');
$this
->assertEqual($typed_data
->count(), 5);
$this
->assertTrue(isset($typed_data[0]));
$this
->assertTrue(!isset($typed_data[6]));
// Test isEmpty and cloning.
$this
->assertFalse($typed_data
->isEmpty());
$clone = clone $typed_data;
$this
->assertTrue($typed_data
->getValue() === $clone
->getValue());
$this
->assertTrue($typed_data[0] !== $clone[0]);
$clone
->setValue(array());
$this
->assertTrue($clone
->isEmpty());
// Make sure the difference between NULL (not set) and an empty array is
// kept.
$clone
->setValue(array());
$typed_data
->setValue(NULL);
$this
->assertNull($typed_data
->getValue());
$this
->assertIdentical($clone
->getValue(), array());
// Test dealing with NULL items.
$typed_data[] = NULL;
$this
->assertTrue($typed_data
->isEmpty());
$this
->assertEqual(count($typed_data), 1);
$typed_data[] = '';
$this
->assertFalse($typed_data
->isEmpty());
$this
->assertEqual(count($typed_data), 2);
$typed_data[] = 'three';
$this
->assertFalse($typed_data
->isEmpty());
$this
->assertEqual(count($typed_data), 3);
$this
->assertEqual($typed_data
->getValue(), array(
NULL,
'',
'three',
));
// Test unsetting.
unset($typed_data[2]);
$this
->assertEqual(count($typed_data), 2);
$this
->assertNull($typed_data[3]
->getValue());
// Getting a not set list item sets it.
$this
->assertNull($typed_data[4]
->getValue());
$this
->assertEqual(count($typed_data), 4);
// Test setting the list with less values.
$typed_data
->setValue(array(
'one',
));
$this
->assertEqual($typed_data
->count(), 1);
// Test setting invalid values.
try {
$typed_data
->setValue(array(
'not a list' => 'one',
));
$this
->fail('No exception has been thrown when setting an invalid value.');
} catch (\Exception $e) {
$this
->pass('Exception thrown:' . $e
->getMessage());
}
try {
$typed_data
->setValue('string');
$this
->fail('No exception has been thrown when setting an invalid value.');
} catch (\Exception $e) {
$this
->pass('Exception thrown:' . $e
->getMessage());
}
}