chill-bundles/Form/DataMapper/AddressDataMapper.php

122 lines
3.9 KiB
PHP

<?php
/*
* Copyright (C) 2019 Champs Libres Cooperative <info@champs-libres.coop>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Chill\MainBundle\Form\DataMapper;
use Symfony\Component\Form\DataMapperInterface;
use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Entity\PostalCode;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Exception\UnexpectedTypeException;
/**
* Add a data mapper to Address.
*
* If the address is incomplete, the data mapper returns null
*/
class AddressDataMapper implements DataMapperInterface
{
/**
*
* @param Address $address
* @param \Iterator $forms
*/
public function mapDataToForms($address, $forms)
{
if (NULL === $address) {
return;
}
if (!$address instanceof Address) {
throw new UnexpectedTypeException($address, Address::class);
}
foreach ($forms as $key => $form) {
/** @var FormInterface $form */
switch ($key) {
case 'streetAddress1':
$form->setData($address->getStreetAddress1());
break;
case 'streetAddress2':
$form->setData($address->getStreetAddress2());
break;
case 'postCode':
$form->setData($address->getPostcode());
break;
case 'validFrom':
$form->setData($address->getValidFrom());
break;
case 'isNoAddress':
$form->setData($address->isNoAddress());
break;
default:
break;
}
}
}
/**
*
* @param \Iterator $forms
* @param Address $address
*/
public function mapFormsToData($forms, &$address)
{
if (!$address instanceof Address) {
$address = new Address();
}
$isNoAddress = false;
foreach ($forms as $key => $form) {
if ($key === 'isNoAddress') {
$isNoAddress = $form->get('isNoAddress')->getData();
}
}
foreach ($forms as $key => $form) {
/** @var FormInterface $form */
switch($key) {
case 'postCode':
if (!$form->getData() instanceof PostalCode && !$isNoAddress) {
$address = null;
return;
}
$address->setPostcode($form->getData());
break;
case 'streetAddress1':
if (empty($form->getData()) && !$isNoAddress) {
$address = null;
return;
}
$address->setStreetAddress1($form->getData());
break;
case 'streetAddress2':
$address->setStreetAddress2($form->getData());
break;
case 'validFrom':
$address->setValidFrom($form->getData());
break;
case 'isNoAddress':
$address->setIsNoAddress($form->getData());
break;
default:
break;
}
}
}
}