function ConfigTargetTest::testMultiTarget

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/Tests/Core/Form/ConfigTargetTest.php \Drupal\Tests\Core\Form\ConfigTargetTest::testMultiTarget()

File

core/tests/Drupal/Tests/Core/Form/ConfigTargetTest.php, line 304

Class

ConfigTargetTest
@coversDefaultClass <a href="/api/drupal/core%21lib%21Drupal%21Core%21Form%21ConfigTarget.php/class/ConfigTarget/10" title="Represents the mapping of a config property to a form element." class="local">\Drupal\Core\Form\ConfigTarget</a> @group Form

Namespace

Drupal\Tests\Core\Form

Code

public function testMultiTarget() : void {
    $config_target = new ConfigTarget('foo.settings', [
        'first',
        'second',
    ], fromConfig: fn(int $first, int $second): string => "{$first}|{$second}", toConfig: fn(string $form_value): array => [
        'first' => intval(explode('|', $form_value)[0]),
        'second' => intval(explode('|', $form_value)[1]),
    ]);
    // Assert the logic in the callables works as expected.
    $this->assertSame("42|-4", ($config_target->fromConfig)(42, -4));
    $this->assertSame([
        'first' => 9,
        'second' => 19,
    ], ($config_target->toConfig)("9|19"));
    // Now simulate how this will be used in the form, and ensure it results in
    // the expected Config::set() calls.
    $config = $this->prophesize(Config::class);
    $config->getName()
        ->willReturn('foo.settings');
    // First to transform the stored config value to the form value.
    $config->get('first')
        ->willReturn(-17);
    $config->get('second')
        ->willReturn(71);
    $this->assertSame("-17|71", $config_target->getValue($config->reveal()));
    // Then to transform the modified form value back to config.
    $config->set('first', 1988)
        ->shouldBeCalledTimes(1);
    $config->set('second', 1992)
        ->shouldBeCalledTimes(1);
    $config_target->setValue($config->reveal(), '1988|1992', $this->prophesize(FormStateInterface::class)
        ->reveal());
}

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