mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-06-07 18:44:08 +00:00
88 lines
2.5 KiB
PHP
88 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace Chill\PersonBundle\Form\DataMapper;
|
|
|
|
use Symfony\Component\Form\DataMapperInterface;
|
|
use Doctrine\Common\Collections\ArrayCollection;
|
|
use Doctrine\Common\Collections\Collection;
|
|
use Symfony\Component\Form\Exception\UnexpectedTypeException;
|
|
use Chill\PersonBundle\Entity\PersonAltName;
|
|
|
|
/**
|
|
*
|
|
*
|
|
*/
|
|
class PersonAltNameDataMapper implements DataMapperInterface
|
|
{
|
|
public function mapDataToForms($viewData, $forms)
|
|
{
|
|
if (null === $viewData) {
|
|
return;
|
|
}
|
|
|
|
if (!$viewData instanceof Collection) {
|
|
throw new UnexpectedTypeException($viewData, Collection::class);
|
|
}
|
|
|
|
$mapIndexToKey = [];
|
|
foreach ($viewData->getIterator() as $key => $altName) {
|
|
/** @var PersonAltName $altName */
|
|
$mapIndexToKey[$altName->getKey()] = $key;
|
|
}
|
|
|
|
foreach ($forms as $key => $form) {
|
|
if (\array_key_exists($key, $mapIndexToKey)) {
|
|
$form->setData($viewData->get($mapIndexToKey[$key])->getLabel());
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @param FormInterface[] $forms
|
|
* @param Collection $viewData
|
|
*/
|
|
public function mapFormsToData($forms, &$viewData)
|
|
{
|
|
$mapIndexToKey = [];
|
|
|
|
if (is_array($viewData)) {
|
|
$dataIterator = $viewData;
|
|
} else {
|
|
$dataIterator = $viewData instanceof ArrayCollection ?
|
|
$viewData->toArray() : $viewData->getIterator();
|
|
}
|
|
|
|
foreach ($dataIterator as $key => $altName) {
|
|
/** @var PersonAltName $altName */
|
|
$mapIndexToKey[$altName->getKey()] = $key;
|
|
}
|
|
|
|
foreach ($forms as $key => $form) {
|
|
$isEmpty = empty($form->getData());
|
|
|
|
if (\array_key_exists($key, $mapIndexToKey)) {
|
|
if ($isEmpty) {
|
|
$viewData->remove($mapIndexToKey[$key]);
|
|
} else {
|
|
$viewData->get($mapIndexToKey[$key])->setLabel($form->getData());
|
|
}
|
|
} else {
|
|
if (!$isEmpty) {
|
|
$altName = (new PersonAltName())
|
|
->setKey($key)
|
|
->setLabel($form->getData())
|
|
;
|
|
|
|
if (is_array($viewData)) {
|
|
$viewData[] = $altName;
|
|
} else {
|
|
$viewData->add($altName);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|