Skip to content

Instantly share code, notes, and snippets.

@JoshuaEstes
Last active October 9, 2015 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshuaEstes/420026cbcb2e04c73761 to your computer and use it in GitHub Desktop.
Save JoshuaEstes/420026cbcb2e04c73761 to your computer and use it in GitHub Desktop.
<?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