function TypedDataTest::testTypedDataListsFilter

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php \Drupal\KernelTests\Core\TypedData\TypedDataTest::testTypedDataListsFilter()
  2. 10 core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php \Drupal\KernelTests\Core\TypedData\TypedDataTest::testTypedDataListsFilter()
  3. 11.x core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php \Drupal\KernelTests\Core\TypedData\TypedDataTest::testTypedDataListsFilter()

Tests the filter() method on typed data lists.

File

core/tests/Drupal/KernelTests/Core/TypedData/TypedDataTest.php, line 438

Class

TypedDataTest
Tests the functionality of all core data types.

Namespace

Drupal\KernelTests\Core\TypedData

Code

public function testTypedDataListsFilter() {
    // Check that an all-pass filter leaves the list untouched.
    $value = [
        'zero',
        'one',
    ];
    $typed_data = $this->createTypedData(ListDataDefinition::create('string'), $value);
    $typed_data->filter(function (TypedDataInterface $item) {
        return TRUE;
    });
    $this->assertEqual($typed_data->count(), 2);
    $this->assertEqual($typed_data[0]->getValue(), 'zero');
    $this->assertEqual($typed_data[0]->getName(), 0);
    $this->assertEqual($typed_data[1]->getValue(), 'one');
    $this->assertEqual($typed_data[1]->getName(), 1);
    // Check that a none-pass filter empties the list.
    $value = [
        'zero',
        'one',
    ];
    $typed_data = $this->createTypedData(ListDataDefinition::create('string'), $value);
    $typed_data->filter(function (TypedDataInterface $item) {
        return FALSE;
    });
    $this->assertEqual($typed_data->count(), 0);
    // Check that filtering correctly renumbers elements.
    $value = [
        'zero',
        'one',
        'two',
    ];
    $typed_data = $this->createTypedData(ListDataDefinition::create('string'), $value);
    $typed_data->filter(function (TypedDataInterface $item) {
        return $item->getValue() !== 'one';
    });
    $this->assertEqual($typed_data->count(), 2);
    $this->assertEqual($typed_data[0]->getValue(), 'zero');
    $this->assertEqual($typed_data[0]->getName(), 0);
    $this->assertEqual($typed_data[1]->getValue(), 'two');
    $this->assertEqual($typed_data[1]->getName(), 1);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.