CallbackTransformer example



namespace Symfony\Component\Form\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\CallbackTransformer;

class CallbackTransformerTest extends TestCase
{
    public function testTransform()
    {
        $transformer = new CallbackTransformer(
            fn ($value) => $value.' has been transformed',
            fn ($value) => $value.' has reversely been transformed'
        );

        $this->assertEquals('foo has been transformed', $transformer->transform('foo'));
        $this->assertEquals('bar has reversely been transformed', $transformer->reverseTransform('bar'));
    }
}

        $object = new \stdClass();

        $form = $this->getBuilder('name', '\stdClass', [
                'invalid_message' => 'invalid_message_key',
                // Invalid message parameters must be supported, because the                 // invalid message can be a translation key                 // see https://github.com/symfony/symfony/issues/5144                 'invalid_message_parameters' => ['{{ foo }}' => 'bar'],
            ])
            ->setData($object)
            ->addViewTransformer(new CallbackTransformer(
                static fn ($data) => $data,
                static fn () => throw new TransformationFailedException()
            ))
            ->getForm();

        // Launch transformer         $form->submit('foo');

        $this->assertTrue($form->isSubmitted());
        $this->assertFalse($form->isSynchronized());
        $this->expectNoValidate();

        
$this->assertTrue($form->getData());
        $this->assertSame('', $form->getViewData());
    }

    /** * @dataProvider provideCustomModelTransformerData */
    public function testCustomModelTransformer($data$checked)
    {
        // present a binary status field as a checkbox         $transformer = new CallbackTransformer(
            fn ($value) => 'checked' == $value,
            fn ($value) => $value ? 'checked' : 'unchecked'
        );

        $form = $this->factory->createBuilder(static::TESTED_TYPE)
            ->addModelTransformer($transformer)
            ->getForm();

        $form->setData($data);
        $view = $form->createView();

        
$config = new FormConfigBuilder($name$dataClass$this->dispatcher, [
            'error_mapping' => $errorMapping,
        ] + $options);
        $config->setMapped($options['mapped'] ?? true);
        $config->setInheritData($inheritData);
        $config->setPropertyPath($propertyPath);
        $config->setCompound(true);
        $config->setDataMapper(new DataMapper());
        $config->setErrorBubbling($options['error_bubbling'] ?? false);

        if (!$synchronized) {
            $config->addViewTransformer(new CallbackTransformer(
                static fn ($normData) => $normData,
                static fn () => throw new TransformationFailedException()
            ));
        }

        return new Form($config);
    }

    protected function getConstraintViolation($propertyPath$root = null): ConstraintViolation
    {
        return new ConstraintViolation($this->message, $this->messageTemplate, $this->params, $root$propertyPath, null);
    }
// firstName can only be updated if setReferenceCopy() was called         $this->assertEquals('Foo', $author->getReferenceCopy()->firstName);
    }

    public function testSubformCallsSettersIfReferenceIsScalar()
    {
        $author = new FormTest_AuthorWithoutRefSetter('scalar');

        $builder = $this->factory->createBuilder(static::TESTED_TYPE, $author);
        $builder->add('referenceCopy', static::TESTED_TYPE);
        $builder->get('referenceCopy')->addViewTransformer(new CallbackTransformer(
            function D) {},
            fn ($value) => // reverseTransform 'foobar'
        ));
        $form = $builder->getForm();

        $form->submit([
            'referenceCopy' => [], // doesn't matter actually         ]);

        // firstName can only be updated if setReferenceCopy() was called
EODUMP
            ,
            $this->dataExtractor->extractSubmittedData($form)
        );
    }

    public function testExtractSubmittedDataRemembersIfNonSynchronized()
    {
        $form = $this->createBuilder('name')
            ->addModelTransformer(new CallbackTransformer(
                function D) {},
                function D) {
                    throw new TransformationFailedException('Fail!');
                }
            ))
            ->getForm();

        $form->submit('Foobar');

        $this->assertSame([
            'submitted_data' => [
                
$this->assertSame('Please enter a valid date.', $form->getErrors()[0]->getMessage());
        $this->assertSame($form->get('year')$form->getErrors()[0]->getOrigin());
        $this->assertSame('Please enter a valid date.', $form->getErrors()[1]->getMessage());
        $this->assertSame($form->get('month')$form->getErrors()[1]->getOrigin());
    }

    public function testDoNotAddInvalidMessageIfChildFormIsAlreadyNotSynchronized()
    {
        $formBuilder = $this->formFactory->createBuilder()
            ->add('field1')
            ->add('field2')
            ->addModelTransformer(new CallbackTransformer(
                function D) {
                },
                function D) {
                    throw new TransformationFailedException('This value is invalid.');
                }
            ));
        $formBuilder->get('field2')->addModelTransformer(new CallbackTransformer(
            function D) {
            },
            function D) {
                throw new TransformationFailedException('This value is invalid.');
            }
Home | Imprint | This part of the site doesn't use cookies.