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 1 commit
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
Next Next commit
[Form] Add accessor data mapper for built-in DTO support
  • Loading branch information
alcaeus committed Jul 20, 2020
commit 7ca2f0b753a5f8372dfc7c669dfd439617602030
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,81 @@
<?php

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

use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;

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.

($this->set)($data, $form->getData());
}
}
}

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
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy