Skip to content

[POC] [Form] Support get/set accessors for form fields #37614

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Symfony/Component/Form/Extension/Core/CoreExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface;
use Symfony\Component\Form\ChoiceList\Factory\DefaultChoiceListFactory;
use Symfony\Component\Form\ChoiceList\Factory\PropertyAccessDecorator;
use Symfony\Component\Form\Extension\Core\Type\AccessorMapperExtension;
use Symfony\Component\Form\Extension\Core\Type\TransformationFailureExtension;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
Expand Down Expand Up @@ -84,6 +85,7 @@ protected function loadTypeExtensions()
{
return [
new TransformationFailureExtension($this->translator),
new AccessorMapperExtension(),
];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
<?php

namespace Symfony\Component\Form\Extension\Core\DataMapper;

use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\ExceptionInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
use Symfony\Component\Form\FormError;
use TypeError;

class AccessorMapper implements DataMapperInterface
{
private $get;
private $set;
private $fallbackMapper;

public function __construct(?\Closure $get, ?\Closure $set, DataMapperInterface $fallbackMapper)
{
$this->get = $get;
$this->set = $set;
$this->fallbackMapper = $fallbackMapper;
}

/**
* {@inheritdoc}
*/
public function mapDataToForms($data, iterable $forms)
{
$empty = null === $data || [] === $data;

if (!$empty && !\is_array($data) && !\is_object($data)) {
throw new UnexpectedTypeException($data, 'object, array or empty');
}

if (!$this->get) {
$this->fallbackMapper->mapDataToForms($data, $forms);
return;
}

foreach ($forms as $form) {
$config = $form->getConfig();

if (!$empty && $config->getMapped()) {
$form->setData($this->getPropertyValue($data));
} else {
$form->setData($config->getData());
}
}
}

/**
* {@inheritdoc}
*/
public function mapFormsToData(iterable $forms, &$data)
{
if (null === $data) {
return;
}

if (!\is_array($data) && !\is_object($data)) {
throw new UnexpectedTypeException($data, 'object, array or empty');
}

if (!$this->set) {
$this->fallbackMapper->mapFormsToData($forms, $data);
return;
}

foreach ($forms as $form) {
$config = $form->getConfig();

// Write-back is disabled if the form is not synchronized (transformation failed),
// if the form was not submitted and if the form is disabled (modification not allowed)
if (null !== $this->set && $config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It shouldn't be possible for $this->set to be null as you checked it a few lines earlier (to fallback on the old datamapper).

Unless I read something wrong ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are correct. I'll update this.

try {
$returnValue = ($this->set)($data, $form->getData());
Copy link
Member

@yceruto yceruto Jul 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Given a compound form with two fields (let's say name and active, string and bool respectively) If I understand it correctly, the same 'set' accessor will be used for all (children) form data, is that expected? shouldn't the 'set' accessor of the current child be called instead?

Copy link
Member

@yceruto yceruto Jul 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically, I expected something like this $set = $form->getConfig()->getOption('set') somewhere. same for 'get' accessor.

} catch (ExceptionInterface | TypeError $e) {
$form->addError(new FormError($e->getMessage()));
continue;
}

$type = is_object($returnValue) ? get_class($returnValue) : gettype($returnValue);

if (
(is_scalar($data) && gettype($data) === $type)
|| (is_array($data) && is_array($returnValue))
|| (is_object($data) && $returnValue instanceof $type)) {
Copy link
Member

@yceruto yceruto Jul 25, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Immutability] We could also apply the same approach as data mappers but on the closure &$data and get rid of extra checks and rules in our side, so it's the user responsability and it'll work same:

$builder->add('name', null, [
    'set' => function(Category &$category, string $name) { 
        $category = $category->rename($name); 
    },
]);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting idea. Passing the argument by reference also makes it clearer that you are always modifying the data directly, apart from being consistent with the data mapper API.

$data = $returnValue;
}
}
}
}

private function getPropertyValue($data)
{
return $this->get ? ($this->get)($data) : null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Form\Extension\Core\Type;

use Closure;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\DataMapper\AccessorMapper;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class AccessorMapperExtension extends AbstractTypeExtension
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing service registration in FrameworkBundle/Resources/config/form.php

{
public function buildForm(FormBuilderInterface $builder, array $options)
{
if (!$options['get'] && !$options['set']) {
return;
}

if (!$dataMapper = $builder->getDataMapper()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By default, there is no data mapper bound to single form fields (see FormType, only compound forms will have a default data mapper), so the accessors configured for individual fields wouldn't work unless you call them from AccessorMapper, but that's not the case currently (related to previous comment).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The chicken and egg problem, if the parent (compound) form doesn't configure any accessor option then AccessorMapper won't be set.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, yes. I'll add some functional tests to cover this as well.

return;
}

$builder->setDataMapper(new AccessorMapper($options['get'], $options['set'], $dataMapper));
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'get' => null,
'set' => null,
]);

$resolver->setAllowedTypes('get', ['null', Closure::class]);
$resolver->setAllowedTypes('set', ['null', Closure::class]);
}

/**
* {@inheritdoc}
*/
public static function getExtendedTypes(): iterable
{
return [FormType::class];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@

namespace Symfony\Component\Form\Tests\Extension\Core;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use stdClass;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\Extension\Core\DataMapper\AccessorMapper;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormFactoryBuilder;

class CoreExtensionTest extends TestCase
Expand All @@ -30,4 +34,32 @@ public function testTransformationFailuresAreConvertedIntoFormErrors()

$this->assertFalse($form->isValid());
}

public function testMapperExtensionIsLoaded()
{
$formFactoryBuilder = new FormFactoryBuilder();
$formFactory = $formFactoryBuilder->addExtension(new CoreExtension())
->getFormFactory();

$mock = $this->getMockBuilder(stdClass::class)->addMethods(['get', 'set'])->getMock();
$mock->expects($this->once())->method('get')->willReturn('foo');
$mock->expects($this->once())->method('set')->with('bar');

$formBuilder = $formFactory->createBuilder();
$form = $formBuilder
->add(
'foo',
TextType::class
)
->setDataMapper(new AccessorMapper(
function (MockObject $data) { return $data->get(); },
function (MockObject $data, $value) { return $data->set($value); },
$formBuilder->getDataMapper()
))
->setData($mock)
->getForm();

$this->assertInstanceOf(AccessorMapper::class, $form->getConfig()->getDataMapper());
$form->submit(['foo' => 'bar']);
}
}
Loading