Add data transformation interface for filters

Introduced a new DataTransformerFilterInterface that allows transforming filter's form data before it is processed. Updated the FilterType file to add a view transformer if the filter implements this new interface. This new transformation process caters to transforming existing data in saved exports and replacing it with default values.
This commit is contained in:
Julien Fastré 2024-06-14 13:58:48 +02:00
parent 5ca222b501
commit 90b615c5b2
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB
3 changed files with 39 additions and 0 deletions

View File

@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Export;
/**
* Transform data from filter.
*
* This interface defines a method for transforming filter's form data before it is processed.
*
* You can implement this interface on @see{FilterInterface}, to allow to transform existing data in saved exports
* and replace it with some default values.
*/
interface DataTransformerFilterInterface
{
public function transformData(?array $before): array;
}

View File

@ -32,6 +32,9 @@ interface FilterInterface extends ModifierInterface
/** /**
* Get the default data, that can be use as "data" for the form. * Get the default data, that can be use as "data" for the form.
*
* In case of adding new parameters to a filter, you can implement a @see{DataTransformerFilterInterface} to
* transforme the filters's data saved in an export to the desired state.
*/ */
public function getFormDefaultData(): array; public function getFormDefaultData(): array;

View File

@ -11,8 +11,10 @@ declare(strict_types=1);
namespace Chill\MainBundle\Form\Type\Export; namespace Chill\MainBundle\Form\Type\Export;
use Chill\MainBundle\Export\DataTransformerFilterInterface;
use Chill\MainBundle\Export\FilterInterface; use Chill\MainBundle\Export\FilterInterface;
use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
@ -43,6 +45,15 @@ class FilterType extends AbstractType
]); ]);
$filter->buildForm($filterFormBuilder); $filter->buildForm($filterFormBuilder);
if ($filter instanceof DataTransformerFilterInterface) {
$filterFormBuilder->addViewTransformer(new CallbackTransformer(
fn (?array $data) => $data,
function (?array $data) use ($filter) {
return $filter->transformData($data);
},
));
}
$builder->add($filterFormBuilder); $builder->add($filterFormBuilder);
} }