function ConfigTargetTest::testMultiTarget

Same name 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 \Drupal\Core\Form\ConfigTarget @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.