Last active
October 9, 2015 20:29
-
-
Save JoshuaEstes/420026cbcb2e04c73761 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace AppBundle\Form\DataMapper; | |
use Symfony\Component\Form\DataMapperInterface; | |
use Symfony\Component\Form\Exception\UnexpectedTypeException; | |
use Symfony\Component\Security\Core\User\UserInterface; | |
class UserSettingDataMapper implements DataMapperInterface | |
{ | |
public function mapDataToForms($data, $forms) | |
{ | |
if (!$data instanceof UserInterface) { | |
throw new UnexpectedTypeException($data, 'must be instance of Symfony\Component\Security\Core\User\UserInterface'); | |
} | |
foreach ($forms as $form) { | |
/** @var string */ | |
$key = $form->getName(); | |
/** @var \Symfony\Component\Form\FormConfigInterface */ | |
$config = $form->getConfig(); | |
/** @var boolean */ | |
$hasSetting = $data->hasSetting($key); | |
/** @var \AppBundle\Entity\UserSetting */ | |
$setting = $data->getSetting($key); | |
if ($hasSetting && $config->getMapped()) { | |
$form->setData($setting->getValue()); | |
} else { | |
$form->setData($config->setData()); | |
} | |
} | |
} | |
public function mapFormsToData($forms, $data) | |
{ | |
if (null === $data) { | |
return; | |
} | |
if (!$data instanceof UserInterface) { | |
throw new UnexpectedTypeException($data, 'must be instance of Symfony\Component\Security\Core\User\UserInterface'); | |
} | |
foreach ($forms as $form) { | |
/** @var string */ | |
$key = $form->getName(); | |
/** @var \Symfony\Component\Form\FormConfigInterface */ | |
$config = $form->getConfig(); | |
/** @var boolean */ | |
$hasSetting = $data->hasSetting($key); | |
/** @var \AppBundle\Entity\UserSetting */ | |
$setting = $data->getSetting($key); | |
if ($config->getMapped() && $form->isSubmitted() && $form->isSynchronized() && !$form->isDisabled()) { | |
if (null === $form->getData()) { | |
$data->removeSetting($setting); | |
} else { | |
$setting->setValue($form->getData()); | |
$data->addSetting($setting); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment