fix cs and add EntityToIdTransformer

This commit is contained in:
2022-05-20 15:52:02 +02:00
parent dba0e84781
commit b6e0379583
14 changed files with 308 additions and 97 deletions

View File

@@ -0,0 +1,82 @@
<?php
/**
* 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.
*/
declare(strict_types=1);
namespace Chill\MainBundle\Form\DataTransformer;
use Closure;
use Doctrine\Persistence\ObjectRepository;
use Symfony\Component\Form\DataTransformerInterface;
use function call_user_func;
/**
* @template T
*/
class IdToEntityDataTransformer implements DataTransformerInterface
{
private Closure $getId;
private bool $multiple = false;
private ObjectRepository $repository;
/**
* @param Closure $getId
*/
public function __construct(ObjectRepository $repository, bool $multiple = false, ?callable $getId = null)
{
$this->repository = $repository;
$this->multiple = $multiple;
$this->getId = $getId ?? static function (object $o) { return $o->getId(); };
}
/**
* @param string $value
*
* @return array|object[]|T[]|T|object
*/
public function reverseTransform($value)
{
if ($this->multiple) {
if (null === $value | '' === $value) {
return [];
}
return array_map(
fn (string $id): ?object => $this->repository->findOneBy(['id' => (int) $id]),
explode(',', $value)
);
}
if (null === $value | '' === $value) {
return null;
}
return $this->repository->findOneBy(['id' => (int) $value]);
}
/**
* @param object|T|object[]|T[] $value
*/
public function transform($value): string
{
if ($this->multiple) {
$ids = [];
foreach ($value as $v) {
$ids[] = call_user_func($this->getId, $v);
}
return implode(',', $ids);
}
return call_user_func($this->getId, $value);
}
}